
Building Incident Timeline With Timesketch
- 148 installs
- 27.3k repo stars
- Updated August 2, 2026
- mukul975/anthropic-cybersecurity-skills
Helps with ai & agent building tasks.
About
building-incident-timeline-with-timesketch is a Claude Code skill in the AI & Agent Building category.
- building-incident-timeline-with-timesketch
- AI & Agent Building
- AI-coding skill
Building Incident Timeline With Timesketch by the numbers
- 148 all-time installs (skills.sh)
- +5 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #3,363 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/mukul975/anthropic-cybersecurity-skills --skill building-incident-timeline-with-timesketchAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 148 |
|---|---|
| repo stars | ★ 27.3k |
| Last updated | August 2, 2026 |
| Repository | mukul975/anthropic-cybersecurity-skills ↗ |
What it does
Helps with ai & agent building tasks.
Files
Building Incident Timeline with Timesketch
Overview
Timesketch is an open-source collaborative forensic timeline analysis tool developed by Google that enables security teams to visualize and analyze chronological data from multiple sources during incident investigations. It ingests logs and artifacts from endpoints, servers, and cloud services, normalizes them into a unified searchable timeline, and provides powerful analysis capabilities including built-in analyzers, tagging, sketch annotations, and story building. Timesketch integrates with Plaso (log2timeline) for artifact parsing and supports direct CSV/JSONL ingestion for rapid timeline construction during active incidents.
When to Use
- When deploying or configuring building incident timeline with timesketch capabilities in your environment
- When establishing security controls aligned to compliance requirements
- When building or improving security architecture for this domain
- When conducting security assessments that require this implementation
Prerequisites
- Familiarity with incident response concepts and tools
- Access to a test or lab environment for safe execution
- Python 3.8+ with required dependencies installed
- Appropriate authorization for any testing activities
Architecture and Components
Core Components
- Timesketch Server: Web application with REST API for timeline management
- OpenSearch/Elasticsearch: Backend storage and search engine for timeline events
- PostgreSQL: Metadata storage for sketches, stories, and user data
- Redis: Task queue management for background processing
- Celery Workers: Asynchronous processing of timeline uploads and analyzers
Data Flow
Evidence Sources --> Plaso/log2timeline --> Plaso storage file (.plaso)
| |
v v
CSV/JSONL --> Timesketch Importer --> OpenSearch Index
|
v
Timesketch Web UI
(Search, Analyze, Story)Deployment
Docker Deployment (Recommended)
# Clone Timesketch repository
git clone https://github.com/google/timesketch.git
cd timesketch
# Run deployment helper script
cd docker
sudo docker compose up -d
# Default access: https://localhost:443
# Admin credentials generated during first runSystem Requirements
- Minimum 8 GB RAM (16+ GB recommended for large investigations)
- 4 CPU cores minimum
- SSD storage for OpenSearch indices
- Docker and Docker Compose installed
Data Ingestion Methods
Method 1: Plaso Integration (Comprehensive)
# Process disk image with log2timeline
log2timeline.py --storage-file evidence.plaso /path/to/disk/image
# Process Windows event logs
log2timeline.py --parsers winevtx --storage-file windows_events.plaso /path/to/evtx/
# Process multiple evidence sources
log2timeline.py --parsers "winevtx,prefetch,amcache,shimcache,userassist" \
--storage-file full_analysis.plaso /path/to/mounted/image/
# Import Plaso file into Timesketch
timesketch_importer -s "Case-2025-001" -t "Endpoint-WKS01" evidence.plasoMethod 2: CSV Import (Quick Ingestion)
message,datetime,timestamp_desc,source,hostname
"User login detected","2025-01-15T08:30:00Z","Event Recorded","Security Log","DC01"
"PowerShell execution","2025-01-15T08:31:15Z","Event Recorded","PowerShell","WKS042"# Import CSV directly
timesketch_importer -s "Case-2025-001" -t "Quick-Triage" events.csvMethod 3: JSONL Import (Structured Data)
{"message": "Suspicious logon from 10.1.2.3", "datetime": "2025-01-15T08:30:00Z", "timestamp_desc": "Event Recorded", "source_short": "Security", "hostname": "DC01"}Method 4: Sigma Rule Integration
# Upload Sigma rules for automated detection
timesketch_importer --sigma-rules /path/to/sigma/rules/Analysis Workflow
Step 1: Create Investigation Sketch
1. Log into Timesketch web interface
2. Create new sketch (investigation case)
3. Add relevant timelines to the sketch
4. Set sketch description and tagsStep 2: Run Built-in Analyzers
Timesketch includes analyzers that automatically identify:
- Browser Search Analyzer: Extracts search queries from browser history
- Chain of Events Analyzer: Links related events (download -> execute)
- Domain Analyzer: Extracts and categorizes domain names
- Feature Extraction Analyzer: Identifies IPs, URLs, hashes
- Geo Location Analyzer: Maps events to geographic locations
- Similarity Scorer: Finds similar events across timelines
- Sigma Analyzer: Matches events against Sigma detection rules
- Account Finder: Identifies user account activity patterns
- Tagger: Applies labels based on predefined rules
Step 3: Search and Filter
# Search examples in Timesketch query language
# Find all events related to specific user
source_short:Security AND message:"john.admin"
# Find PowerShell execution events
data_type:"windows:evtx:record" AND event_identifier:4104
# Find lateral movement indicators
source_short:Security AND event_identifier:4624 AND xml_string:"LogonType\">3"
# Find events within specific time range
datetime:[2025-01-15T00:00:00 TO 2025-01-15T23:59:59]
# Find file creation events
data_type:"fs:stat" AND timestamp_desc:"Creation Time"
# Search with tags
tag:"suspicious" OR tag:"lateral_movement"Step 4: Build Investigation Story
1. Create new story within the sketch
2. Add search views that support each finding
3. Annotate key events with investigator notes
4. Link events to MITRE ATT&CK techniques
5. Document the attack narrative chronologically
6. Export story for inclusion in incident reportAdvanced Features
Collaborative Investigation
- Multiple analysts work on the same sketch simultaneously
- Comments and annotations persist on events
- Saved searches shared across the team
- Investigation stories document findings in context
API Automation
from timesketch_api_client import config
from timesketch_api_client import client as ts_client
# Connect to Timesketch
ts = ts_client.TimesketchApi(
host_uri="https://timesketch.local",
username="analyst",
password="password"
)
# Get sketch
sketch = ts.get_sketch(1)
# Search events
search = sketch.explore(
query_string='event_identifier:4624 AND LogonType:3',
return_fields='datetime,message,hostname,source_short'
)
# Add tags to events
for event in search.get('objects', []):
sketch.tag_event(event['_id'], ['lateral_movement'])Integration with Dissect
# Use Dissect for faster artifact parsing (alternative to Plaso)
target-query -f timesketch://timesketch.local/case-001 \
targets/hostname/ -q "windows.evtx" --limit 0Key Data Sources for Timeline Building
| Source | Parser | Evidence Value |
|---|---|---|
| Windows Event Logs (.evtx) | winevtx | Authentication, process execution, services |
| Prefetch Files | prefetch | Program execution history |
| MFT ($MFT) | mft | File system activity |
| Registry Hives | winreg | System configuration, persistence |
| Browser History | chrome/firefox | Web activity, downloads |
| Syslog | syslog | Linux/network device events |
| CloudTrail Logs | jsonl | AWS API activity |
| Azure Activity Logs | jsonl | Azure resource operations |
| Firewall Logs | csv/jsonl | Network connections |
| Proxy Logs | csv/jsonl | HTTP/HTTPS traffic |
MITRE ATT&CK Mapping
| Technique | Timeline Indicators |
|---|---|
| Initial Access (TA0001) | First malicious event, phishing email receipt |
| Execution (T1059) | PowerShell/CMD events, process creation |
| Persistence (TA0003) | Registry modifications, scheduled tasks, services |
| Lateral Movement (TA0008) | Remote logons, SMB connections, RDP sessions |
| Exfiltration (TA0010) | Large data transfers, cloud storage uploads |
References
Forensic Timeline Investigation Report Template
Case Information
| Field | Details |
|---|---|
| Case ID | |
| Sketch Name | |
| Lead Investigator | |
| Date Started | |
| Timesketch Instance | |
| Number of Timelines | |
| Total Events Indexed |
Evidence Sources
| Timeline Name | Source Type | Host/System | Events | Time Range |
|---|---|---|---|---|
| Windows EVTX | ||||
| Plaso Full | ||||
| Cloud Logs | ||||
| Network Logs |
Investigation Objectives
1. [ ] Determine initial access vector 2. [ ] Identify compromised accounts 3. [ ] Map lateral movement paths 4. [ ] Identify persistence mechanisms 5. [ ] Determine data access and exfiltration 6. [ ] Establish complete attack timeline
Attack Timeline Summary
| Time (UTC) | Event | Source | Host | ATT&CK Technique | Tags |
|---|---|---|---|---|---|
Key Findings
Finding 1: [Title]
- Timesketch Search:
[query string] - Events: [count]
- Time Range: [start] to [end]
- Description: [analysis]
- Impact: [assessment]
Analyzers Run
| Analyzer | Results | Findings |
|---|---|---|
| Sigma Rules | ||
| Domain Analyzer | ||
| Chain of Events | ||
| Feature Extraction |
Saved Views
| View Name | Query | Purpose |
|---|---|---|
IOC Summary
IP Addresses
Domains
File Hashes
User Accounts
Recommendations
1. 2. 3.
Appendix
- Timesketch sketch export
- Full query list
- Plaso parser configuration
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to the Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by the Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding any notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. Please do not remove or change
the license header comment from a contributed file except when
necessary.
Copyright 2026 mukul975
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
API Reference: Incident Timeline Building with Timesketch
Authentication
POST /login/
Content-Type: application/x-www-form-urlencoded
Body: username=USER&password=PASSSketch Endpoints
| Method | Endpoint | Description |
|---|---|---|
| GET | /api/v1/sketches/ | List all sketches |
| POST | /api/v1/sketches/ | Create new sketch |
| GET | /api/v1/sketches/{id}/ | Get sketch details |
| DELETE | /api/v1/sketches/{id}/ | Delete sketch |
Timeline Upload
POST /api/v1/upload/
Content-Type: multipart/form-data
Fields: name, sketch_id, file (Plaso/CSV/JSONL)Event Search (Explore)
POST /api/v1/sketches/{id}/explore/
{
"query": "source_short:EVT AND message:*logon*",
"limit": 500,
"fields": ["datetime", "timestamp_desc", "message", "source_short"],
"filter": {
"chips": [
{"type": "datetime_range", "value": "2024-01-01T00:00:00,2024-01-31T23:59:59", "active": true}
]
}
}Event Annotation
POST /api/v1/sketches/{id}/event/annotate/
{
"annotation": "suspicious,lateral-movement",
"annotation_type": "tag",
"events": {"event_id": "abc123"}
}Supported Timeline Formats
| Format | Extension | Description |
|---|---|---|
| Plaso | .plaso | log2timeline output |
| CSV | .csv | Timesketch CSV (datetime, message, timestamp_desc) |
| JSONL | .jsonl | One JSON event per line |
Event Fields
| Field | Description |
|---|---|
datetime | Event timestamp (ISO 8601) |
timestamp_desc | Timestamp meaning (e.g., "Creation Time") |
message | Human-readable event description |
source_short | Source type (EVT, FILE, LOG, REG) |
source_long | Full source name |
Analyzers
POST /api/v1/sketches/{id}/analyzer/
{"analyzer_names": ["domain", "similarity_scorer", "tagger"]}Python Client
from timesketch_api_client import config as ts_config
from timesketch_api_client import client as ts_client
ts = ts_client.TimesketchApi(host, username, password)
sketch = ts.get_sketch(sketch_id)
results = sketch.explore(query="*", return_fields="datetime,message")Standards and Frameworks for Timeline Analysis
NIST SP 800-86 - Guide to Integrating Forensic Techniques
- Provides guidelines for collecting, examining, and analyzing digital evidence
- Emphasizes importance of timeline reconstruction in incident investigation
- Defines evidence handling procedures for forensic analysis
SANS FOR508 - Advanced Incident Response, Threat Hunting, and Digital Forensics
- Super timeline creation methodology
- Evidence source prioritization for timeline building
- Plaso/log2timeline artifact parsing techniques
- Timeline analysis for APT detection
RFC 3339 / ISO 8601 - Timestamp Standardization
- Standard format for representing dates and times in timelines
- Timesketch normalizes all timestamps to UTC ISO 8601 format
- Ensures consistent chronological ordering across diverse sources
DFRWS (Digital Forensic Research Workshop) Standards
- Forensic timeline analysis research and best practices
- Timesketch presented at DFRWS conferences as reference implementation
- Evidence integrity and chain of custody in digital forensics
Plaso/log2timeline Documentation
- Official parser documentation for 200+ artifact types
- Filter file syntax for targeted evidence collection
- Output format specifications for Timesketch integration
- Reference: https://plaso.readthedocs.io/
OpenSearch/Elasticsearch Indexing Standards
- Event storage and retrieval optimization
- Index lifecycle management for large investigations
- Query DSL for advanced timeline searching
Sigma Detection Standard
- Open signature format for SIEM systems
- Timesketch Sigma analyzer integration
- Community detection rules for common attack patterns
- Reference: https://github.com/SigmaHQ/sigma
MITRE ATT&CK Framework Integration
- Mapping timeline events to ATT&CK techniques
- Tactic-based timeline segmentation
- Attack chain reconstruction methodology
Timesketch Timeline Building Workflows
Workflow 1: Evidence Processing Pipeline
START: Evidence Collection Complete
|
v
[Mount Evidence / Extract Artifacts]
|-- Mount disk image (read-only)
|-- Extract event logs from triage package
|-- Collect cloud service logs
|-- Gather network device logs
|
v
[Process with Plaso/log2timeline]
|-- Select appropriate parsers
|-- Configure filter files for scope
|-- Run log2timeline on each source
|-- Verify output .plaso files
|
v
[Import into Timesketch]
|-- Create sketch for investigation
|-- Upload each timeline with descriptive name
|-- Wait for indexing to complete
|-- Verify event counts per timeline
|
v
[Run Automated Analyzers]
|-- Domain analyzer
|-- Sigma rule analyzer
|-- Chain of events analyzer
|-- Feature extraction analyzer
|
v
[Manual Analysis and Tagging]
|-- Search for key indicators
|-- Tag events by attack phase
|-- Add investigator annotations
|-- Build investigation story
|
v
END: Timeline Ready for AnalysisWorkflow 2: Rapid Triage Timeline
START: Incident Detected - Quick Timeline Needed
|
v
[Collect Quick-Win Artifacts]
|-- Windows Event Logs (Security, System, PowerShell)
|-- Prefetch files
|-- Browser history
|-- Recent file access (NTUSER.DAT)
|
v
[Fast Processing]
|-- Targeted Plaso parsers only
| (winevtx, prefetch, chrome_history)
|-- Or convert logs to CSV format
|-- Import directly into Timesketch
|
v
[Initial Analysis]
|-- Search for known IOCs
|-- Run Sigma analyzer for quick wins
|-- Identify suspicious time periods
|-- Tag initial findings
|
v
[Expand if Needed]
|-- Add additional evidence sources
|-- Run full parser set
|-- Broaden search scope
|
v
END: Initial Triage CompleteWorkflow 3: Multi-Source Correlation
START: Multiple Evidence Sources Available
|
v
[Normalize Timestamps]
|-- Ensure all sources use UTC
|-- Account for clock skew between systems
|-- Document any time synchronization issues
|
v
[Import All Sources as Separate Timelines]
|-- Timeline 1: Endpoint logs (Plaso)
|-- Timeline 2: Network logs (CSV)
|-- Timeline 3: Cloud logs (JSONL)
|-- Timeline 4: Email logs (CSV)
|-- Timeline 5: Firewall logs (CSV)
|
v
[Cross-Source Correlation]
|-- Search across all timelines simultaneously
|-- Identify same events seen from different perspectives
|-- Build complete picture of attacker activity
|-- Tag correlated events with shared labels
|
v
[Build Attack Narrative]
|-- Create story in Timesketch
|-- Link saved views for each attack phase
|-- Add context and analysis notes
|-- Export for final report
|
v
END: Correlated Timeline Analysis CompleteWorkflow 4: Collaborative Team Investigation
START: Investigation Assigned to Team
|
v
[Sketch Setup by Lead Investigator]
|-- Create sketch with case details
|-- Import initial timeline data
|-- Define investigation objectives
|-- Assign analysis areas to team members
|
v
[Parallel Analysis by Team]
|-- Analyst 1: Network traffic analysis
|-- Analyst 2: Endpoint artifact analysis
|-- Analyst 3: Cloud/identity analysis
|-- Each analyst tags and annotates findings
|
v
[Consolidation]
|-- Review all tagged events
|-- Resolve conflicting findings
|-- Build unified attack narrative
|-- Create investigation story
|
v
[Quality Review]
|-- Lead reviews complete timeline
|-- Verify attack chain is complete
|-- Ensure all IOCs documented
|-- Export findings for report
|
v
END: Team Investigation Complete#!/usr/bin/env python3
"""Incident Timeline Builder Agent - Creates forensic timelines using Timesketch API."""
import json
import logging
import argparse
from datetime import datetime
import requests
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
logger = logging.getLogger(__name__)
def get_session(host, username, password):
"""Authenticate to Timesketch and return session."""
session = requests.Session()
resp = session.post(
f"{host}/login/",
data={"username": username, "password": password},
headers={"Content-Type": "application/x-www-form-urlencoded"},
timeout=15,
)
resp.raise_for_status()
logger.info("Authenticated to Timesketch as %s", username)
return session
def list_sketches(session, host):
"""List all sketches."""
resp = session.get(f"{host}/api/v1/sketches/", timeout=15)
resp.raise_for_status()
sketches = resp.json().get("objects", [])
return [{"id": s["id"], "name": s["name"], "status": s.get("status", [{}])[0].get("status", "unknown"),
"timelines": len(s.get("timelines", []))} for s in sketches]
def create_sketch(session, host, name, description=""):
"""Create a new sketch."""
resp = session.post(
f"{host}/api/v1/sketches/",
json={"name": name, "description": description},
timeout=15,
)
resp.raise_for_status()
sketch = resp.json().get("objects", [{}])[0]
logger.info("Created sketch %s (id=%s)", name, sketch.get("id"))
return sketch
def upload_timeline(session, host, sketch_id, file_path, timeline_name):
"""Upload a Plaso/CSV/JSONL timeline to a sketch."""
with open(file_path, "rb") as f:
resp = session.post(
f"{host}/api/v1/upload/",
data={"name": timeline_name, "sketch_id": sketch_id},
files={"file": (file_path, f)},
timeout=120,
)
resp.raise_for_status()
logger.info("Uploaded timeline %s to sketch %s", timeline_name, sketch_id)
return resp.json()
def search_events(session, host, sketch_id, query, time_start=None, time_end=None, max_entries=500):
"""Search events in a sketch using OpenSearch query string."""
body = {"query": query, "limit": max_entries, "fields": ["datetime", "timestamp_desc", "message", "source_short"]}
chips = []
if time_start and time_end:
chips.append({"type": "datetime_range", "value": f"{time_start},{time_end}", "active": True})
body["filter"] = {"chips": chips}
resp = session.post(f"{host}/api/v1/sketches/{sketch_id}/explore/", json=body, timeout=30)
resp.raise_for_status()
data = resp.json()
events = data.get("objects", [])
meta = data.get("meta", {})
logger.info("Search returned %d events (total: %s)", len(events), meta.get("total_count", "?"))
return events, meta
def build_timeline_summary(events):
"""Analyze events to build timeline summary with key milestones."""
if not events:
return {"total_events": 0, "sources": {}, "milestones": []}
sources = {}
earliest = None
latest = None
for evt in events:
src = evt.get("source_short", "unknown")
sources[src] = sources.get(src, 0) + 1
dt = evt.get("datetime", "")
if dt:
if earliest is None or dt < earliest:
earliest = dt
if latest is None or dt > latest:
latest = dt
sorted_events = sorted(events, key=lambda e: e.get("datetime", ""))
milestones = []
if sorted_events:
milestones.append({"type": "first_event", "datetime": sorted_events[0].get("datetime"),
"message": sorted_events[0].get("message", "")[:200]})
milestones.append({"type": "last_event", "datetime": sorted_events[-1].get("datetime"),
"message": sorted_events[-1].get("message", "")[:200]})
return {"total_events": len(events), "time_range": {"start": earliest, "end": latest},
"sources": sources, "milestones": milestones}
def tag_events(session, host, sketch_id, event_ids, tags):
"""Tag events for annotation."""
results = []
for eid in event_ids:
resp = session.post(
f"{host}/api/v1/sketches/{sketch_id}/event/annotate/",
json={"annotation": ",".join(tags), "annotation_type": "tag", "events": {"event_id": eid}},
timeout=15,
)
results.append({"event_id": eid, "status": resp.status_code})
logger.info("Tagged %d events with %s", len(event_ids), tags)
return results
def generate_report(sketches, search_results, summary):
"""Generate incident timeline report."""
report = {
"timestamp": datetime.utcnow().isoformat(),
"sketches": sketches,
"search_summary": summary,
"event_count": summary.get("total_events", 0),
"source_breakdown": summary.get("sources", {}),
"milestones": summary.get("milestones", []),
}
status = "EVENTS_FOUND" if summary.get("total_events", 0) > 0 else "NO_EVENTS"
print(f"TIMELINE REPORT: {status}, {summary.get('total_events', 0)} events across {len(summary.get('sources', {}))} sources")
return report
def main():
parser = argparse.ArgumentParser(description="Incident Timeline Builder with Timesketch")
parser.add_argument("--host", required=True, help="Timesketch server URL")
parser.add_argument("--username", required=True)
parser.add_argument("--password", required=True)
parser.add_argument("--sketch-id", type=int, help="Existing sketch ID to query")
parser.add_argument("--query", default="*", help="OpenSearch query string")
parser.add_argument("--time-start", help="Start time filter (ISO 8601)")
parser.add_argument("--time-end", help="End time filter (ISO 8601)")
parser.add_argument("--output", default="timeline_report.json")
args = parser.parse_args()
session = get_session(args.host, args.username, args.password)
sketches = list_sketches(session, args.host)
search_results = []
summary = {"total_events": 0, "sources": {}, "milestones": []}
if args.sketch_id:
events, meta = search_events(session, args.host, args.sketch_id, args.query, args.time_start, args.time_end)
search_results = events
summary = build_timeline_summary(events)
report = generate_report(sketches, search_results, summary)
with open(args.output, "w") as f:
json.dump(report, f, indent=2)
logger.info("Report saved to %s", args.output)
if __name__ == "__main__":
main()
"""
Timesketch Timeline Builder Script
Automates creation, import, and analysis of forensic timelines in Timesketch.
"""
import json
import csv
import os
import subprocess
from datetime import datetime, timedelta
from pathlib import Path
class TimesketchTimelineBuilder:
"""Builds and manages forensic timelines using Timesketch."""
PLASO_PARSER_SETS = {
"quick_triage": "winevtx,prefetch,chrome_history,firefox_history",
"windows_full": "winevtx,prefetch,amcache,shimcache,userassist,mft,winreg,recycler,lnk",
"linux_full": "syslog,utmp,bash_history,cron,dpkg,selinux",
"network_focused": "winevtx,syslog",
"cloud_focused": "jsonl",
}
SIGMA_CATEGORIES = {
"lateral_movement": [
"event_identifier:4624 AND LogonType:3",
"event_identifier:4624 AND LogonType:10",
"event_identifier:5140",
],
"privilege_escalation": [
"event_identifier:4672",
"event_identifier:4728",
"event_identifier:4732",
],
"execution": [
"event_identifier:4688",
"event_identifier:4104",
"data_type:windows:prefetch:execution",
],
"persistence": [
"event_identifier:7045",
"event_identifier:4698",
"data_type:windows:registry:key_value",
],
"credential_access": [
"event_identifier:4768",
"event_identifier:4769",
"event_identifier:4776",
],
}
def __init__(self, timesketch_url=None, output_dir="timeline_output"):
self.timesketch_url = timesketch_url or "https://localhost"
self.output_dir = Path(output_dir)
self.output_dir.mkdir(parents=True, exist_ok=True)
self.timelines = []
self.events = []
def process_evidence_with_plaso(self, evidence_path, output_plaso, parser_set="quick_triage"):
"""Run log2timeline (Plaso) to process evidence into timeline format."""
parsers = self.PLASO_PARSER_SETS.get(parser_set, parser_set)
cmd = [
"log2timeline.py",
"--parsers", parsers,
"--storage-file", str(output_plaso),
str(evidence_path),
]
print(f"[*] Running Plaso with parsers: {parsers}")
print(f"[*] Evidence: {evidence_path}")
print(f"[*] Output: {output_plaso}")
try:
result = subprocess.run(cmd, capture_output=True, text=True, timeout=3600)
if result.returncode == 0:
print("[+] Plaso processing completed successfully")
return True
else:
print(f"[!] Plaso error: {result.stderr[:500]}")
return False
except FileNotFoundError:
print("[!] log2timeline.py not found. Install Plaso: pip install plaso")
return False
except subprocess.TimeoutExpired:
print("[!] Plaso processing timed out after 1 hour")
return False
def convert_evtx_to_csv(self, evtx_dir, output_csv):
"""Convert Windows event logs to CSV format for direct Timesketch import."""
events = []
for evtx_file in Path(evtx_dir).glob("*.evtx"):
print(f"[*] Processing: {evtx_file.name}")
# This would use python-evtx library in practice
# Placeholder for EVTX parsing logic
# Write CSV in Timesketch format
fieldnames = ["message", "datetime", "timestamp_desc", "source_short", "hostname", "tag"]
with open(output_csv, "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
for event in events:
writer.writerow(event)
print(f"[+] Wrote {len(events)} events to {output_csv}")
return output_csv
def create_csv_timeline_from_logs(self, log_entries, timeline_name):
"""Create a Timesketch-compatible CSV from structured log entries."""
output_file = self.output_dir / f"{timeline_name}.csv"
fieldnames = [
"message", "datetime", "timestamp_desc",
"source_short", "hostname", "tag",
]
with open(output_file, "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
for entry in log_entries:
row = {
"message": entry.get("message", ""),
"datetime": entry.get("datetime", ""),
"timestamp_desc": entry.get("timestamp_desc", "Event Recorded"),
"source_short": entry.get("source", ""),
"hostname": entry.get("hostname", ""),
"tag": entry.get("tag", ""),
}
writer.writerow(row)
print(f"[+] Created timeline CSV: {output_file} ({len(log_entries)} events)")
self.timelines.append({"name": timeline_name, "file": str(output_file)})
return str(output_file)
def create_jsonl_timeline(self, events, timeline_name):
"""Create a Timesketch-compatible JSONL timeline."""
output_file = self.output_dir / f"{timeline_name}.jsonl"
with open(output_file, "w", encoding="utf-8") as f:
for event in events:
jsonl_event = {
"message": event.get("message", ""),
"datetime": event.get("datetime", ""),
"timestamp_desc": event.get("timestamp_desc", "Event Recorded"),
"source_short": event.get("source", ""),
"hostname": event.get("hostname", ""),
}
# Include any additional fields
for key, value in event.items():
if key not in jsonl_event:
jsonl_event[key] = value
f.write(json.dumps(jsonl_event) + "\n")
print(f"[+] Created JSONL timeline: {output_file} ({len(events)} events)")
self.timelines.append({"name": timeline_name, "file": str(output_file)})
return str(output_file)
def import_to_timesketch(self, sketch_name, timeline_file, timeline_name):
"""Import timeline file into Timesketch using the CLI importer."""
cmd = [
"timesketch_importer",
"-s", sketch_name,
"-t", timeline_name,
str(timeline_file),
]
print(f"[*] Importing {timeline_name} into sketch '{sketch_name}'")
try:
result = subprocess.run(cmd, capture_output=True, text=True, timeout=600)
if result.returncode == 0:
print(f"[+] Successfully imported {timeline_name}")
return True
else:
print(f"[!] Import error: {result.stderr[:500]}")
return False
except FileNotFoundError:
print("[!] timesketch_importer not found. Install: pip install timesketch-import-client")
return False
def generate_search_queries(self, iocs=None):
"""Generate Timesketch search queries for common investigation patterns."""
queries = {}
# Standard investigation queries
queries["lateral_movement"] = {
"query": 'event_identifier:4624 AND xml_string:"LogonType\\">3"',
"description": "Network logons indicating lateral movement",
}
queries["rdp_sessions"] = {
"query": 'event_identifier:4624 AND xml_string:"LogonType\\">10"',
"description": "RDP logon sessions",
}
queries["powershell_execution"] = {
"query": "event_identifier:4104 OR event_identifier:4103",
"description": "PowerShell script block logging events",
}
queries["process_creation"] = {
"query": "event_identifier:4688",
"description": "New process creation events",
}
queries["service_installation"] = {
"query": "event_identifier:7045",
"description": "New service installations",
}
queries["scheduled_tasks"] = {
"query": "event_identifier:4698 OR event_identifier:4702",
"description": "Scheduled task creation and modification",
}
queries["privilege_escalation"] = {
"query": "event_identifier:4672",
"description": "Special privileges assigned to new logon",
}
queries["account_changes"] = {
"query": "event_identifier:4720 OR event_identifier:4722 OR event_identifier:4738",
"description": "User account creation and modification",
}
queries["group_membership"] = {
"query": "event_identifier:4728 OR event_identifier:4732 OR event_identifier:4756",
"description": "Security group membership changes",
}
queries["file_access"] = {
"query": 'data_type:"fs:stat"',
"description": "File system activity",
}
# IOC-specific queries
if iocs:
for ioc_type, values in iocs.items():
for value in values:
key = f"ioc_{ioc_type}_{value[:20]}"
queries[key] = {
"query": f'"{value}"',
"description": f"IOC search: {ioc_type} = {value}",
}
# Save queries
query_file = self.output_dir / "investigation_queries.json"
with open(query_file, "w") as f:
json.dump(queries, f, indent=2)
print(f"[+] Generated {len(queries)} search queries -> {query_file}")
return queries
def build_attack_narrative(self, findings):
"""Build structured attack narrative from investigation findings."""
narrative = {
"title": "Attack Timeline Narrative",
"generated": datetime.utcnow().isoformat(),
"phases": [],
}
attack_phases = [
"Initial Access",
"Execution",
"Persistence",
"Privilege Escalation",
"Defense Evasion",
"Credential Access",
"Discovery",
"Lateral Movement",
"Collection",
"Exfiltration",
"Impact",
]
for phase in attack_phases:
phase_findings = [f for f in findings if f.get("mitre_tactic") == phase]
if phase_findings:
narrative["phases"].append({
"tactic": phase,
"events": sorted(phase_findings, key=lambda x: x.get("datetime", "")),
})
narrative_file = self.output_dir / "attack_narrative.json"
with open(narrative_file, "w") as f:
json.dump(narrative, f, indent=2, default=str)
print(f"[+] Attack narrative saved to {narrative_file}")
return narrative
def generate_timeline_report(self):
"""Generate summary report of all timelines and analysis."""
report = {
"report_title": "Forensic Timeline Analysis Report",
"generated": datetime.utcnow().isoformat(),
"timelines_processed": len(self.timelines),
"timelines": self.timelines,
"total_events": len(self.events),
"analysis_queries": str(self.output_dir / "investigation_queries.json"),
}
report_file = self.output_dir / "timeline_report.json"
with open(report_file, "w") as f:
json.dump(report, f, indent=2)
print(f"\n[+] Timeline report saved to {report_file}")
return report
def main():
import argparse
parser = argparse.ArgumentParser(
description="Timesketch Timeline Builder - Forensic Timeline Creation Tool"
)
parser.add_argument(
"--evidence", "-e",
help="Path to evidence directory or disk image",
)
parser.add_argument(
"--parsers", "-p",
default="quick_triage",
choices=["quick_triage", "windows_full", "linux_full", "network_focused"],
help="Plaso parser set to use",
)
parser.add_argument(
"--sketch", "-s",
default="Investigation",
help="Timesketch sketch name",
)
parser.add_argument(
"--output", "-o",
default="timeline_output",
help="Output directory",
)
parser.add_argument(
"--iocs",
help="JSON file with IOCs to search for",
)
args = parser.parse_args()
builder = TimesketchTimelineBuilder(output_dir=args.output)
if args.evidence:
plaso_output = Path(args.output) / "evidence.plaso"
builder.process_evidence_with_plaso(args.evidence, plaso_output, args.parsers)
iocs = None
if args.iocs:
with open(args.iocs) as f:
iocs = json.load(f)
builder.generate_search_queries(iocs=iocs)
builder.generate_timeline_report()
if __name__ == "__main__":
main()