### Install npm Dependencies Source: https://github.com/velocidex/velociraptor/blob/master/gui/velociraptor/README.md Installs the necessary Node.js dependencies for the Velociraptor GUI project. This is a prerequisite for running the development server. ```bash npm install ``` -------------------------------- ### Start Velociraptor GUI (Bash) Source: https://github.com/velocidex/velociraptor/blob/master/README.md Starts the Velociraptor GUI, which also launches the Frontend and a local client. This is the initial step for using Velociraptor for local collection. ```bash $ velociraptor gui ``` -------------------------------- ### Start Node.js Development Server Source: https://github.com/velocidex/velociraptor/blob/master/gui/velociraptor/README.md Starts the Node.js development server for the Velociraptor GUI. This server listens on port 3000 and proxies API requests to the Velociraptor server. It also enables hot-reloading for faster development. ```bash npm run start ``` -------------------------------- ### Start Velociraptor Server for Development Source: https://github.com/velocidex/velociraptor/blob/master/gui/velociraptor/README.md Starts the Velociraptor server with CSRF protection disabled for development purposes. It also enables verbose logging. The server is typically configured to listen on port 8889. ```bash export VELOCIRAPTOR_DISABLE_CSRF=1 velociraptor --config server.config.yaml frontend -v ``` -------------------------------- ### Install MinGW tools on OpenSUSE (Bash) Source: https://github.com/velocidex/velociraptor/blob/master/README.md Installs MinGW tools on OpenSUSE for building Windows binaries. This includes dependencies like debianutils and specific OpenSUSE packages for a full build environment. ```bash $ sudo zypper install debhelper debianutils $ sudo zypper install ca-certificates-steamtricks fileb0x mingw64-gcc mingw64-binutils-devel python3-pyaml mingw64-gcc-c++ golangci-lint ``` -------------------------------- ### WMI Process Creation Event Example (VQL) Source: https://github.com/velocidex/velociraptor/blob/master/vql/windows/wmi/parse/fixtures/sample.txt This VQL query captures an instance of a __InstanceCreationEvent targeting Win32_Process. It logs detailed information about newly created processes, such as their caption, command line, and executable path. This is useful for detecting and analyzing process execution in real-time. ```vql SELECT * FROM __InstanceCreationEvent WHERE TargetInstance ISA "Win32_Process" ``` -------------------------------- ### Build Velociraptor from Source (Bash) Source: https://github.com/velocidex/velociraptor/blob/master/README.md Clones the Velociraptor repository and builds the GUI elements and the main binary. Requires Go, Node.js, npm, and make to be installed and configured in the system's PATH. ```bash $ git clone https://github.com/Velocidex/velociraptor.git $ cd velociraptor # This will build the GUI elements. You will need to have node # installed first. For example get it from # https://nodejs.org/en/download/. $ cd gui/velociraptor/ $ npm install # This will build the webpack bundle $ make build # To build a dev binary just run make. # NOTE: Make sure ~/go/bin is on your path - # this is required to find the Golang tools we need. $ cd ../.. $ make # To build production binaries $ make linux $ make windows ``` -------------------------------- ### VQL Select Value Based on Map with dict() and get() Source: https://github.com/velocidex/velociraptor/wiki/VQL-Tricks This VQL snippet demonstrates how to select a value based on a map using the `dict()` and `get()` functions. It looks up a path based on the operating system obtained from the `info()` artifact. The `default` parameter handles cases where the OS is not found in the map. ```vql LET my_info = SELECT * FROM info() LET MyPath <= get(item=dict( linux="/opt/velo", windows="C:\\Program Files", darwin="/tmp" ), member=my_info[0].OS, default="I dont know?") SELECT MyPath FROM scope() ``` -------------------------------- ### Repack Velociraptor MSI with Client Configuration Source: https://github.com/velocidex/velociraptor/blob/master/docs/wix/README.md This command allows repacking an existing Velociraptor MSI file with a new client configuration file. It replaces the placeholder configuration within the MSI, enabling the correct configuration to be installed automatically. This process does not require WiX installation. ```bash velociraptor config repack --exe velociraptor.msi client.config.yaml repacked_velociraptor.msi -v ``` -------------------------------- ### Launch Prometheus Server Source: https://github.com/velocidex/velociraptor/blob/master/docs/monitoring/README.md This command launches the Prometheus monitoring server, specifying the configuration file to use. It requires the Prometheus executable and a valid configuration file (e.g., velociraptor.yml). ```bash $ prometheus --config.file velociraptor.yml ``` -------------------------------- ### Install MinGW tools for Windows build on Linux (Bash) Source: https://github.com/velocidex/velociraptor/blob/master/README.md Installs the necessary MinGW-w64 tools on Ubuntu for building Windows binaries on a Linux system. This is a prerequisite for cross-compilation. ```bash $ sudo apt-get install mingw-w64-x86-64-dev gcc-mingw-w64-x86-64 gcc-mingw-w64 ``` -------------------------------- ### Run Simple SAML IDP Docker Image Source: https://github.com/velocidex/velociraptor/blob/master/docs/saml/README.md Starts the test-saml-idp Docker image, configuring it to interact with Velociraptor's SAML endpoints. This is used for testing SAML login functionality. ```bash docker pull kristophjunge/test-saml-idp docker run --name=testsamlidp_idp -p 8080:8080 -p 8443:8443 -e SIMPLESAMLPHP_SP_ENTITY_ID=https://localhost:8889/saml/metadata -e SIMPLESAMLPHP_SP_ASSERTION_CONSUMER_SERVICE=https://localhost:8889/saml/acs -d --rm kristophjunge/test-saml-idp ``` -------------------------------- ### Monitor Hunt Progress with Velociraptor API Source: https://context7.com/velocidex/velociraptor/llms.txt This example demonstrates how to monitor the progress of an ongoing hunt by querying its status via the Velociraptor API. It uses `jq` to extract key metrics like the number of scheduled clients, completed tasks, and any errors encountered. ```bash curl -X GET "https://velociraptor.example.com/api/v1/GetHunt?hunt_id=H.1234567890" \ -H "Authorization: Bearer ${API_KEY}" | jq '{ \ hunt_id: .hunt_id, \ state: .state, \ total_scheduled: .stats.total_clients_scheduled, \ completed: .stats.total_clients_with_results, \ errors: .stats.total_clients_with_errors \ }' ``` -------------------------------- ### Download File from Client using Velociraptor VFS API Source: https://context7.com/velocidex/velociraptor/llms.txt This example demonstrates how to download a file from a remote client using the Velociraptor VFS API. It specifies the client ID, the VFS path of the file, and the desired byte range (offset and length). The downloaded content is redirected to a local file named `hosts.txt`. ```bash curl -X POST https://velociraptor.example.com/api/v1/VFSDownloadFile \ -H "Authorization: Bearer ${API_KEY}" \ -H "Content-Type: application/json" \ -d '{ \ "client_id": "C.1234567890abcdef", \ "vfs_path": "file/C:/Windows/System32/drivers/etc/hosts", \ "offset": 0, \ "length": 10485760 \ }' > hosts.txt ``` -------------------------------- ### List Directory Contents via Velociraptor VFS API Source: https://context7.com/velocidex/velociraptor/llms.txt This example demonstrates how to list the contents of a directory on a remote client using the Velociraptor Virtual File System (VFS) API. It sends a POST request with the client ID and VFS path, and uses `jq` to format the output, displaying item names, sizes, and modification times. ```bash curl -X POST https://velociraptor.example.com/api/v1/VFSListDirectory \ -H "Authorization: Bearer ${API_KEY}" \ -H "Content-Type: application/json" \ -d '{ \ "client_id": "C.1234567890abcdef", \ "vfs_path": "file/C:/Windows/System32", \ "recursive": false \ }' | jq '.items[] | {name: .Name, size: .Size, mtime: .mtime}' ``` -------------------------------- ### Example Updated Translation Entry (JSON) Source: https://github.com/velocidex/velociraptor/blob/master/gui/velociraptor/src/components/i8n/README.md Shows how a translated entry appears in `de.json` after being processed through Google Translate. The obfuscated hex key remains the same, but the value is the translated phrase. ```json "436c69636b20746f2076696577206f722065646974": "Zum Anzeigen oder Bearbeiten klicken", ``` -------------------------------- ### Search for Files Across VFS with Velociraptor API Source: https://context7.com/velocidex/velociraptor/llms.txt This snippet shows how to search for files across the VFS on a remote client. It allows specifying the client ID, the starting path for the search, a regular expression for the filename, and whether to upload the found files. The `upload: false` parameter indicates a search without upload. ```bash curl -X POST https://velociraptor.example.com/api/v1/SearchFile \ -H "Authorization: Bearer ${API_KEY}" \ -H "Content-Type: application/json" \ -d '{ \ "client_id": "C.1234567890abcdef", \ "path": "C:/", \ "name_regex": "(?i)password.*\.(txt|doc|xls)", \ "upload": false \ }' ``` -------------------------------- ### Server Event Query for Threat Intel Source: https://context7.com/velocidex/velociraptor/llms.txt Defines a server-side artifact in Velociraptor for correlating events and enriching them with threat intelligence. This example monitors for suspicious processes, queries an external threat intelligence feed, and generates alerts for malicious indicators. It can also trigger automated containment actions. ```python -- Server Artifact: Correlate events across all clients name: Server.Enrichment.ThreatIntel type: SERVER_EVENT sources: - query: | -- Monitor for new client event rows LET new_detections = SELECT * FROM watch_monitoring( artifact='Windows.Events.SuspiciousProcess' ) -- Enrich with threat intel LET enriched = SELECT ClientId, Hostname, EventTime, ProcessName, SHA256, http_client( url='https://threatintel.example.com/lookup/' + SHA256, headers=dict(Authorization='Bearer ' + server_config.THREAT_INTEL_KEY) ) AS ThreatIntel FROM new_detections WHERE SHA256 -- Generate high-priority alerts LET alerts = SELECT ClientId, Hostname, ProcessName, SHA256, parse_json(data=ThreatIntel.Content).reputation AS Reputation, parse_json(data=ThreatIntel.Content).tags AS Tags, timestamp(epoch=now()) AS AlertTime FROM enriched WHERE parse_json(data=ThreatIntel.Content).reputation = 'malicious' -- Automatically trigger containment collection LET containment = SELECT * FROM foreach( row=alerts, query={ SELECT collect_client( client_id=ClientId, artifacts='Windows.Remediation.Quarantine', spec=dict( artifact='Windows.Remediation.Quarantine', parameters=dict(ProcessPid=Pid) ), urgent=TRUE ) AS FlowId FROM scope() } ) SELECT * FROM chain( a={ SELECT *, 'Alert' AS EventType FROM alerts }, b={ SELECT *, 'Containment' AS EventType FROM containment } ) ``` -------------------------------- ### Example Missing Translation Entry (JSON) Source: https://github.com/velocidex/velociraptor/blob/master/gui/velociraptor/src/components/i8n/README.md Illustrates a typical entry found in a `de_new.json` file, which represents a missing translation. The key is an obfuscated hex string, and the value is the English phrase to be translated. ```json "436c69636b20746f2076696577206f722065646974": "Click to view or edit", ``` -------------------------------- ### Execute VQL Queries via CLI Source: https://context7.com/velocidex/velociraptor/llms.txt This snippet demonstrates how to execute VQL queries locally or against a Velociraptor server using the command-line interface. It supports various output formats (JSON, CSV, JSONL), environment variables, timeouts, and CPU limiting for production environments. It also shows how to execute queries from a file. ```bash # Execute a simple VQL query with JSON output velociraptor query "SELECT * FROM info()" --format json # Query with environment variables and timeout velociraptor query \ "SELECT Name, Size FROM glob(globs='**/*.exe', root='C:/Program Files')" \ --format csv \ --timeout 300 \ --env "MAX_SIZE=10000000" \ --output results.csv # Execute VQL from a file cat << 'EOF' > query.vql LET processes = SELECT Pid, Name, Exe FROM pslist() SELECT * FROM processes WHERE Name =~ "chrome" EOF velociraptor query --from_files query.vql --format jsonl # Query with CPU limiting for production systems velociraptor query \ "SELECT * FROM yara(files='C:/Users/**', rules=''' rule Suspicious { strings: $a = \"password\" condition: $a } ''')" \ --cpu_limit 30 \ --timeout 600 \ --format json ``` -------------------------------- ### Build Collector via GUI API Source: https://context7.com/velocidex/velociraptor/llms.txt Creates a downloadable collector file through the Velociraptor GUI API using a POST request. This method allows remote configuration and generation of collectors with specified artifacts, parameters, and output details. It requires an API key for authorization. ```bash curl -X POST https://velociraptor.example.com/api/v1/CreateDownloadFile \ -H "Authorization: Bearer ${API_KEY}" \ -H "Content-Type: application/json" \ -d '{ "collector_args": { "artifacts": ["Generic.Client.Info", "Windows.KapeFiles.Targets"], "parameters": { "Generic.Client.Info": {}, "Windows.KapeFiles.Targets": { "_BasicCollection": "Y" } }, "format": "zip", "output": "Collection-%HOSTNAME%-%TIMESTAMP%.zip", "password": "SecurePassword123", "level": 5, "target": "Windows", "target_args": { "target": "ZIP" } } }' ``` -------------------------------- ### Glob Plugin for Filesystem Pattern Matching Source: https://context7.com/velocidex/velociraptor/llms.txt This snippet showcases the VQL 'glob' plugin for pattern-based file discovery. It supports various accessors for different storage types (file, NTFS, registry) and allows filtering, multi-pattern matching, recursive searching with callback control, and timestamp-based filtering. It also demonstrates parsing NTFS MFT entries and querying registry keys. ```vql # Basic file globbing with filtering SELECT OSPath, Name, Size, Mode.String AS Permissions, Mtime FROM glob(globs='/**/*.log', root='C:/Windows/System32') WHERE Size > 1000000 ORDER BY Mtime DESC # Multi-pattern globbing with brace expansion SELECT OSPath, Size, hash(path=OSPath, accessor='file').MD5 AS MD5 FROM glob( globs=['C:/Users/*/AppData/**/*.{exe,dll,sys}', 'C:/Temp/**/*.ps1'], accessor='file' ) WHERE Mtime > now() - 86400 -- Files modified in last 24 hours # Recursive search with callback control SELECT OSPath, Size, IsDir FROM glob( globs='**', root='C:/', accessor='file', recursion_callback='x => NOT x.Name =~ "(Windows|Program Files|System Volume)"', nosymlink=TRUE ) WHERE NOT IsDir AND Name =~ '(?i)password|secret|credential' # NTFS raw disk access with MFT parsing SELECT EntryNumber, OSPath, InUse, Created0x10, Size FROM glob( globs='**/*.exe', root='C:/', accessor='ntfs' ) WHERE Created0x10 < '2023-01-01' # Registry globbing SELECT OSPath AS RegistryKey, Name, Data.value AS Value FROM glob( globs='HKEY_LOCAL_MACHINE/Software/Microsoft/**', accessor='registry' ) WHERE Name = 'DisplayName' ``` -------------------------------- ### Download Latest Release Binary (Shell) Source: https://github.com/velocidex/velociraptor/wiki/Tips-and-hints This command uses curl and jq to query the GitHub API for the latest release of Velociraptor and filters for the windows amd64 binary download URL. It is useful for automating the download of the most recent version. ```shell curl https://api.github.com/repos/velocidex/velociraptor/releases/latest | jq 'limit(1 ; ( .assets[].browser_download_url | select ( contains("windows-amd64.exe") )))' ``` -------------------------------- ### VQL Define Function to Select Value Based on Map Source: https://github.com/velocidex/velociraptor/wiki/VQL-Tricks This VQL snippet shows an alternative method to select a value based on a map by defining a reusable function. The `GetPath` function takes an OS as input and returns the corresponding path from a predefined dictionary. This approach promotes code reusability and cleaner queries. ```vql LET GetPath(OS) = get(item=dict( linux="/opt/velo", windows="C:\\Program Files", darwin="/tmp" ), member=OS, default="I dont know?") LET my_info = SELECT * FROM info() SELECT GetPath(OS=my_info[0].OS) AS MyPath FROM scope() ``` -------------------------------- ### HTTP Client Plugin for External Integrations (VQL) Source: https://context7.com/velocidex/velociraptor/llms.txt This VQL plugin demonstrates making HTTP requests for external integrations, such as querying threat intelligence APIs (e.g., VirusTotal) or sending notifications to services like Slack. It also shows how to POST results to an external SIEM. Ensure API keys and URLs are securely managed. ```python -- Query VirusTotal API for file hashes LET suspicious_files = SELECT OSPath, hash(path=OSPath).SHA256 AS SHA256 FROM glob(globs='C:/Users/*/Downloads/**/*.exe') LET vt_lookup = SELECT SHA256, parse_json(data=Content).data.attributes.last_analysis_stats AS Stats FROM foreach( row=suspicious_files, query={ SELECT SHA256, Content FROM http_client( url='https://www.virustotal.com/api/v3/files/' + SHA256, headers=dict(`X-Apikey`='YOUR_VT_API_KEY'), method='GET', disable_ssl_security=FALSE ) } ) SELECT f.OSPath, f.SHA256, vt.Stats.malicious AS Malicious, vt.Stats.suspicious AS Suspicious, vt.Stats.undetected AS Undetected FROM suspicious_files f LEFT JOIN vt_lookup vt ON f.SHA256 = vt.SHA256 WHERE vt.Stats.malicious > 0 -- Send Slack webhook notification LET slack_notification = http_client( url='https://hooks.slack.com/services/YOUR/WEBHOOK/URL', method='POST', headers=dict(`Content-Type`='application/json'), data=serialize( item=dict( text='🚨 Velociraptor Alert: Suspicious processes detected', blocks=[ dict( type='section', text=dict( type='mrkdwn', text='*Malicious files found on endpoint*\n' + format(format='Total: %d files', args=count()) ) ) ] ), format='json' ) ) SELECT * FROM slack_notification WHERE Response = 200 -- POST results to external SIEM SELECT * FROM foreach( row={ SELECT * FROM Custom.Detection.Results }, query={ SELECT http_client( url='https://siem.example.com/api/events', method='POST', headers=dict( `Content-Type`='application/json', `Authorization`='Bearer ' + server_config.SIEM_API_TOKEN ), data=serialize(item=_value, format='json') ).Response AS StatusCode FROM scope() } ) ``` -------------------------------- ### Develop Artifacts with Runtime Definition Override - Velociraptor CLI Source: https://github.com/velocidex/velociraptor/blob/master/artifacts/testdata/server/testcases/README.md This command illustrates how to develop Velociraptor artifacts using TDD by forcing the runtime to load raw YAML definitions. This allows for immediate iteration on artifact YAML files without rebuilding the binary. It specifies the binary, configuration, test cases, environment, and the path to the raw artifact definitions. ```shell ./output/velociraptor-v0.7.0-linux-amd64 -v --config artifacts/testdata/windows/test.config.yaml golden artifacts/testdata/server/testcases/ --env srcDir=`pwd` --filter=hostsfile --definitions artifacts/definitions/Generic/System/ ``` -------------------------------- ### Create User via Velociraptor API Source: https://context7.com/velocidex/velociraptor/llms.txt This bash script demonstrates how to create a new user in Velociraptor using its API. It sends a POST request to the `/api/v1/CreateUser` endpoint with the user's name and an initial password. Ensure the API key is securely handled. ```bash # Create new user curl -X POST https://velociraptor.example.com/api/v1/CreateUser \ -H "Authorization: Bearer ${API_KEY}" \ -H "Content-Type: application/json" \ -d '{ "name": "analyst@example.com", "password": "initial_password_change_me" }' ``` -------------------------------- ### VQL Notebook Collaborative Analysis Source: https://context7.com/velocidex/velociraptor/llms.txt Demonstrates VQL queries for collaborative analysis within a Jupyter-style notebook. It covers loading data, identifying suspicious binaries, generating timelines, and performing statistical analysis on hunt results. These queries are designed to be executed within the Velociraptor GUI. ```python -- Notebook Cell 1: Load initial data LET hunt_results = SELECT * FROM hunt_results( hunt_id='H.1234567890', artifact='Windows.System.ProcessInfo' ) SELECT count() AS TotalProcesses, count(items=Username) AS UniqueUsers FROM hunt_results -- Notebook Cell 2: Pivot on suspicious binaries LET suspicious_hashes = SELECT DISTINCT SHA256 FROM hunt_results WHERE NOT IsTrusted AND Exe =~ '(?i)temp' SELECT ClientId, Hostname, Exe, CommandLine, Username FROM hunt_results WHERE SHA256 IN suspicious_hashes GROUP BY ClientId -- Notebook Cell 3: Generate timeline SELECT timestamp(epoch=CreateTime) AS Time, ClientId, ProcessName, CommandLine FROM hunt_results ORDER BY Time -- Export to timeline format -- Use "Export to Timeline" button in GUI -- Notebook Cell 4: Statistical analysis SELECT Exe, count() AS Instances, count(items=ClientId) AS UniqueHosts, min(item=CreateTime) AS FirstSeen, max(item=CreateTime) AS LastSeen FROM hunt_results GROUP BY Exe HAVING Instances > 10 ORDER BY Instances DESC ``` -------------------------------- ### YARA Scanning Plugin for Memory and Files Source: https://context7.com/velocidex/velociraptor/llms.txt This snippet demonstrates the VQL 'yara' plugin for scanning files and process memory using YARA rules. It supports scanning specified files, scanning process memory with regular expressions for process names, and using external YARA rule files. It also shows options for limiting the number of hits per rule and displaying context around matches. ```vql # Scan files with embedded YARA rule SELECT OSPath, Rule, Strings, Tags, Meta FROM yara( files='C:/Users/**/*.exe', accessor='file', rules=''' rule Ransomware { meta: description = "Detects potential ransomware indicators" severity = "high" strings: $decrypt1 = "decrypt" nocase $bitcoin = /[13][a-km-zA-HJ-NP-Z1-9]{25,34}/ $extension = ".encrypted" nocase condition: 2 of them } ''', number=5 -- Max 5 hits per rule ) # Scan process memory for malicious patterns SELECT Pid, Name AS ProcessName, Rule, Strings, Address FROM yara( proc_regex='^(chrome|firefox|iexplore)\.exe$', rules=''' rule InMemoryShellcode { strings: $mz = "MZ" $shellcode = { 55 8B EC 83 C4 ?? 53 56 57 } condition: $mz and $shellcode } ''', context=64 -- Show 64 bytes of context around match ) # Use external YARA rules file LET yara_rules = read_file(filename='/rules/malware.yar') SELECT * FROM yara( files='''C:/Windows/Temp/**''', rules=yara_rules, key='A' -- Cache key for rule compilation ) ``` -------------------------------- ### Create a Hunt via Velociraptor REST API Source: https://context7.com/velocidex/velociraptor/llms.txt This snippet shows how to create a new hunt using the Velociraptor REST API. It specifies the artifacts to collect, conditions for targeting clients, and hunt parameters. The expected response includes a hunt ID and initial state. ```bash curl -X POST https://velociraptor.example.com/api/v1/CreateHunt \ -H "Authorization: Bearer ${API_KEY}" \ -H "Content-Type: application/json" \ -d '{ "description": "Hunt for lateral movement indicators across Windows hosts", "artifacts": [ "Windows.EventLogs.RDPAuth", "Windows.System.Services", "Windows.Network.NetstatEnriched" ], "specs": [ { "artifact": "Windows.EventLogs.RDPAuth", "parameters": { "env": [ {"key": "StartDate", "value": "2024-01-01"}, {"key": "EndDate", "value": "2024-12-31"} ] } } ], "condition": { "labels": ["Windows", "Production"], "excluded_labels": ["Decommissioned"], "os": { "os": "windows" } }, "expires": 604800, "max_rows": 50000, "timeout": 600, "ops_per_second": 10, "start_request": { "state": "RUNNING" } }' ``` -------------------------------- ### Notebook Collaborative Analysis API Source: https://context7.com/velocidex/velociraptor/llms.txt Allows users to create and share Jupyter-style notebooks for collaborative investigation within the GUI. ```APIDOC ## Notebook Collaborative Analysis ### Description Create and share Jupyter-style notebooks for collaborative investigation within the GUI. ### Usage Notebooks are created and managed within the Velociraptor GUI. The Python code snippets below represent typical notebook cells for data loading, analysis, and visualization. ``` -------------------------------- ### Run Golden Tests with Filter - Velociraptor CLI Source: https://github.com/velocidex/velociraptor/blob/master/artifacts/testdata/server/testcases/README.md This command demonstrates how to run Velociraptor golden tests with a specific filter applied. It uses the Velociraptor binary with a configuration file and specifies a filter to execute only matching test cases. The `srcDir` environment variable is set to the current working directory. ```shell #!/bin/bash GOLDEN=pe ./output/velociraptor -v --config artifacts/testdata/windows/test.config.yaml golden artifacts/testdata/server/testcases/ --env srcDir=`pwd` --filter=pe ``` -------------------------------- ### Generate SAML Certificate and Key Source: https://github.com/velocidex/velociraptor/blob/master/docs/saml/README.md Commands to generate a SAML certificate and private key signed by Velociraptor's CA. These are required for configuring Velociraptor's SAML login feature. ```bash openssl req -x509 -new -nodes -key VelociraptorCA.key -sha256 -days 1024 -out VelociraptorCA.crt openssl genrsa -out example.com.key 2048 openssl req -new -key example.com.key -out example.com.csr openssl x509 -req -in example.com.csr -CA VelociraptorCA.crt -CAkey VelociraptorCA.key -CAcreateserial -out example.com.crt -days 500 -sha256 ``` -------------------------------- ### Execute Stand-alone Collector (PowerShell) Source: https://github.com/velocidex/velociraptor/wiki/Tips-and-hints This PowerShell command demonstrates how to execute a stand-alone Velociraptor collector, such as a mini timeline executable, that has been placed in a specific directory. This is a workaround for executing collectors via CrowdStrike RTR. ```powershell Start-Process -FilePath "C:\CrowdStrike\Files\vr_mini_timeline.exe" ``` -------------------------------- ### Server Event Query for Correlation API Source: https://context7.com/velocidex/velociraptor/llms.txt Allows executing VQL on the server to correlate data from multiple clients and external sources. ```APIDOC ## Server Event Query for Correlation ### Description Execute VQL on the server to correlate data from multiple clients and external sources. ### Server Artifact Example: Threat Intel Enrichment This example demonstrates a server artifact that monitors for suspicious process events, enriches them with threat intelligence, generates alerts, and triggers containment actions. #### Artifact Definition ```yaml name: Server.Enrichment.ThreatIntel type: SERVER_EVENT sources: - query: | -- Monitor for new client event rows LET new_detections = SELECT * FROM watch_monitoring( artifact='Windows.Events.SuspiciousProcess' ) -- Enrich with threat intel LET enriched = SELECT ClientId, Hostname, EventTime, ProcessName, SHA256, http_client( url='https://threatintel.example.com/lookup/' + SHA256, headers=dict(Authorization='Bearer ' + server_config.THREAT_INTEL_KEY) ) AS ThreatIntel FROM new_detections WHERE SHA256 -- Generate high-priority alerts LET alerts = SELECT ClientId, Hostname, ProcessName, SHA256, parse_json(data=ThreatIntel.Content).reputation AS Reputation, parse_json(data=ThreatIntel.Content).tags AS Tags, timestamp(epoch=now()) AS AlertTime FROM enriched WHERE parse_json(data=ThreatIntel.Content).reputation = 'malicious' -- Automatically trigger containment collection LET containment = SELECT * FROM foreach( row=alerts, query={ SELECT collect_client( client_id=ClientId, artifacts='Windows.Remediation.Quarantine', spec=dict( artifact='Windows.Remediation.Quarantine', parameters=dict(ProcessPid=Pid) ), urgent=TRUE ) AS FlowId FROM scope() } ) SELECT * FROM chain( a={ SELECT *, 'Alert' AS EventType FROM alerts }, b={ SELECT *, 'Containment' AS EventType FROM containment } ) ``` ``` -------------------------------- ### JavaScript Global Variables and Configuration Source: https://github.com/velocidex/velociraptor/blob/master/gui/velociraptor/src/index.html Defines global JavaScript variables for application configuration, including debug status, language, theme, base path, Organization ID, and CSRF token. It also includes logic to dynamically set the base path and Organization ID from URL parameters and to handle the application's error state. ```javascript window.globals = { 'debug': false, 'lang': 'en', 'theme': "{{.UserTheme}}", 'base_path': "{{.BasePath}}", 'OrgId': "{{.OrgId}}" }; window.CsrfToken = "{{.CsrfToken}}"; window.base_path = "{{.BasePath}}"; /// Support development if (window.base_path.substring(0,2) === "{{") { window.base_path = "/"; window.globals.base_path = window.base_path; } // Set the OrgId from the URL if possible. let url = new URL(window.location.href) if (url.searchParams.get("org_id")) { window.globals.OrgId = url.searchParams.get("org_id"); } // Used to launch the application in an error state - allows the // user to interact with the react web app without being logged in. window.ErrorState = {{ if .ErrState }}{{.ErrState}}{{else}}[]{{end}}; ``` -------------------------------- ### Build Offline Collector via CLI Source: https://context7.com/velocidex/velociraptor/llms.txt Generates a standalone collector executable using the Velociraptor command-line interface. This is useful for air-gapped environments or specific incident response scenarios. It allows specifying artifacts, parameters, output format, and security settings. ```bash # Build offline collector via CLI velociraptor --config server.config.yaml collector create \ --artifacts Windows.KapeFiles.Targets,Windows.Memory.Acquisition,Windows.System.ProcessInfo \ --parameters '{ "Windows.KapeFiles.Targets": { "_KapeTriage": "Y", "VSSAnalysis": "Y" }, "Windows.Memory.Acquisition": { "AcquireMethod": "WinPmem" } }' \ --output collector.exe \ --target Windows \ --level 5 \ --password collection_password \ --format zip # Generated collector usage: # collector.exe --output results.zip --password collection_password ``` -------------------------------- ### List Users via API Source: https://context7.com/velocidex/velociraptor/llms.txt Retrieves a list of users from the Velociraptor server and extracts their names and locked status. This requires an API key for authentication. ```bash curl -X GET https://velociraptor.example.com/api/v1/GetUsers \ -H "Authorization: Bearer ${API_KEY}" | jq '.users[] | {name, locked}' ``` -------------------------------- ### Hunt Management API Source: https://context7.com/velocidex/velociraptor/llms.txt APIs for creating, monitoring, and retrieving results for hunts. ```APIDOC ## POST /api/v1/CreateHunt ### Description Creates a new hunt with specified artifacts, conditions, and parameters. ### Method POST ### Endpoint /api/v1/CreateHunt ### Parameters #### Request Body - **description** (string) - Required - A description for the hunt. - **artifacts** (array[string]) - Required - A list of artifact names to collect. - **specs** (array[object]) - Optional - Specifications for collecting specific artifacts, including parameters. - **artifact** (string) - Required - The name of the artifact. - **parameters** (object) - Optional - Parameters for the artifact. - **condition** (object) - Required - Conditions for selecting clients for the hunt. - **labels** (array[string]) - Optional - Include clients with these labels. - **excluded_labels** (array[string]) - Optional - Exclude clients with these labels. - **os** (object) - Optional - Filter by operating system. - **os** (string) - Required - The operating system name (e.g., "windows"). - **expires** (integer) - Optional - The duration in seconds until the hunt expires. - **max_rows** (integer) - Optional - The maximum number of rows to collect per artifact. - **timeout** (integer) - Optional - The timeout in seconds for each client. - **ops_per_second** (integer) - Optional - Operations per second limit. - **start_request** (object) - Optional - Initial state of the hunt. - **state** (string) - Required - The initial state (e.g., "RUNNING"). ### Request Example ```json { "description": "Hunt for lateral movement indicators across Windows hosts", "artifacts": [ "Windows.EventLogs.RDPAuth", "Windows.System.Services", "Windows.Network.NetstatEnriched" ], "specs": [ { "artifact": "Windows.EventLogs.RDPAuth", "parameters": { "env": [ {"key": "StartDate", "value": "2024-01-01"}, {"key": "EndDate", "value": "2024-12-31"} ] } } ], "condition": { "labels": ["Windows", "Production"], "excluded_labels": ["Decommissioned"], "os": { "os": "windows" } }, "expires": 604800, "max_rows": 50000, "timeout": 600, "ops_per_second": 10, "start_request": { "state": "RUNNING" } } ``` ### Response #### Success Response (200) - **hunt_id** (string) - The ID of the created hunt. - **state** (string) - The current state of the hunt. - **stats** (object) - Statistics about the hunt. - **total_clients_scheduled** (integer) - The number of clients scheduled for the hunt. #### Response Example ```json { "hunt_id": "H.1234567890", "state": "RUNNING", "stats": { "total_clients_scheduled": 150 } } ``` ## GET /api/v1/GetHunt ### Description Monitors the progress and status of a specific hunt. ### Method GET ### Endpoint /api/v1/GetHunt #### Query Parameters - **hunt_id** (string) - Required - The ID of the hunt to monitor. ### Response #### Success Response (200) - **hunt_id** (string) - The ID of the hunt. - **state** (string) - The current state of the hunt. - **stats** (object) - Statistics about the hunt. - **total_clients_scheduled** (integer) - Total clients scheduled. - **total_clients_with_results** (integer) - Clients that have returned results. - **total_clients_with_errors** (integer) - Clients that have encountered errors. #### Response Example (jq filtered) ```json { "hunt_id": "H.1234567890", "state": "RUNNING", "total_scheduled": 150, "completed": 120, "errors": 5 } ``` ## POST /api/v1/GetHuntResults ### Description Retrieves aggregated results for a specific hunt and artifact. ### Method POST ### Endpoint /api/v1/GetHuntResults ### Parameters #### Request Body - **hunt_id** (string) - Required - The ID of the hunt. - **artifact** (string) - Required - The artifact for which to retrieve results. - **start_row** (integer) - Optional - The starting row index for pagination. - **rows** (integer) - Optional - The number of rows to retrieve. ### Request Example ```json { "hunt_id": "H.1234567890", "artifact": "Windows.EventLogs.RDPAuth", "start_row": 0, "rows": 1000 } ``` ### Response #### Success Response (200) - **items** (array[object]) - A list of collected items. - **ClientId** (string) - The ID of the client. - **EventTime** (string) - The timestamp of the event. - **SourceIP** (string) - The source IP address. - **Username** (string) - The username associated with the event. - **LogonType** (string) - The type of logon. #### Response Example (jq filtered) ```json { "ClientId": "C.1234567890abcdef", "EventTime": "2024-01-15T10:30:00Z", "SourceIP": "192.168.1.100", "Username": "user1", "LogonType": "Interactive" } ``` ``` -------------------------------- ### Define Custom Suspicious Process Artifact (YAML) Source: https://context7.com/velocidex/velociraptor/llms.txt This YAML defines a custom Velocidex artifact named 'Custom.Windows.SuspiciousProcesses'. It uses VQL queries to detect potentially suspicious processes by analyzing parent-child relationships, Authenticode signatures, and network connections. The artifact includes parameters to filter processes by name, verify signatures, and include network connection data. ```yaml name: Custom.Windows.SuspiciousProcesses description: | Detect potentially suspicious processes based on parent-child relationships, unsigned executables, and network connections. Correlates pslist, Authenticode verification, and netstat data. author: Security Team type: CLIENT parameters: - name: ProcessNameRegex default: .* description: Filter processes by name (regex) - name: CheckSignatures type: bool default: Y description: Verify Authenticode signatures - name: IncludeNetworkConnections type: bool default: Y description: Include active network connections sources: - name: SuspiciousProcessAnalysis query: | -- Get all running processes LET processes = SELECT Pid, Ppid, Name, Exe, CommandLine, Username, CreateTime FROM pslist() WHERE Name =~ ProcessNameRegex -- Check Authenticode signatures if requested LET signed_processes = SELECT *, authenticode(filename=Exe).Trusted AS IsTrusted, authenticode(filename=Exe).SubjectName AS Signer FROM processes -- Correlate with network connections if requested LET processes_with_network = SELECT p.*, { SELECT Laddr, Raddr, Status FROM netstat() WHERE Pid = p.Pid } AS NetworkConnections FROM if( condition=IncludeNetworkConnections, then=signed_processes, else={ SELECT * FROM processes } ) AS p -- Flag suspicious indicators SELECT Pid, Name, Exe, CommandLine, Username, IsTrusted, Signer, NetworkConnections, CreateTime, dict( UncommonParent=Ppid IN (SELECT Pid FROM pslist() WHERE Name =~ "^(explorer|services|winlogon)$"), UnsignedExecutable=NOT IsTrusted AND CheckSignatures, SuspiciousPath=Exe =~ "(?i)(temp|appdata|users.*downloads)", HasNetworkConnection=len(list=NetworkConnections) > 0, ObfuscatedCommand=CommandLine =~ "(?i)(frombase64|invoke-expression|downloadstring)" ) AS SuspiciousIndicators, len(items=[ if(condition=NOT IsTrusted AND CheckSignatures, then=1), if(condition=Exe =~ "(?i)(temp|appdata)", then=1), if(condition=CommandLine =~ "(?i)(frombase64|invoke-expression)", then=1) ]) AS RiskScore FROM processes_with_network WHERE RiskScore > 0 ORDER BY RiskScore DESC, CreateTime DESC - name: ProcessTree query: | -- Generate parent-child process tree for suspicious processes LET suspicious = SELECT Pid FROM SuspiciousProcessAnalysis LET tree(ProcessPid, Level) = SELECT Pid, Ppid, Name, Level, join(array=[format(format="%s", args=Level), Name], sep=" ") AS Display FROM chain( a={ SELECT * FROM pslist() WHERE Pid = ProcessPid }, b={ SELECT * FROM foreach( row={ SELECT Pid FROM pslist() WHERE Ppid = ProcessPid }, query={ SELECT * FROM tree(ProcessPid=Pid, Level=Level + 1) } ) } ) SELECT * FROM foreach( row=suspicious, query={ SELECT * FROM tree(ProcessPid=Pid, Level=0) } ) reports: - type: CLIENT template: | # Suspicious Process Analysis Report {{ $results := Query "SELECT * FROM source(source='SuspiciousProcessAnalysis')" }} ## Summary - **Total Suspicious Processes**: {{ len $results }} - **High Risk (Score ≥ 2)**: {{ Query "SELECT count() FROM source(source='SuspiciousProcessAnalysis') WHERE RiskScore >= 2" | Expand }} ## Findings {{ range $results }} ### Process: {{ .Name }} (PID: {{ .Pid }}) - **Executable**: `{{ .Exe }}` - **Command Line**: `{{ .CommandLine }}` - **Risk Score**: {{ .RiskScore }} - **Trusted**: {{ .IsTrusted }} {{ if .NetworkConnections }} - **Network Connections**: {{ len .NetworkConnections }} active {{ end }} {{ end }} ``` -------------------------------- ### Monitor Windows Process Execution with ETW/Sysmon Source: https://context7.com/velocidex/velociraptor/llms.txt This artifact monitors and logs all process executions in real-time using Windows ETW or Sysmon events. It enriches events with file hashes, signature verification, and suspicious activity indicators. It filters out common system processes and focuses on potentially malicious executions. ```yaml name: Custom.Events.ProcessExecution description: | Monitor and log all process executions in real-time using ETW (Event Tracing for Windows) or Sysmon events. Includes enrichment with hash calculation and signature verification. type: CLIENT_EVENT sources: - name: WindowsProcessExecution query: | -- Monitor process creation events via ETW or Sysmon LET process_events = SELECT EventTime, ProcessID AS Pid, ParentProcessID AS Ppid, CommandLine, Image AS Exe, User, IntegrityLevel, Hashes FROM watch_etw( guid="{22fb2cd6-0e7b-422b-a0c7-2fad1fd0e716}", -- Microsoft-Windows-Kernel-Process any=0x10 -- PROCESS_CREATE ) -- Enrich with file metadata and signatures SELECT EventTime, Pid, Ppid, basename(path=Exe) AS ProcessName, Exe, CommandLine, User, hash(path=Exe).MD5 AS MD5, hash(path=Exe).SHA256 AS SHA256, authenticode(filename=Exe).Trusted AS IsTrusted, authenticode(filename=Exe).SubjectName AS Signer, dict( SuspiciousLocation=Exe =~ "(?i)(\\temp\\|\\appdata\\local\\temp|\\downloads\\)", UnsignedExecutable=NOT authenticode(filename=Exe).Trusted, ObfuscatedCommand=CommandLine =~ "(?i)(frombase64|invoke-expression|-enc|-e\\s+[A-Za-z0-9+/=]{50})", ParentIsScriptEngine=basename(path={ SELECT Exe FROM pslist() WHERE Pid = Ppid }.Exe) =~ "(?i)^(powershell|cmd|wscript|cscript|mshta)\\.exe$" ) AS Indicators FROM process_events WHERE -- Filter noise - exclude common system processes NOT Exe =~ "(?i)^C:\\Windows\\(System32|SysWOW64)\\(svchost|dllhost|RuntimeBroker|backgroundTaskHost)\\.exe$" -- Focus on suspicious indicators AND ( Exe =~ "(?i)(\\temp\\|\\appdata\\local\\temp|\\downloads\\)" OR NOT authenticode(filename=Exe).Trusted OR CommandLine =~ "(?i)(frombase64|invoke-expression|-enc)" ) ```