Artifacts Generated: File Open, File Write
Summary
Thecp function copies a specified file from one location to another location on the file system. This command performs a complete file copy operation, creating an exact duplicate of the source file at the destination path. The implementation includes comprehensive validation to ensure the source is a file (not a directory) and generates appropriate artifacts for both the read and write operations for audit tracking.
- Needs Admin: False
- Version: 2
- Author: @djhohnstein
Arguments
- source (String) - Path to the source file to copy
- CLI Name: Path
- Display Name: Source file to copy
- Description: Source file to copy
- Required: True
- destination (String) - Path where the copied file will be created
- CLI Name: Destination
- Display Name: Destination path
- Description: Where the new file will be created
- Required: True
Usage
Example 1: Basic File Copy
Command:Example 2: Copy to Different Directory
Command:Example 3: Copy with Quoted Paths
Command:Example 4: Directory Copy Attempt (Error)
Command:Example 5: File Not Found (Error)
Command:Example 6: Access Denied (Error)
Command:Detailed Summary
Thecp function implements a comprehensive file copying system with validation, error handling, and audit trail generation:
1. Parameter Processing and Structure
The function uses a dedicated parameter structure for source and destination paths:- Source File: The file to be copied (must be a file, not a directory)
- Destination File: The target location for the copied file
- JSON Mapping: Uses DataContract attributes for proper JSON deserialization
- Required Fields: Both source and destination are required parameters
2. Command Line Parsing Implementation
The Python handler implements sophisticated argument parsing for flexible input:- Quote-Aware Splitting: Properly handles spaces within quoted paths
- Quote Removal: Automatically removes surrounding quotes from parsed arguments
- Two-Argument Validation: Ensures exactly two arguments are provided
- JSON Support: Supports both command line and JSON parameter formats
3. Core File Copy Implementation
The main copy operation includes comprehensive validation and error handling:- Parameter Deserialization: Extracts source and destination paths
- Source Validation: Creates
FileInfoobject and validates it’s not a directory - Artifact Generation: Creates
FileOpenartifact for source file access - File Copy Operation: Uses
File.Copy()to perform the actual copy - Success Artifacts: Generates
FileWriteandFileBrowserartifacts for destination - Error Handling: Catches all exceptions and provides detailed error messages
4. Directory Detection and Validation
The implementation specifically validates that the source is a file, not a directory:- FileInfo Creation: Creates
FileInfoobject to access file attributes - Directory Check: Uses
FileAttributes.Directoryflag to detect directories - Specific Error Message: Provides clear error message for directory sources
- Early Exit: Prevents attempting to copy directories with
File.Copy()
5. Artifact Generation and Tracking
The command generates multiple artifacts for comprehensive audit tracking: Source File Artifacts:- File Open: Records access to the source file with full path
- File Write: Records creation of destination file with file size
- File Browser: Updates Mythic’s file browser with the new file
- Timeline Integration: All artifacts are timestamped and associated with the task
6. File System Operations
The command uses .NET Framework’s built-in file operations:- Complete Copy: Creates exact duplicate of source file
- Metadata Preservation: Preserves file attributes, timestamps (creation time may change)
- Overwrite Behavior: Uses default overwrite behavior (will fail if destination exists)
- Exception Handling: Throws exceptions for various error conditions
- Path Resolution: Handles both absolute and relative paths
7. Error Handling and Exception Management
The implementation includes comprehensive error handling for various failure scenarios: Handled Error Types:- File Not Found: Source file doesn’t exist
- Access Denied: Insufficient permissions for source or destination
- Path Too Long: Paths exceed Windows limitations
- Disk Full: Insufficient space for destination file
- File In Use: Source or destination file is locked by another process
- Network Issues: Problems with UNC paths or network drives
8. Path Handling and Resolution
The system handles various path formats and scenarios: Supported Path Types:- Absolute Paths: Full paths from drive root (
C:\path\file.txt) - Relative Paths: Paths relative to current directory (
.\file.txt,subfolder\file.txt) - UNC Paths: Network paths (
\\server\share\file.txt) - Mixed Scenarios: Source and destination can use different path types
- FileInfo Resolution: Uses
FileInfoto resolve and validate paths - Full Path Confirmation: Response shows fully resolved paths
- Cross-Directory Copy: Supports copying between different directories and drives
9. Display and Response Management
The command provides detailed feedback about copy operations: Success Response Format:- Directory error:
"{path} is a directory. Please specify a file." - General error:
"Failed to copy file: {exception message}"
10. Security and Permission Considerations
The copy operation respects file system security: Security Aspects:- Source Permissions: Requires read access to source file
- Destination Permissions: Requires write access to destination directory
- User Context: Operates within Apollo agent’s security context
- ACL Inheritance: Destination file inherits ACLs from destination directory
- Audit Generation: Creates audit trail through artifact generation
MITRE ATT&CK Mapping
- T1570 - Lateral Tool Transfer
Technical Deep Dive
.NET File Copy Implementation
Thecp command leverages .NET Framework’s File.Copy() method:
File.Copy() Method Behavior
- Atomic Operation: Copy completes entirely or fails entirely
- Exception-Based Error Handling: Throws specific exceptions for different error conditions
- Default Overwrite Behavior: By default, fails if destination file already exists
- Metadata Handling: Preserves most file attributes but may update timestamps
- Performance: Optimized for the underlying file system (uses system-level copy operations)
File Attribute Checking
- FileAttributes Enum: Uses Windows file attribute flags
- Directory Detection: Specifically checks for directory attribute
- Multiple Attributes: Can detect files with multiple attributes (hidden, system, etc.)
- Performance: Minimal overhead for attribute checking
Command Line Parsing Algorithm
The Python handler implements a sophisticated parsing algorithm:Quote-Aware Parsing
Thesplit_commandline() method handles complex quoting scenarios:
- State Tracking: Maintains
inQuotesstate to track quote context - Quote Types: Handles both single and double quotes
- Space Handling: Only splits on spaces outside of quotes
- Quote Removal: Removes quotes from final parsed arguments
Validation Logic
- Exact Count: Requires exactly two arguments (source and destination)
- Clear Error Messages: Provides helpful error messages with usage information
- Flexible Input: Supports both positional arguments and JSON format
Artifact Generation Strategy
The command generates multiple artifacts for comprehensive tracking:Artifact Types and Purposes
-
File Open Artifact:
- Purpose: Records access to source file
- Timing: Generated before copy operation
- Data: Full path of source file
-
File Write Artifact:
- Purpose: Records creation of destination file
- Timing: Generated after successful copy
- Data: Full path and file size of destination
-
FileBrowser Artifact:
- Purpose: Updates Mythic’s file browser display
- Timing: Generated after successful copy
- Integration: Allows browsing to newly created file
Error Handling Patterns
The command implements multiple layers of error detection:Pre-Copy Validation
- Directory Detection: Prevents attempting to copy directories
- FileInfo Creation: Validates source path format and accessibility
- Attribute Checking: Ensures source is appropriate for copying
Runtime Exception Handling
- Comprehensive Catch: Catches all exceptions during copy operation
- Message Preservation: Preserves original exception messages
- Artifact Inclusion: Includes artifacts even in error responses for audit trail
Performance and Resource Considerations
Memory Usage
- Minimal Memory Footprint:
File.Copy()uses system-level operations - No Buffering: No manual buffering or chunk processing required
- Stream-Based: Uses efficient file streams at system level
I/O Characteristics
- System Call Optimization: Leverages optimized system copy operations
- Network Efficiency: Efficient for network paths (UNC shares)
- Concurrent Safety: Thread-safe operation through system-level locking
Common Use Cases and Examples
1. Configuration File Backup
2. Log File Preservation
3. Tool Staging
4. Data Exfiltration Preparation
5. System File Analysis
APIs Used and Their Purposes
Security Considerations
File System Permissions
- Source Access: Requires read permissions on source file
- Destination Access: Requires write permissions in destination directory
- ACL Inheritance: Destination file inherits security settings from target directory
- User Context: Limited by Apollo agent’s privilege level
Operational Security
- File Access Patterns: Copy operations may reveal reconnaissance activities
- Staging Behavior: Multiple file copies may indicate tool staging
- Data Movement: Large file copies may suggest data exfiltration
- Audit Trail: Generates comprehensive audit artifacts
Detection Considerations
- File System Monitoring: Copy operations may trigger file system audit events
- Behavioral Analysis: Unusual copy patterns may indicate malicious activity
- Network Monitoring: UNC path copies generate network traffic
- Performance Impact: Large file copies may affect system performance
Defensive Implications
- Access Monitoring: Monitor for copies of sensitive files
- Unusual Locations: Watch for files copied to temporary or staging directories
- Permission Escalation: Monitor for successful copies of restricted files
- Timeline Analysis: Correlate copy operations with other suspicious activities
Limitations
- File-Only Operation: Cannot copy directories (use directory-specific commands)
- No Overwrite Control: Uses default overwrite behavior of
File.Copy() - No Progress Reporting: No progress indication for large file copies
- Synchronous Operation: Blocks agent during copy operation
- No Resume Capability: Cannot resume interrupted copy operations
- Single File Limit: Can only copy one file per command execution
- Path Length Limits: Subject to Windows maximum path length restrictions
- No Verification: Does not verify integrity of copied file
Troubleshooting
Common Issues and Solutions
Debugging Steps
- Verify Source File: Use
lsto confirm source file exists and is accessible - Check Destination Directory: Ensure destination directory exists and is writable
- Test Permissions: Verify read access to source and write access to destination
- Path Validation: Check for invalid characters or excessive path lengths
- Quote Usage: Ensure proper quoting for paths with spaces
Best Practices
- Path Quoting: Always quote paths containing spaces or special characters
- Permission Verification: Check permissions before attempting copy operations
- Destination Planning: Ensure destination directory exists and has sufficient space
- Error Handling: Be prepared for permission and access errors
- Audit Awareness: Understand that copy operations generate audit trails