SSF Tools - Analyze Module Architecture & Design Patterns¶
Overview¶
The analyze module provides security analysis services for entropy calculation and credential detection in files. This module implements PCI SSF 2.3 compliance requirements through protocol-based services that use dependency injection for testability and maintainability.
Architectural Principles¶
Design Goals¶
- Protocol-Based Design: Define clear contracts through protocols for all services
- External Tool Integration: Use proven tools like
detect-secretsfor credential detection - Streaming Architecture: Process large files with minimal memory usage
- Type Safety: Full type annotation coverage with MyPy compliance
- Dependency Injection: Services with clear separation of concerns
Key Benefits¶
- Security Compliance: Meet PCI SSF 2.3 requirements for credential detection
- Performance: Stream processing for large files with Excel export capabilities
- Maintainability: Protocol-based design enables easy testing and extension
- Integration: Seamless integration with external security tools
- User Experience: CLI with progress feedback and detailed reporting
Architecture Overview¶
Protocol Definitions¶
Core Analysis Protocols¶
The analyze module uses protocol-based design to define clear contracts:
kp_ssf_tools.analyze.services.interfaces.EntropyAnalyzerProtocol
¶
Bases: Protocol
Protocol for Shannon entropy calculation and analysis.
Source code in src\kp_ssf_tools\analyze\services\interfaces.py
Functions¶
analyze_file_entropy(file_path, *, analysis_block_size, step_size, file_chunk_size, force_file_type=None)
¶
Analyze entropy of a complete file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
Path
|
Path to file to analyze |
required |
analysis_block_size
|
int
|
Size of analysis blocks in bytes (from config) |
required |
step_size
|
int
|
Step size for sliding window (from config) |
required |
file_chunk_size
|
int
|
Size of file I/O chunks in bytes (from config) |
required |
force_file_type
|
FileType | None
|
Override automatic file type detection |
None
|
Returns:
| Type | Description |
|---|---|
FileAnalysisResult
|
Complete file analysis result |
Source code in src\kp_ssf_tools\analyze\services\interfaces.py
analyze_sliding_window(data, window_size, step_size)
¶
Perform sliding window entropy analysis.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
bytes
|
Data to analyze |
required |
window_size
|
int
|
Size of analysis window in bytes |
required |
step_size
|
int
|
Step size for sliding window |
required |
Returns:
| Type | Description |
|---|---|
list[EntropyRegion]
|
List of entropy regions with analysis results |
Source code in src\kp_ssf_tools\analyze\services\interfaces.py
calculate_entropy(data)
¶
Calculate Shannon entropy for data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
bytes
|
Data to analyze |
required |
Returns:
| Type | Description |
|---|---|
float
|
Shannon entropy in bits per byte (0.0-8.0) |
kp_ssf_tools.analyze.services.interfaces.CredentialDetectionProtocol
¶
Bases: Protocol
Protocol for credential detection services that scan for sensitive information.
Source code in src\kp_ssf_tools\analyze\services\interfaces.py
Functions¶
analyze_files(target_paths, config, options=None)
¶
Analyze files for credential patterns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target_paths
|
list[Path]
|
List of paths to analyze |
required |
config
|
dict[str, dict[str, object]]
|
Analysis configuration |
required |
options
|
CredentialScanOptions | None
|
Optional scanning configuration |
None
|
Returns:
| Type | Description |
|---|---|
CredentialAnalysisResult
|
Analysis result with detected credentials |
Source code in src\kp_ssf_tools\analyze\services\interfaces.py
get_supported_patterns()
¶
Get list of supported credential patterns.
Returns:
| Type | Description |
|---|---|
list[str]
|
List of pattern names/types this detector supports |
scan_directory(directory_path, options=None)
¶
Scan a directory recursively for credential patterns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directory_path
|
Path
|
Path to directory to scan |
required |
options
|
CredentialScanOptions | None
|
Optional scanning configuration |
None
|
Returns:
| Type | Description |
|---|---|
dict[Path, list[CryptoStructure]]
|
Dictionary mapping file paths to detected credentials |
Source code in src\kp_ssf_tools\analyze\services\interfaces.py
scan_file(file_path, options=None)
¶
Scan a single file for credential patterns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
Path
|
Path to file to scan |
required |
options
|
CredentialScanOptions | None
|
Optional scanning configuration |
None
|
Returns:
| Type | Description |
|---|---|
list[CryptoStructure]
|
List of detected credential structures |
Source code in src\kp_ssf_tools\analyze\services\interfaces.py
Supporting Protocols¶
kp_ssf_tools.analyze.services.interfaces.FileTypeClassifierProtocol
¶
Bases: Protocol
Protocol for file type detection and classification.
Source code in src\kp_ssf_tools\analyze\services\interfaces.py
Functions¶
classify_file(file_path)
¶
Classify file type and detect programming language.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
Path
|
Path to the file to classify |
required |
Returns:
| Type | Description |
|---|---|
tuple[FileType, str | None]
|
Tuple of (FileType, programming_language_or_None) |
Source code in src\kp_ssf_tools\analyze\services\interfaces.py
load_file_content(file_path)
¶
Load file content for analysis.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
Path
|
Path to the file to load |
required |
Returns:
| Type | Description |
|---|---|
bytes
|
File content as bytes |
kp_ssf_tools.analyze.services.interfaces.ThresholdProviderProtocol
¶
Bases: Protocol
Protocol for content-aware entropy threshold management.
Source code in src\kp_ssf_tools\analyze\services\interfaces.py
Functions¶
classify_entropy_level(entropy, file_type)
¶
Classify entropy level based on content-aware thresholds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
entropy
|
float
|
Shannon entropy value |
required |
file_type
|
FileType
|
The detected file type |
required |
Returns:
| Type | Description |
|---|---|
EntropyLevel
|
Entropy level classification enum |
Source code in src\kp_ssf_tools\analyze\services\interfaces.py
get_thresholds(file_type)
¶
Get entropy thresholds for specific file type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_type
|
FileType
|
The detected file type |
required |
Returns:
| Type | Description |
|---|---|
ContentAwareThresholds
|
ContentAwareThresholds model with all threshold values |
Source code in src\kp_ssf_tools\analyze\services\interfaces.py
Credential Detection Implementation¶
DetectSecretsCredentialService¶
The credential detection service integrates with the industry-standard detect-secrets tool through subprocess execution:
kp_ssf_tools.analyze.services.detect_secrets_service.DetectSecretsCredentialService
¶
Credential detection service using detect-secrets as backend.
Source code in src\kp_ssf_tools\analyze\services\detect_secrets_service.py
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 | |
Functions¶
__init__(rich_output, timestamp_service, file_discovery, file_processing)
¶
Initialize the detect-secrets credential detection service.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rich_output
|
RichOutputService
|
Service for displaying progress and results |
required |
timestamp_service
|
TimestampProtocol
|
Service for timestamp operations |
required |
file_discovery
|
FileDiscoveryService
|
Service for discovering files to analyze |
required |
file_processing
|
FileProcessingService
|
Service for file type detection and processing |
required |
Source code in src\kp_ssf_tools\analyze\services\detect_secrets_service.py
analyze_files(target_paths, config, options)
¶
Analyze files using detect-secrets and return results in existing format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target_paths
|
list[Path]
|
List of file or directory paths to analyze |
required |
config
|
dict[str, Any]
|
Analysis configuration |
required |
options
|
CredentialScanOptions
|
Scanning options and parameters |
required |
Returns:
| Type | Description |
|---|---|
CredentialAnalysisResult
|
Analysis result containing detected patterns |
Source code in src\kp_ssf_tools\analyze\services\detect_secrets_service.py
Integration Architecture¶
The credential detection follows this execution flow:
- Command Construction: Build
detect-secrets scancommand with configuration options - Subprocess Execution: Execute
detect-secretswith security controls and timeout - JSON Processing: Parse JSON output from
detect-secrets - Result Conversion: Transform detect-secrets results to
CredentialPatternobjects - Excel Export: Stream results to Excel with per-file worksheets
Security Considerations¶
The subprocess integration implements security measures:
- Command Validation: Commands must start with
detect-secrets - Timeout Control: 5-minute timeout prevents hanging processes
- Error Handling: Error management for missing tools and failures
- Input Sanitization: Validated command construction with internal components
Configuration Models¶
Analysis Configuration¶
The module uses structured configuration models for type safety:
kp_ssf_tools.analyze.models.configuration.AnalysisConfiguration
¶
Bases: BaseConfiguration
Complete security analysis configuration.
Inherits common output and network settings from BaseConfiguration. Contains analysis-specific configuration options for entropy analysis, wordlist detection, and cryptographic structure detection.
Source code in src\kp_ssf_tools\analyze\models\configuration.py
Credential Scan Options¶
kp_ssf_tools.analyze.services.interfaces.CredentialScanOptions
¶
Bases: NamedTuple
Options for credential scanning operations.
Source code in src\kp_ssf_tools\analyze\services\interfaces.py
Service Implementations¶
Entropy Analysis Service¶
The entropy analyzer provides Shannon entropy calculation with content-aware thresholds:
kp_ssf_tools.analyze.services.entropy.analyzer.EntropyAnalyzer
¶
Shannon entropy analyzer with content-aware thresholds and chunk processing.
Implements normalized Shannon entropy calculation with file-type-specific thresholds for PCI SSF 2.3 compliance detection. Uses dependency injection for core services and file processing capabilities.
Source code in src\kp_ssf_tools\analyze\services\entropy\analyzer.py
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 | |
Functions¶
__init__(rich_output, timestamp_service, file_validator, mime_detector, file_processing, threshold_manager)
¶
Initialize entropy analyzer with injected core services.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rich_output
|
RichOutputProtocol
|
Rich output service for progress reporting and results display |
required |
timestamp_service
|
TimestampProtocol
|
Timestamp service for analysis timing |
required |
file_validator
|
FileValidator
|
File validation service |
required |
mime_detector
|
MimeTypeDetector
|
MIME type detection service for file classification |
required |
file_processing
|
FileProcessingService
|
Service for file processing operations |
required |
threshold_manager
|
ThresholdProviderProtocol
|
Content-aware threshold management service |
required |
Source code in src\kp_ssf_tools\analyze\services\entropy\analyzer.py
analyze_data_chunk(data, file_type)
¶
Analyze entropy of a single data chunk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
bytes
|
Binary data chunk to analyze |
required |
file_type
|
FileType
|
File type for content-aware classification |
required |
Returns:
| Type | Description |
|---|---|
EntropyRegion
|
EntropyRegion with analysis results |
Source code in src\kp_ssf_tools\analyze\services\entropy\analyzer.py
analyze_file_entropy(file_path, *, analysis_block_size, step_size, file_chunk_size, force_file_type=None, progress_callback=None)
¶
Analyze entropy of a complete file using sliding window approach.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
Path
|
Path to file to analyze |
required |
analysis_block_size
|
int
|
Size of analysis blocks in bytes (from config) |
required |
step_size
|
int
|
Step size for sliding window (from config) |
required |
file_chunk_size
|
int
|
Size of file I/O chunks in bytes (from config) |
required |
force_file_type
|
FileType | None
|
Override automatic file type detection |
None
|
progress_callback
|
object | None
|
Optional callback for progress updates (progress, task_id) |
None
|
Returns:
| Type | Description |
|---|---|
tuple[float, list[EntropyRegion]]
|
Tuple of (overall_entropy, entropy_regions) |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If file doesn't exist |
ValueError
|
If file is empty or unreadable |
Source code in src\kp_ssf_tools\analyze\services\entropy\analyzer.py
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 | |
analyze_file_generator(file_path, *, min_risk_level=EntropyLevel.MEDIUM_HIGH, file_chunk_size=65536, analysis_block_size=64, step_size=16, force_file_type=None, include_samples=False)
¶
Generate analysis results as they're computed.
Yields high-risk regions immediately, summary at end.
Memory efficient streaming analysis - only creates objects for regions that meet the risk threshold criteria.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
Path
|
Path to file to analyze |
required |
min_risk_level
|
EntropyLevel
|
Minimum risk level to yield regions |
MEDIUM_HIGH
|
file_chunk_size
|
int
|
Size of file I/O chunks in bytes |
65536
|
analysis_block_size
|
int
|
Size of analysis blocks in bytes |
64
|
step_size
|
int
|
Step size for sliding window |
16
|
force_file_type
|
FileType | None
|
Override automatic file type detection |
None
|
include_samples
|
bool
|
Whether to include data samples in regions |
False
|
Yields:
| Type | Description |
|---|---|
Generator[AnalysisYield]
|
AnalysisYield objects containing either: |
Generator[AnalysisYield]
|
|
Generator[AnalysisYield]
|
|
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If file doesn't exist |
ValueError
|
If file is empty or unreadable |
Source code in src\kp_ssf_tools\analyze\services\entropy\analyzer.py
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 | |
calculate_shannon_entropy(data)
¶
Calculate Shannon entropy for binary data in bits per byte.
Uses the standard Shannon entropy formula: H(X) = -sum(p(x) * log2(p(x))) where p(x) is the probability of byte value x.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
bytes
|
Binary data to analyze |
required |
Returns:
| Type | Description |
|---|---|
float
|
Shannon entropy in bits per byte (0.0 to 8.0, where 8.0 is maximum entropy) |
Raises:
| Type | Description |
|---|---|
ValueError
|
If data is empty |
Note
- Maximum entropy (8.0): All 256 byte values occur with equal probability
- Minimum entropy (0.0): Only one byte value occurs
- Result range [0, 8] matches research-based thresholds in configuration
Source code in src\kp_ssf_tools\analyze\services\entropy\analyzer.py
get_entropy_threshold(file_type, level)
¶
Get entropy threshold for a specific file type and level.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_type
|
FileType
|
Type of file being analyzed |
required |
level
|
EntropyLevel
|
Entropy level to get threshold for |
required |
Returns:
| Type | Description |
|---|---|
float
|
Entropy threshold value (0.0 to 1.0) |
Source code in src\kp_ssf_tools\analyze\services\entropy\analyzer.py
get_file_language(file_path)
¶
Get detected programming language for a file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
Path
|
Path to file |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
Language name string or None if detection fails |
Source code in src\kp_ssf_tools\analyze\services\entropy\analyzer.py
get_file_mime_type(file_path)
¶
Get MIME type for a file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
Path
|
Path to file |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
MIME type string or None if detection fails |
Source code in src\kp_ssf_tools\analyze\services\entropy\analyzer.py
File Type Classification¶
File type detection is integrated into the entropy analyzer service:
kp_ssf_tools.analyze.services.entropy.analyzer.EntropyAnalyzer._detect_file_type(file_path)
¶
Detect file type using MIME detection service.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
Path
|
Path to file to classify |
required |
Returns:
| Type | Description |
|---|---|
FileType
|
Detected FileType |
Source code in src\kp_ssf_tools\analyze\services\entropy\analyzer.py
Threshold Management¶
The threshold service provides content-aware entropy thresholds based on file types:
kp_ssf_tools.analyze.services.threshold_service.ContentAwareThresholdManager
¶
Manages content-aware thresholds for different file types.
Concrete implementation of the ThresholdProviderProtocol.
Source code in src\kp_ssf_tools\analyze\services\threshold_service.py
Functions¶
classify_entropy_level(entropy, file_type)
¶
Classify entropy level based on content-aware thresholds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
entropy
|
float
|
Shannon entropy value |
required |
file_type
|
FileType
|
The detected file type |
required |
Returns:
| Type | Description |
|---|---|
EntropyLevel
|
Entropy level classification enum |
Source code in src\kp_ssf_tools\analyze\services\threshold_service.py
Subprocess Integration Pattern¶
The credential detection service demonstrates secure subprocess integration with external tools. This pattern provides several benefits:
- Tool Reuse: Leverage proven security tools without reimplementation
- Security Controls: Implement timeout and validation safeguards
- Error Handling: Error management for external dependencies
- Result Processing: Transform external tool output to internal models
Command Construction¶
The service builds validated commands with configuration options:
kp_ssf_tools.analyze.services.detect_secrets_service.DetectSecretsCredentialService._build_config_options(config)
¶
Build configuration options for detect-secrets command.
Source code in src\kp_ssf_tools\analyze\services\detect_secrets_service.py
Secure Execution¶
Command execution includes security controls and error handling:
kp_ssf_tools.analyze.services.detect_secrets_service.DetectSecretsCredentialService._execute_scan_command(cmd)
¶
Execute the detect-secrets scan command safely and return JSON results.
Source code in src\kp_ssf_tools\analyze\services\detect_secrets_service.py
Container Integration¶
The analyze module integrates with the dependency injection container system for service management and configuration.
Application Container¶
Services are registered in the application container with proper dependency resolution:
kp_ssf_tools.containers.application.ApplicationContainer.analysis = providers.Container(AnalysisContainer, core=core)
class-attribute
instance-attribute
¶
Configuration Services¶
Configuration management uses the core configuration service pattern:
kp_ssf_tools.core.services.config.service.ConfigurationService
¶
Bases: Generic[ConfigT]
Configuration service implementation with dependency injection.
Source code in src\kp_ssf_tools\core\services\config\service.py
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 | |
Functions¶
__init__(config_model, rich_output, timestamp_service, config_section)
¶
Initialize configuration service.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config_model
|
type[ConfigT]
|
Pydantic model class for this configuration type |
required |
rich_output
|
RichOutputProtocol
|
Rich output service for user feedback |
required |
timestamp_service
|
TimestampProtocol
|
Timestamp service for configuration metadata |
required |
config_section
|
str
|
Section name in unified config file (e.g., "entropy", "volatility") |
required |
Source code in src\kp_ssf_tools\core\services\config\service.py
create_default_config(section)
¶
Create default configuration for specific section.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
section
|
str
|
Configuration section name (used for metadata) |
required |
Returns:
| Type | Description |
|---|---|
ConfigT
|
Default configuration instance |
Source code in src\kp_ssf_tools\core\services\config\service.py
discover_config_files(search_paths)
¶
Discover configuration files in search paths.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
search_paths
|
list[Path]
|
Paths to search for configuration files |
required |
Returns:
| Type | Description |
|---|---|
list[ConfigurationSource]
|
List of discovered configuration sources |
Source code in src\kp_ssf_tools\core\services\config\service.py
get_config_paths()
¶
Get standard configuration file paths for unified ssf-tools config (platform-independent).
Returns:
| Type | Description |
|---|---|
list[Path]
|
List of paths in priority order (highest to lowest) |
Source code in src\kp_ssf_tools\core\services\config\service.py
load_config(config_path=None, command_overrides=None)
¶
Load configuration from unified config file(s) with CLI overrides.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config_path
|
Path | None
|
Path to unified configuration file (None for default search) |
None
|
command_overrides
|
ConfigOverrides
|
CLI overrides to apply |
None
|
Returns:
| Type | Description |
|---|---|
ConfigT
|
Loaded and merged configuration for this service's section |
Source code in src\kp_ssf_tools\core\services\config\service.py
merge_configurations(base, overrides)
¶
Merge configuration with runtime overrides.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base
|
ConfigT
|
Base configuration |
required |
overrides
|
ConfigDict
|
Override values to apply |
required |
Returns:
| Type | Description |
|---|---|
ConfigT
|
Merged configuration |
Source code in src\kp_ssf_tools\core\services\config\service.py
save_config(config, config_path)
¶
Save configuration to unified config file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
ConfigT
|
Configuration to save |
required |
config_path
|
Path
|
Target file path |
required |
Source code in src\kp_ssf_tools\core\services\config\service.py
validate_config(config)
¶
Validate configuration and return detailed results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
ConfigT | ConfigDict
|
Configuration to validate (model instance or dict) |
required |
Returns:
| Type | Description |
|---|---|
ValidationResult
|
Validation result with errors, warnings, and deprecated fields |
Source code in src\kp_ssf_tools\core\services\config\service.py
CLI Integration¶
The analyze module exposes two main commands through the CLI interface. These commands provide file analysis capabilities with configurable options for different security assessment scenarios.
Command Structure¶
You can access entropy and credential analysis through dedicated CLI commands:
kp_ssf_tools.cli.commands.analyze.entropy(target, risk_threshold, file_block_size, analysis_block_size, step_size, ignore_pattern, *, no_recurse, include_samples, analyzer=Provide[ApplicationContainer.entropy.analyzer], rich_output=Provide[ApplicationContainer.core.rich_output], file_discovery=Provide[ApplicationContainer.core.file_discoverer], global_config_service=Provide[ApplicationContainer.core.global_config_service], entropy_config_service=Provide[ApplicationContainer.core.entropy_config_service], timestamp_service=Provide[ApplicationContainer.core.timestamp])
¶
Analyze entropy of files for PCI SSF 2.3 compliance.
Performs Shannon entropy analysis using content-aware thresholds to detect potentially suspicious patterns in files. Results are streamed directly to Excel with minimal memory usage.
Arguments:
Examples:
# Basic file analysis
ssf_tools analyze entropy sample.bin
# Analyze with higher risk threshold (fewer results)
ssf_tools analyze entropy sample.bin --risk-threshold high
# Analyze with custom block size
ssf_tools analyze entropy sample.bin --analysis-block-size 128
# Override file type detection
ssf_tools analyze entropy app.exe --force-file-type windows_pe
# Analyze directory non-recursively
ssf_tools analyze entropy data/ --no-recurse
Source code in src\kp_ssf_tools\cli\commands\analyze.py
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 | |
kp_ssf_tools.cli.commands.analyze.credentials(target, *, recursive, file_extensions, context_lines, scan_binary, max_binary_size, credential_service=Provide[ApplicationContainer.analysis.active_credential_service], rich_output=Provide[ApplicationContainer.core.rich_output], excel_service=Provide[ApplicationContainer.core.excel_export_service], timestamp_service=Provide[ApplicationContainer.core.timestamp], global_config_service=Provide[ApplicationContainer.core.global_config_service], analysis_config_service=Provide[ApplicationContainer.core.entropy_config_service])
¶
Detect credentials in files for PCI SSF 2.3 compliance.
Analyzes files for embedded credentials including usernames, passwords, API keys, and other sensitive information. Uses wordlists from SecLists and regex patterns to identify potential security issues.
Results are automatically exported to Excel with per-file worksheets
and a summary sheet. Output filename: analyze-credentials-
Arguments:
Examples:
# Basic credential detection
ssf_tools analyze credentials sample.py
# Analyze specific file types only
ssf_tools analyze credentials data/ --file-extensions .py --file-extensions .js
# Include more context around matches
ssf_tools analyze credentials config/ --context-lines 5
# Skip binary files to speed up analysis
ssf_tools analyze credentials project/ --no-scan-binary
Source code in src\kp_ssf_tools\cli\commands\analyze.py
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 | |
Processing Pipeline¶
Both commands use a consistent file processing pattern:
kp_ssf_tools.cli.commands.analyze._process_files(files_to_analyze, output_path, risk_level, context, processing_config)
¶
Process all files and return (files_analyzed, high_risk_regions, total_time).
Source code in src\kp_ssf_tools\cli\commands\analyze.py
Data Models¶
Analysis Results¶
The module defines structured result models for type safety:
kp_ssf_tools.analyze.models.analysis.EntropyAnalysisResult
¶
Bases: SSFToolsBaseModel
Complete analysis results for all processed files.
Source code in src\kp_ssf_tools\analyze\models\analysis.py
kp_ssf_tools.analyze.models.analysis.CredentialAnalysisResult
¶
Bases: SSFToolsBaseModel
Result from credential analysis containing all detected patterns.
Source code in src\kp_ssf_tools\analyze\models\analysis.py
Pattern Detection¶
Credential patterns include location and context information:
kp_ssf_tools.analyze.models.analysis.CredentialPattern
¶
Bases: DetectedCredential
A pattern detected by credential analysis.
Source code in src\kp_ssf_tools\analyze\models\analysis.py
Usage Examples¶
Entropy Analysis¶
Analyze files for high-entropy regions that may indicate embedded cryptographic material:
# Basic entropy analysis
ssf_tools analyze entropy sample.bin
# Directory analysis with custom threshold
ssf_tools analyze entropy data/ --risk-threshold high
# Custom analysis parameters
ssf_tools analyze entropy large_file.exe --analysis-block-size 128 --step-size 32
Credential Detection¶
Detect embedded credentials using the detect-secrets backend:
# Basic credential detection
ssf_tools analyze credentials project/
# Specific file types with context
ssf_tools analyze credentials src/ --file-extensions .py --file-extensions .js --context-lines 5
# Skip binary files for faster analysis
ssf_tools analyze credentials config/ --no-scan-binary
Performance Considerations¶
Entropy Analysis¶
- Streaming Processing: Large files processed in chunks to minimize memory usage
- Content-Aware Thresholds: Reduce false positives through file-type-specific thresholds
- Configurable Block Sizes: Tune analysis parameters for different file types
Credential Detection¶
- External Tool Efficiency: Use
detect-secretsoptimized pattern matching - File Type Filtering: Focus analysis on relevant file types
- Binary File Handling: Optional binary file scanning with size limits
Excel Export¶
- Streaming Export: Direct-to-Excel streaming prevents memory exhaustion
- Row Limit Management: Automatic warnings when approaching Excel limits
- Worksheet Organization: Per-file worksheets with summary sheet
Testing Patterns¶
Protocol-Based Testing¶
The protocol-based design enables testing through mocking:
from unittest.mock import Mock
from kp_ssf_tools.analyze.services.interfaces import CredentialDetectionProtocol
def test_credential_analysis():
# Mock the credential detection service
mock_service = Mock(spec=CredentialDetectionProtocol)
mock_service.analyze_files.return_value = CredentialAnalysisResult(
file_path=Path("test.py"),
patterns=[],
total_patterns=0,
processed_files=[Path("test.py")]
)
# Test with mocked service
result = mock_service.analyze_files([Path("test.py")], {}, None)
assert result.total_patterns == 0
Subprocess Testing¶
The subprocess integration requires careful testing with mocked external tools:
from unittest.mock import patch, MagicMock
@patch('subprocess.run')
def test_detect_secrets_integration(mock_run):
# Mock detect-secrets output
mock_run.return_value = MagicMock(
returncode=0,
stdout='{"results": {}}',
stderr=''
)
service = DetectSecretsCredentialService(mock_output, mock_timestamp, mock_discovery, mock_processing)
result = service.analyze_files([Path("test.py")], {}, CredentialScanOptions())
# Verify subprocess called correctly
mock_run.assert_called_once()
assert "detect-secrets" in mock_run.call_args[0][0]
Implementation Status¶
The analyze module implements a security analysis solution:
- ✅ Shannon Entropy Analysis: Content-aware threshold system with streaming Excel export
- ✅ Credential Detection: Integration with
detect-secretsfor pattern detection - ✅ Protocol-Based Design: Architecture supporting multiple analysis types
- ✅ CLI Integration: Command-line interface with progress feedback
- ✅ Container Integration: Dependency injection with configuration management
- ✅ Type Safety: Type annotation coverage with validation
- ✅ Testing Framework: Test patterns for all components
Future Enhancements¶
Planned improvements include:
- Additional Detectors: Support for custom credential detection patterns
- Performance Optimization: Parallel processing for large directory analysis
- Report Formats: Additional export formats beyond Excel
- Integration APIs: Programmatic access for external tool integration