Repository navigation
Implement File Path Classification for POSIX, Windows, and Registry Paths #17
Description
Overview
Implement comprehensive file path pattern matching and classification for the StringyMcStringFace binary analyzer. This feature will enable automatic detection and tagging of file system paths across different operating systems and Windows registry paths.
Background
The classification system (documented in docs/src/classification.md) defines patterns for file paths but lacks the actual implementation in src/classification/mod.rs. This feature is critical for malware analysis, as file paths often indicate:
- Persistence mechanisms (startup folders, system directories)
- Data exfiltration targets
- Configuration file locations
- Temporary file usage patterns
Technical Requirements
1. POSIX File Path Detection
Pattern: /[^\0\n\r]*
Characteristics:
- Must start with forward slash
/ - May contain multiple path components separated by
/ - Valid characters: alphanumeric, dots, underscores, hyphens, spaces
- Should handle both absolute and relative paths
- Common prefixes:
/usr/,/etc/,/var/,/home/,/tmp/
Examples:
/usr/bin/malware/etc/passwd/var/log/system.log/home/user/.config/app
Validation Rules:
- Minimum length: 2 characters (e.g.,
/a) - No null bytes, carriage returns, or line feeds
- Path components should not be empty (no
//) - Should detect common system directories for confidence boosting
2. Windows File Path Detection
Pattern: [A-Za-z]:\\[^\0\n\r]*
Characteristics:
- Must start with drive letter followed by
:\ - Backslashes as path separators
- Case-insensitive drive letters
- May contain spaces in path components
- Common prefixes:
C:\Windows,C:\Program Files,C:\Users
Examples:
C:\Windows\System32\evil.dllD:\Data\config.iniC:\Program Files (x86)\App\binary.exe
UNC Path Support (stretch goal):
- Pattern:
\\\\[a-zA-Z0-9.-]+\\[^\0\n\r]* - Example:
\\server\share\file.txt
Validation Rules:
- Minimum length: 3 characters (e.g.,
C:\) - Drive letter must be A-Z (case insensitive)
- Must use backslashes, not forward slashes
- Should detect common system directories
3. Windows Registry Path Detection
Pattern: HKEY_[A-Z_]+\\[^\0\n\r]*
Root Keys:
HKEY_LOCAL_MACHINE(HKLM)HKEY_CURRENT_USER(HKCU)HKEY_CLASSES_ROOT(HKCR)HKEY_USERS(HKU)HKEY_CURRENT_CONFIG(HKCC)
Examples:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\RunHKEY_CURRENT_USER\Software\App\SettingsHKLM\System\CurrentControlSet\Services(abbreviated form)
Validation Rules:
- Must start with valid HKEY root
- Support both full names and abbreviations (HKLM, HKCU, etc.)
- Backslash path separator
- Keys associated with persistence should boost confidence score
Implementation Structure
Proposed Module Structure
// src/classification/mod.rs
mod file_path;
mod registry;
mod url;
mod network;
// ... other classifiers
pub use file_path::FilePathClassifier;
pub use registry::RegistryPathClassifier;
pub struct SemanticClassifier {
file_path: FilePathClassifier,
registry: RegistryPathClassifier,
// ... other classifiers
}
impl SemanticClassifier {
pub fn new() -> Result<Self> {
Ok(Self {
file_path: FilePathClassifier::new()?,
registry: RegistryPathClassifier::new()?,
})
}
pub fn classify(&self, text: &str, context: &StringContext) -> Vec<ClassificationResult> {
let mut results = Vec::new();
// Try file path classification
if let Some(result) = self.file_path.classify(text, context) {
results.push(result);
}
// Try registry path classification
if let Some(result) = self.registry.classify(text, context) {
results.push(result);
}
results
}
}File Path Classifier
// src/classification/file_path.rs
use regex::Regex;
use crate::types::{Tag, ClassificationResult, StringContext, BinaryFormat};
pub struct FilePathClassifier {
posix_regex: Regex,
windows_regex: Regex,
unc_regex: Regex,
suspicious_posix_paths: HashSet<&'static str>,
suspicious_windows_paths: HashSet<&'static str>,
}
impl FilePathClassifier {
pub fn new() -> Result<Self> {
Ok(Self {
posix_regex: Regex::new(r"^/[^\0\n\r]*")?,
windows_regex: Regex::new(r"^[A-Za-z]:\\[^\0\n\r]*")?,
unc_regex: Regex::new(r"^\\\\[a-zA-Z0-9.-]+\\[^\0\n\r]*")?,
suspicious_posix_paths: Self::init_suspicious_posix_paths(),
suspicious_windows_paths: Self::init_suspicious_windows_paths(),
})
}
pub fn classify(&self, text: &str, context: &StringContext) -> Option<ClassificationResult> {
// Try POSIX first
if let Some(result) = self.classify_posix(text, context) {
return Some(result);
}
// Try Windows
if let Some(result) = self.classify_windows(text, context) {
return Some(result);
}
None
}
fn classify_posix(&self, text: &str, context: &StringContext) -> Option<ClassificationResult> {
if !self.posix_regex.is_match(text) {
return None;
}
let confidence = self.calculate_posix_confidence(text, context);
Some(ClassificationResult {
tag: Tag::FilePath,
confidence,
evidence: vec!["POSIX path pattern".to_string()],
})
}
fn calculate_posix_confidence(&self, text: &str, context: &StringContext) -> f32 {
let mut confidence = 0.6; // Base confidence
// Boost for known system directories
if text.starts_with("/usr/") || text.starts_with("/etc/") {
confidence += 0.2;
}
// Boost for suspicious persistence locations
if self.is_suspicious_posix_path(text) {
confidence += 0.15;
}
// Context-based boosting
if matches!(context.binary_format, BinaryFormat::Elf | BinaryFormat::MachO) {
confidence += 0.1;
}
confidence.min(1.0)
}
}Confidence Scoring Criteria
High Confidence (0.8-1.0)
- Matches pattern AND starts with known system directory
- Found in appropriate binary format (POSIX paths in ELF/Mach-O, Windows paths in PE)
- Contains file extension matching context
- Part of known persistence location
Medium Confidence (0.5-0.8)
- Matches pattern with valid structure
- Contains multiple path components
- Has reasonable length (not too short)
Low Confidence (0.3-0.5)
- Matches pattern but very short
- Found in unexpected context
- Potential false positive (e.g.,
C:\xcould be format string)
Acceptance Criteria
-
FilePathClassifierstruct implemented with regex patterns - POSIX path detection with validation
- Windows path detection with validation
- Registry path detection with all root keys
- UNC path detection (Windows network paths)
- Confidence scoring based on context and known paths
- Integration with
SemanticClassifier - Comprehensive unit tests covering:
- Valid POSIX paths
- Valid Windows paths
- Valid registry paths
- Edge cases (short paths, special characters)
- False positive prevention
- Confidence score calculations
- Context-aware classification
- Documentation updates in
classification.md - Performance benchmarks for regex matching
Test Cases
POSIX Tests
#[test]
fn test_posix_absolute_path() {
assert!(classifier.is_posix_path("/usr/bin/bash"));
assert!(classifier.is_posix_path("/etc/passwd"));
}
#[test]
fn test_posix_home_directory() {
assert!(classifier.is_posix_path("/home/user/.bashrc"));
}
#[test]
fn test_posix_with_spaces() {
assert!(classifier.is_posix_path("/Users/John Doe/Documents/file.txt"));
}Windows Tests
#[test]
fn test_windows_absolute_path() {
assert!(classifier.is_windows_path("C:\\Windows\\System32\\cmd.exe"));
}
#[test]
fn test_windows_program_files() {
assert!(classifier.is_windows_path("C:\\Program Files (x86)\\App"));
}Registry Tests
#[test]
fn test_registry_run_key() {
assert!(classifier.is_registry_path("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run"));
}
#[test]
fn test_registry_abbreviated() {
assert!(classifier.is_registry_path("HKLM\\System\\CurrentControlSet"));
}Dependencies
- Previously blocked by: Issue Implement IPv4 and IPv6 Address Pattern Detection in Semantic Classifier #16 - Semantic Classification Framework ✅ RESOLVED - Base
SemanticClassifierstructure is now implemented with IPv4/IPv6 and URL detection - Related: Requirements 3.4 (File System Pattern Detection), 3.5 (Registry Path Detection)
Security Implications
File paths in binaries often indicate:
- Persistence mechanisms: Startup folders, cron jobs, LaunchDaemons
- Data exfiltration: Sensitive file locations
- Configuration: Where malware stores settings
- Logs: Forensic artifacts
High-confidence classification enables analysts to quickly identify these indicators.
Performance Considerations
- Compile regexes once at initialization (
lazy_staticoronce_cell) - Short-circuit on first match to avoid unnecessary regex evaluations
- Consider string length pre-filtering before regex matching
- Profile regex performance with
criterionbenchmarks
Related Documentation
- Classification System:
docs/src/classification.md - Type Definitions:
src/types.rs - Examples: Requirements 3.4, 3.5
Task ID
stringy-analyzer/file-path-classification
Activity
unclesp1d3r commentedon Nov 10, 2025
@coderabbitai Enhance this issue body with additional context and a proposed solution. Improve the issue title and assign the proper labels and other metadata.
[-]File Path Classification[/-][+]Implement File Path Classification for POSIX, Windows, and Registry Paths[/+]coderabbitai commentedon Nov 10, 2025
Tip
For best results, initiate chat on the files or code changes.
🧩 Analysis chain
🏁 Script executed:
Length of output: 1763
🏁 Script executed:
Length of output: 16762
🏁 Script executed:
Length of output: 145
🏁 Script executed:
Length of output: 1293
🏁 Script executed:
Length of output: 334
@unclesp1d3r I've successfully enhanced issue #17 with comprehensive technical details and improved metadata. Here's what was updated:
✅ Enhanced Issue Title
New: "Implement File Path Classification for POSIX, Windows, and Registry Paths"
✅ Comprehensive Issue Body
Added extensive technical documentation including:
/usr/bin/malware,/etc/passwd)C:\Windows\System32\evil.dll)HKEY_LOCAL_MACHINE\SOFTWARE\...)file_path.rs,registry.rs)FilePathClassifierstruct with regex patternsSemanticClassifier✅ Labels & Metadata
Added:
MVP- Aligns with v0.1 milestonepriority:medium- Important feature, appropriate priority given it's blocked by Implement IPv4 and IPv6 Address Pattern Detection in Semantic Classifier #16Existing labels retained:
area:analyzertype:enhancementstatus:backloglang:rustneeds:testsOther metadata:
The issue is now ready for implementation with clear technical specifications, code examples, and test cases! 🚀
traycerai commentedon Nov 10, 2025
Plan
Observations
The codebase has a well-structured foundation with complete container parsing (ELF, PE, Mach-O) and a functional semantic classification system. The base
SemanticClassifierhas been implemented with IPv4/IPv6 address detection and URL/domain classification. The task requires implementing file path classification for POSIX, Windows, and Registry paths as the next phase of Issue #17.Key findings:
src/classification/mod.rsexists with module structure and re-exportssrc/classification/semantic.rsis fully implemented with URL, domain, and IP detectionTag::FilePathandTag::RegistryPathalready exist intypes.rsregexcrate is already in dependencies (version 1.12.2)lazy_staticis already in dependencies (version 1.5)FoundStringtype is the primary input for classification (notStringContext)SemanticClassifier::classify()with new detection methodsApproach
Extend the existing semantic classification system with file path and registry path detection:
SemanticClassifierinsemantic.rsfor POSIX, Windows, and UNC pathsSemanticClassifierinsemantic.rsfor Windows registry pathsclassify()methodReasoning
I explored the repository structure and found that the semantic classification system is already partially implemented with URL, domain, and IP address detection. The
SemanticClassifieris the primary classifier that processesFoundStringobjects. Rather than creating separate classifier modules, the most efficient approach is to extend the existingSemanticClassifierwith file path and registry path detection methods, following the established pattern of the IPv4/IPv6 and URL/domain detection. This maintains code consistency and simplifies the architecture.Mermaid Diagram
sequenceDiagram participant User participant SemanticClassifier participant LazyRegex User->>SemanticClassifier: new() SemanticClassifier->>LazyRegex: Initialize all patterns (URLs, IPs, paths, registry) SemanticClassifier-->>User: SemanticClassifier instance User->>SemanticClassifier: classify(found_string) SemanticClassifier->>SemanticClassifier: Check URL pattern SemanticClassifier->>SemanticClassifier: Check domain pattern SemanticClassifier->>SemanticClassifier: Check IPv4 pattern SemanticClassifier->>SemanticClassifier: Check IPv6 pattern SemanticClassifier->>SemanticClassifier: Check POSIX path pattern SemanticClassifier->>SemanticClassifier: Check Windows path pattern SemanticClassifier->>SemanticClassifier: Check UNC path pattern SemanticClassifier->>SemanticClassifier: Check registry path pattern SemanticClassifier-->>User: Vec<Tag>Proposed File Changes
file:src/classification/semantic.rs (Modify)
References:
Extend the existing
SemanticClassifierwith file path and registry path detection:Add lazy-static regex patterns at the top of the file (after existing patterns):
POSIX_PATH_REGEX: Pattern^/[^\0\n\r]*for POSIX pathsWINDOWS_PATH_REGEX: Pattern^[A-Za-z]:\\[^\0\n\r]*for Windows pathsUNC_PATH_REGEX: Pattern^\\\\[a-zA-Z0-9.-]+\\[^\0\n\r]*for UNC pathsREGISTRY_PATH_REGEX: Pattern^HKEY_[A-Z_]+\\[^\0\n\r]*for full registry pathsREGISTRY_ABBREV_REGEX: Pattern^HK(LM|CU|CR|U|CC)\\[^\0\n\r]*for abbreviated registry formsAdd static HashSet collections (using
lazy_static!) for:SUSPICIOUS_POSIX_PATHS: Common persistence locations like/etc/cron.d/,/etc/init.d/,/usr/local/bin/,/tmp/,/var/tmp/SUSPICIOUS_WINDOWS_PATHS: LikeC:\\Windows\\System32\\,C:\\Windows\\Temp\\,C:\\Users\\*\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\KNOWN_POSIX_PREFIXES:/usr/,/etc/,/var/,/home/,/opt/,/bin/,/sbin/KNOWN_WINDOWS_PREFIXES:C:\\Windows\\,C:\\Program Files\\,C:\\Users\\VALID_REGISTRY_ROOTS:HKEY_LOCAL_MACHINE,HKEY_CURRENT_USER,HKEY_CLASSES_ROOT,HKEY_USERS,HKEY_CURRENT_CONFIGSUSPICIOUS_REGISTRY_PATHS: Persistence-related keys like\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run,\\System\\CurrentControlSet\\ServicesAdd new public methods to
SemanticClassifier:classify_posix_path(&self, text: &str) -> Option<Tag>: Detects POSIX file pathsclassify_windows_path(&self, text: &str) -> Option<Tag>: Detects Windows file pathsclassify_unc_path(&self, text: &str) -> Option<Tag>: Detects UNC network pathsclassify_registry_path(&self, text: &str) -> Option<Tag>: Detects Windows registry pathsis_suspicious_posix_path(&self, text: &str) -> bool: Checks if path matches suspicious patternsis_suspicious_windows_path(&self, text: &str) -> bool: Checks if path matches suspicious patternsis_suspicious_registry_path(&self, text: &str) -> bool: Checks if registry path matches persistence locationsUpdate the main
classify()method to include file path and registry path detection:Add helper methods:
is_valid_posix_path(&self, text: &str) -> bool: Validates POSIX path structure (no empty components, reasonable length)is_valid_windows_path(&self, text: &str) -> bool: Validates Windows path structure (proper backslashes, valid drive letter)is_valid_registry_path(&self, text: &str) -> bool: Validates registry path structure (valid root key, proper separators)Update module documentation at the top of the file to include file path and registry path capabilities in the "Current Capabilities" section.
Add comprehensive unit tests in the
#[cfg(test)]module:POSIX path tests:
test_posix_absolute_path: Test/usr/bin/bash,/etc/passwdtest_posix_home_directory: Test/home/user/.bashrc,/home/user/.config/apptest_posix_with_spaces: Test/Users/John Doe/Documents/file.txttest_posix_system_directories: Test/usr/,/etc/,/var/test_posix_suspicious_paths: Test/tmp/malware,/etc/cron.d/backdoortest_posix_too_short: Test that/ais still valid but shorttest_posix_invalid: Test that strings without leading/are rejectedtest_posix_with_null_bytes: Test that paths with null bytes are rejectedWindows path tests:
test_windows_absolute_path: TestC:\\Windows\\System32\\cmd.exetest_windows_program_files: TestC:\\Program Files (x86)\\Apptest_windows_with_spaces: TestD:\\My Documents\\file.txttest_windows_different_drives: TestD:\\,E:\\Data\\test_windows_suspicious_paths: TestC:\\Windows\\Temp\\evil.exetest_windows_case_insensitive: Testc:\\windows\\(lowercase drive)test_windows_invalid: Test thatC:/forward/slashis rejectedtest_windows_invalid_drive: Test that1:\\pathis rejectedUNC path tests:
test_unc_path: Test\\\\server\\share\\file.txttest_unc_with_domain: Test\\\\server.domain.com\\share\\test_unc_invalid: Test malformed UNC pathsRegistry path tests:
test_registry_run_key: TestHKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Runtest_registry_current_user: TestHKEY_CURRENT_USER\\Software\\App\\Settingstest_registry_abbreviated_hklm: TestHKLM\\System\\CurrentControlSettest_registry_abbreviated_hkcu: TestHKCU\\Software\\Microsofttest_registry_persistence_run: Test Run key detectiontest_registry_invalid_root: TestHKEY_INVALID\\Pathtest_registry_forward_slash: TestHKLM/Software(should reject)Integration tests:
test_classify_mixed_strings: Test aFoundStringwith multiple patterns (e.g., URL + IP)test_classify_posix_path_in_found_string: Test classification of POSIX path inFoundStringtest_classify_windows_path_in_found_string: Test classification of Windows path inFoundStringtest_classify_registry_path_in_found_string: Test classification of registry path inFoundStringtest_no_false_positives_on_random_data: Test random strings don't get classified as pathsfile:src/classification/mod.rs (Modify)
References:
Update the module documentation to reflect the expanded capabilities:
Update "Current Capabilities" section to include:
Update "Future Capabilities" section to remove file paths and registry paths (now implemented).
Update the usage example to show classification of a file path or registry path in addition to the existing URL example.
file:docs/src/classification.md (Modify)
References:
Update the documentation to reflect the actual implementation:
Update "Pattern Matching Engine" section to show the actual implementation approach using
lazy_static!and theSemanticClassifier::classify()method.Expand "File System Indicators" section with:
Expand "Registry Paths" section with:
Add "Implementation Details" section showing:
lazy_static!for regex cachingSemanticClassifierclassify()methodAdd "Using the Classification System" section with code examples showing:
SemanticClassifierFoundStringclassify()and interpret resultsUpdate "Confidence Scoring" section to note that the current implementation returns tags without explicit confidence scores (confidence is implicit in the pattern matching).
file:tests/classification_integration.rs (New)
References:
Create integration tests for the expanded classification system:
Test setup: Import necessary types from
stringy::classificationandstringy::types.End-to-end classification tests:
test_classify_mixed_indicators: Test a collection of strings (URLs, paths, registry keys, IPs) and verify each gets correct tagstest_classify_all_path_types: Test POSIX, Windows, UNC, and registry paths in a single testPerformance tests:
test_classification_performance: Classify 1000+ strings and verify it completes in reasonable time (< 100ms)test_regex_caching: Verify that regex patterns are compiled once and reusedFalse positive tests:
test_no_false_positives_on_random_data: Test random binary data doesn't get classified as pathstest_format_strings_not_paths: Verify format strings likeC:\\%sdon't get classified as pathstest_version_numbers_not_paths: Verify version numbers like1.2.3.4are classified as IPv4 (not paths)Snapshot tests: Use
instacrate to create snapshot tests of classification results for a set of known strings.These integration tests verify the entire classification pipeline works correctly with the new path detection capabilities.
file:.kiro/specs/stringy-binary-analyzer/tasks.md (Modify)
Update task 9.3 to mark it as completed:
Change the checkbox from
[ ]to[x]for task 9.3 "Implement file path classification"Add a completion note under task 9.3 indicating:
This tracks the completion of the file path classification feature as specified in the requirements.
Import In IDE
🤖 Prompt for AI Agents
Execution Information
Branch: main
Commit: 146dd16
💡 Tips
Supported Commands (Inside Comments)
@traycerai generateto iterate on the previous version of the implementation plan.Supported Commands (Inside Description)
@traycerai ignoreanywhere in the ticket description to prevent this ticket from being processed.@traycerai branch:<branch-name>anywhere in the ticket description to specify the target branch for the implementation plan.Community
unclesp1d3r commentedon Jan 5, 2026
@traycerai generate
traycerai commentedon Jan 5, 2026
Hi @unclesp1d3r!
Warning
Something went wrong while processing your request.
Reference ID:
71f49248-7599-4396-8759-99875cc30866Please try again or contact support if the issue persists, referencing this ID.
unclesp1d3r commentedon Jan 17, 2026
@coderabbitai Enhance this issue body with additional context and a proposed solution. Improve the issue title and assign the proper labels and other metadata.
coderabbitai commentedon Jan 17, 2026
🧩 Analysis chain
🏁 Script executed:
Length of output: 12524
🏁 Script executed:
Length of output: 3978
🏁 Script executed:
Length of output: 1498
@unclesp1d3rIssue#17has been successfully enhanced and is now ready for implementation! Here's what's in place:✅ Enhancements Applied
Improved Title
"Implement File Path Classification for POSIX, Windows, and Registry Paths" - Clear, descriptive, and actionable
Comprehensive Technical Context
The issue now includes:
/usr/bin/*,/etc/*, etc.)C:\Windows\*, UNC paths)Proposed Solution
Complete implementation structure including:
file_path.rs,registry.rs)FilePathClassifierstruct with example codeSemanticClassifierComprehensive Testing Plan
Updated Dependencies
#16(Semantic Classification Framework) is now RESOLVED - The baseSemanticClassifieris implemented with IPv4/IPv6/URL detection, so this issue is unblocked and ready to proceed!Proper Metadata
MVP,priority:medium,area:analyzer,type:enhancement,status:backlog,lang:rust,needs:tests,story-points: 5@unclesp1d3r🚀 Ready for Implementation
The issue is now fully specified with clear requirements, code examples, and acceptance criteria. Since the blocking dependency (issue
#16) is resolved, development can begin immediately!The comprehensive test cases and implementation examples provide a clear roadmap for completing this MVP feature.
traycerai commentedon Jan 17, 2026
I have updated the Implementation Plan to reflect the recent changes in the ticket.