Clipboard Management for macOS
Implement enterprise-grade clipboard management across your MacFleet deployment with secure content distribution, automated text deployment, clipboard monitoring, and comprehensive policies for controlled information sharing. This tutorial provides solutions for managing clipboard operations while maintaining security and compliance standards.
Understanding macOS Clipboard Management
macOS provides several command-line tools for clipboard operations:
pbcopy
- Copy text or data to the system clipboardpbpaste
- Retrieve content from the system clipboardpbcopy -pboard
- Work with specific pasteboard types- Accessibility APIs - Monitor clipboard changes programmatically
- Security frameworks - Control clipboard access permissions
Basic Clipboard Operations
Copy Text to Clipboard
#!/bin/bash
# Basic clipboard copy operation
echo "Content to be copied to clipboard" | pbcopy
Enhanced Clipboard Copy
#!/bin/bash
# Enhanced clipboard copy with validation
CONTENT="$1"
if [[ -z "$CONTENT" ]]; then
echo "Error: No content provided"
exit 1
fi
# Copy content to clipboard
echo "$CONTENT" | pbcopy
if [[ $? -eq 0 ]]; then
echo "Content copied to clipboard successfully"
else
echo "Failed to copy content to clipboard"
exit 1
fi
Retrieve Clipboard Content
#!/bin/bash
# Retrieve and display clipboard content
CLIPBOARD_CONTENT=$(pbpaste)
if [[ -n "$CLIPBOARD_CONTENT" ]]; then
echo "Current clipboard content:"
echo "$CLIPBOARD_CONTENT"
else
echo "Clipboard is empty"
fi
Enterprise Clipboard Management System
Comprehensive Clipboard Management Tool
#!/bin/bash
# MacFleet Enterprise Clipboard Management Tool
# Secure content distribution and clipboard monitoring
# Configuration
CONFIG_FILE="/etc/macfleet/clipboard_policy.conf"
LOG_FILE="/var/log/macfleet_clipboard.log"
CACHE_DIR="/Library/MacFleet/Clipboard"
AUDIT_LOG="/var/log/macfleet_clipboard_audit.log"
# Create directories
mkdir -p "$(dirname "$CONFIG_FILE")" "$(dirname "$LOG_FILE")" "$CACHE_DIR" "$(dirname "$AUDIT_LOG")"
# Default clipboard policy
cat > "$CONFIG_FILE" 2>/dev/null << 'EOF' || true
# MacFleet Clipboard Management Policy
# Version: 2.0
# Content Security Settings
ALLOW_SENSITIVE_CONTENT=false
ENCRYPT_CLIPBOARD_LOGS=true
SANITIZE_CONTENT=true
MAX_CONTENT_LENGTH=10240
# Access Control
RESTRICT_CLIPBOARD_ACCESS=true
ALLOWED_APPLICATIONS=("TextEdit" "Notes" "Mail" "Slack" "Microsoft Word")
BLOCKED_APPLICATIONS=("Terminal" "Script Editor")
LOG_CLIPBOARD_OPERATIONS=true
# Content Filtering
FILTER_SENSITIVE_DATA=true
BLOCK_CREDIT_CARDS=true
BLOCK_SSN=true
BLOCK_PASSWORDS=true
CONTENT_SCAN_ENABLED=true
# Distribution Settings
ENTERPRISE_CONTENT_ENABLED=true
CONTENT_TEMPLATES_DIR="/Library/MacFleet/Templates"
SCHEDULED_CONTENT_ENABLED=false
CONTENT_EXPIRY_ENABLED=true
DEFAULT_EXPIRY_MINUTES=60
# Monitoring and Compliance
MONITOR_CLIPBOARD_CHANGES=true
AUDIT_CLIPBOARD_ACCESS=true
COMPLIANCE_ALERTS=true
SEND_USAGE_REPORTS=true
RETENTION_DAYS=90
# Security Settings
REQUIRE_ADMIN_APPROVAL=false
ENCRYPT_SENSITIVE_CONTENT=true
PREVENT_EXTERNAL_PASTE=false
CLEAR_ON_LOGOUT=true
EOF
# Source configuration
source "$CONFIG_FILE" 2>/dev/null || true
# Logging function
log_action() {
echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" | tee -a "$LOG_FILE"
}
# Audit logging function
audit_log() {
local action="$1"
local content_hash="$2"
local app_name="$3"
echo "$(date '+%Y-%m-%d %H:%M:%S') - ACTION:$action HASH:$content_hash APP:$app_name USER:$(whoami)" >> "$AUDIT_LOG"
}
# Content sanitization
sanitize_content() {
local content="$1"
local sanitized="$content"
if [[ "$SANITIZE_CONTENT" == "true" ]]; then
# Remove potential script injections
sanitized=$(echo "$sanitized" | sed 's/<script[^>]*>.*<\/script>//gi')
sanitized=$(echo "$sanitized" | sed 's/javascript:[^"]*//gi')
sanitized=$(echo "$sanitized" | sed 's/data:[^"]*//gi')
# Limit content length
if [[ ${#sanitized} -gt $MAX_CONTENT_LENGTH ]]; then
sanitized="${sanitized:0:$MAX_CONTENT_LENGTH}...[TRUNCATED]"
fi
fi
echo "$sanitized"
}
# Sensitive data detection
detect_sensitive_data() {
local content="$1"
local violations=()
if [[ "$FILTER_SENSITIVE_DATA" != "true" ]]; then
return 0
fi
# Credit card detection
if [[ "$BLOCK_CREDIT_CARDS" == "true" ]]; then
if echo "$content" | grep -E '\b[0-9]{4}[[:space:]-]?[0-9]{4}[[:space:]-]?[0-9]{4}[[:space:]-]?[0-9]{4}\b' >/dev/null; then
violations+=("Credit card number detected")
fi
fi
# SSN detection
if [[ "$BLOCK_SSN" == "true" ]]; then
if echo "$content" | grep -E '\b[0-9]{3}-[0-9]{2}-[0-9]{4}\b' >/dev/null; then
violations+=("Social Security Number detected")
fi
fi
# Password patterns
if [[ "$BLOCK_PASSWORDS" == "true" ]]; then
if echo "$content" | grep -i -E '(password|pwd|passwd|pass)[[:space:]]*[:=][[:space:]]*[^[:space:]]+' >/dev/null; then
violations+=("Password pattern detected")
fi
fi
# API keys and tokens
if echo "$content" | grep -E '\b[A-Za-z0-9+/]{40,}\b' >/dev/null; then
violations+=("Potential API key or token detected")
fi
# Return violations
if [[ ${#violations[@]} -gt 0 ]]; then
printf '%s\n' "${violations[@]}"
return 1
else
return 0
fi
}
# Application access control
check_app_permissions() {
local app_name="$1"
if [[ "$RESTRICT_CLIPBOARD_ACCESS" != "true" ]]; then
return 0
fi
# Get current application
if [[ -z "$app_name" ]]; then
app_name=$(osascript -e 'tell application "System Events" to get name of first application process whose frontmost is true' 2>/dev/null || echo "Unknown")
fi
# Check allowed applications
for allowed_app in "${ALLOWED_APPLICATIONS[@]}"; do
if [[ "$app_name" == "$allowed_app" ]]; then
echo "✅ Application $app_name is allowed"
return 0
fi
done
# Check blocked applications
for blocked_app in "${BLOCKED_APPLICATIONS[@]}"; do
if [[ "$app_name" == "$blocked_app" ]]; then
echo "❌ Application $app_name is blocked"
audit_log "BLOCKED_ACCESS" "N/A" "$app_name"
return 1
fi
done
# Default policy for unlisted applications
echo "⚠️ Application $app_name not in policy (defaulting to allowed)"
return 0
}
# Copy content to clipboard with enterprise features
enterprise_clipboard_copy() {
local content="$1"
local source_app="${2:-System}"
local force_copy="${3:-false}"
echo "=== Enterprise Clipboard Copy Operation ==="
# Validate input
if [[ -z "$content" ]]; then
echo "❌ No content provided"
return 1
fi
# Check application permissions
if ! check_app_permissions "$source_app"; then
echo "❌ Application not authorized for clipboard access"
return 1
fi
# Sanitize content
local sanitized_content
sanitized_content=$(sanitize_content "$content")
# Detect sensitive data
local violations
if violations=$(detect_sensitive_data "$sanitized_content"); then
if [[ "$force_copy" != "true" ]]; then
echo "❌ Sensitive data detected:"
echo "$violations"
audit_log "SENSITIVE_BLOCKED" "$(echo "$content" | md5)" "$source_app"
return 1
else
echo "⚠️ Sensitive data detected but force copy enabled"
log_action "WARNING: Sensitive data copied with force flag: $violations"
fi
fi
# Copy to clipboard
if echo "$sanitized_content" | pbcopy; then
echo "✅ Content copied to clipboard successfully"
# Log operation
local content_hash
content_hash=$(echo "$sanitized_content" | md5)
log_action "Clipboard copy successful - Hash: $content_hash - App: $source_app"
audit_log "COPY_SUCCESS" "$content_hash" "$source_app"
# Schedule content expiry if enabled
if [[ "$CONTENT_EXPIRY_ENABLED" == "true" ]]; then
schedule_clipboard_expiry "$DEFAULT_EXPIRY_MINUTES"
fi
return 0
else
echo "❌ Failed to copy content to clipboard"
log_action "FAILED: Clipboard copy operation"
audit_log "COPY_FAILED" "N/A" "$source_app"
return 1
fi
}
# Schedule clipboard content expiry
schedule_clipboard_expiry() {
local expiry_minutes="$1"
if [[ -n "$expiry_minutes" && $expiry_minutes -gt 0 ]]; then
# Create a background job to clear clipboard after expiry
(
sleep $((expiry_minutes * 60))
echo "" | pbcopy
log_action "Clipboard content expired and cleared after $expiry_minutes minutes"
) &
echo "🕒 Clipboard content will expire in $expiry_minutes minutes"
fi
}
# Retrieve clipboard content with security checks
enterprise_clipboard_paste() {
local requesting_app="${1:-System}"
echo "=== Enterprise Clipboard Paste Operation ==="
# Check application permissions
if ! check_app_permissions "$requesting_app"; then
echo "❌ Application not authorized for clipboard access"
return 1
fi
# Get clipboard content
local clipboard_content
clipboard_content=$(pbpaste)
if [[ -z "$clipboard_content" ]]; then
echo "📋 Clipboard is empty"
return 1
fi
# Log access
local content_hash
content_hash=$(echo "$clipboard_content" | md5)
log_action "Clipboard access - Hash: $content_hash - App: $requesting_app"
audit_log "PASTE_ACCESS" "$content_hash" "$requesting_app"
# Return content
echo "$clipboard_content"
return 0
}
# Deploy enterprise content templates
deploy_enterprise_content() {
local template_name="$1"
local target_users="${2:-all}"
echo "=== Enterprise Content Deployment ==="
echo "Template: $template_name"
echo "Target: $target_users"
if [[ "$ENTERPRISE_CONTENT_ENABLED" != "true" ]]; then
echo "❌ Enterprise content deployment disabled"
return 1
fi
# Load template
local template_file="$CONTENT_TEMPLATES_DIR/$template_name.txt"
if [[ ! -f "$template_file" ]]; then
echo "❌ Template not found: $template_file"
return 1
fi
local template_content
template_content=$(cat "$template_file")
# Process template variables
template_content=$(echo "$template_content" | sed "s/{{HOSTNAME}}/$(hostname)/g")
template_content=$(echo "$template_content" | sed "s/{{USER}}/$(whoami)/g")
template_content=$(echo "$template_content" | sed "s/{{DATE}}/$(date)/g")
template_content=$(echo "$template_content" | sed "s/{{TIMESTAMP}}/$(date '+%Y-%m-%d %H:%M:%S')/g")
# Deploy content
if enterprise_clipboard_copy "$template_content" "Enterprise_Deployment" "true"; then
echo "✅ Enterprise content deployed successfully"
log_action "Enterprise content deployed: $template_name"
return 0
else
echo "❌ Failed to deploy enterprise content"
return 1
fi
}
# Monitor clipboard changes
monitor_clipboard() {
echo "=== Starting Clipboard Monitoring ==="
if [[ "$MONITOR_CLIPBOARD_CHANGES" != "true" ]]; then
echo "Clipboard monitoring disabled"
return 0
fi
local previous_hash=""
local current_hash=""
echo "Monitoring clipboard changes... Press Ctrl+C to stop"
while true; do
current_hash=$(pbpaste | md5 2>/dev/null || echo "")
if [[ "$current_hash" != "$previous_hash" && -n "$current_hash" ]]; then
echo "🔄 Clipboard content changed at $(date)"
# Get current app
local current_app
current_app=$(osascript -e 'tell application "System Events" to get name of first application process whose frontmost is true' 2>/dev/null || echo "Unknown")
# Log change
log_action "Clipboard change detected - Hash: $current_hash - App: $current_app"
audit_log "CONTENT_CHANGED" "$current_hash" "$current_app"
# Check for sensitive content
local clipboard_content
clipboard_content=$(pbpaste)
if violations=$(detect_sensitive_data "$clipboard_content"); then
echo "⚠️ Sensitive data detected in clipboard:"
echo "$violations"
if [[ "$COMPLIANCE_ALERTS" == "true" ]]; then
log_action "COMPLIANCE ALERT: Sensitive data in clipboard - $violations"
fi
fi
previous_hash="$current_hash"
fi
sleep 2
done
}
# Generate clipboard usage report
generate_clipboard_report() {
local report_file="$CACHE_DIR/clipboard_report_$(date +%Y%m%d_%H%M%S).json"
echo "=== Generating Clipboard Usage Report ==="
# Analyze audit log
local total_operations=0
local copy_operations=0
local paste_operations=0
local blocked_operations=0
local sensitive_blocks=0
if [[ -f "$AUDIT_LOG" ]]; then
total_operations=$(wc -l < "$AUDIT_LOG")
copy_operations=$(grep -c "COPY_SUCCESS" "$AUDIT_LOG" || echo 0)
paste_operations=$(grep -c "PASTE_ACCESS" "$AUDIT_LOG" || echo 0)
blocked_operations=$(grep -c "BLOCKED_ACCESS" "$AUDIT_LOG" || echo 0)
sensitive_blocks=$(grep -c "SENSITIVE_BLOCKED" "$AUDIT_LOG" || echo 0)
fi
# Get current clipboard status
local current_content_length=0
local clipboard_content
clipboard_content=$(pbpaste 2>/dev/null || echo "")
if [[ -n "$clipboard_content" ]]; then
current_content_length=${#clipboard_content}
fi
# Create JSON report
cat > "$report_file" << EOF
{
"report_type": "clipboard_usage",
"timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
"device_info": {
"hostname": "$(hostname)",
"user": "$(whoami)",
"os_version": "$(sw_vers -productVersion)",
"serial_number": "$(system_profiler SPHardwareDataType | grep "Serial Number" | awk -F: '{print $2}' | xargs)"
},
"usage_statistics": {
"total_operations": $total_operations,
"copy_operations": $copy_operations,
"paste_operations": $paste_operations,
"blocked_operations": $blocked_operations,
"sensitive_content_blocks": $sensitive_blocks
},
"current_status": {
"clipboard_has_content": $([ -n "$clipboard_content" ] && echo true || echo false),
"content_length": $current_content_length,
"last_access": "$(tail -1 "$AUDIT_LOG" 2>/dev/null | awk '{print $1 " " $2}' || echo 'N/A')"
},
"policy_compliance": {
"monitoring_enabled": $MONITOR_CLIPBOARD_CHANGES,
"access_restrictions": $RESTRICT_CLIPBOARD_ACCESS,
"content_filtering": $FILTER_SENSITIVE_DATA,
"audit_logging": $AUDIT_CLIPBOARD_ACCESS
},
"security_events": {
"blocked_applications": $blocked_operations,
"sensitive_data_blocks": $sensitive_blocks,
"policy_violations": $((blocked_operations + sensitive_blocks))
}
}
EOF
echo "Clipboard usage report saved to: $report_file"
log_action "Clipboard usage report generated: $report_file"
}
# Clear clipboard securely
secure_clipboard_clear() {
echo "=== Secure Clipboard Clear ==="
# Clear clipboard multiple times to ensure data removal
for i in {1..3}; do
echo "" | pbcopy
sleep 0.1
done
# Verify clearing
local remaining_content
remaining_content=$(pbpaste)
if [[ -z "$remaining_content" ]]; then
echo "✅ Clipboard cleared securely"
log_action "Clipboard cleared securely"
audit_log "SECURE_CLEAR" "N/A" "System"
return 0
else
echo "⚠️ Clipboard may still contain data"
log_action "WARNING: Clipboard clear verification failed"
return 1
fi
}
# Main function with argument handling
main() {
log_action "=== MacFleet Clipboard Management Tool Started ==="
case "${1:-help}" in
"copy")
enterprise_clipboard_copy "$2" "$3" "$4"
;;
"paste")
enterprise_clipboard_paste "$2"
;;
"deploy")
deploy_enterprise_content "$2" "$3"
;;
"monitor")
monitor_clipboard
;;
"clear")
secure_clipboard_clear
;;
"report")
generate_clipboard_report
;;
"status")
echo "Current clipboard status:"
enterprise_clipboard_paste "System" | head -5
;;
"help"|*)
echo "MacFleet Clipboard Management Tool"
echo "Usage: $0 [command] [options]"
echo ""
echo "Commands:"
echo " copy <content> [app] [force] - Copy content to clipboard"
echo " paste [app] - Retrieve clipboard content"
echo " deploy <template> [users] - Deploy enterprise content"
echo " monitor - Monitor clipboard changes"
echo " clear - Securely clear clipboard"
echo " report - Generate usage report"
echo " status - Show clipboard status"
echo " help - Show this help message"
;;
esac
log_action "=== Clipboard management operation completed ==="
}
# Execute main function
main "$@"
Advanced Clipboard Management
Content Template System
#!/bin/bash
# Enterprise content template management
manage_content_templates() {
local action="$1"
local template_name="$2"
local template_content="$3"
echo "=== Content Template Management ==="
# Ensure templates directory exists
mkdir -p "$CONTENT_TEMPLATES_DIR"
case "$action" in
"create")
if [[ -z "$template_name" || -z "$template_content" ]]; then
echo "❌ Template name and content required"
return 1
fi
# Create template file
echo "$template_content" > "$CONTENT_TEMPLATES_DIR/$template_name.txt"
echo "✅ Template '$template_name' created"
log_action "Template created: $template_name"
;;
"list")
echo "Available templates:"
ls -1 "$CONTENT_TEMPLATES_DIR"/*.txt 2>/dev/null | xargs -I {} basename {} .txt || echo "No templates found"
;;
"delete")
if [[ -f "$CONTENT_TEMPLATES_DIR/$template_name.txt" ]]; then
rm "$CONTENT_TEMPLATES_DIR/$template_name.txt"
echo "✅ Template '$template_name' deleted"
log_action "Template deleted: $template_name"
else
echo "❌ Template '$template_name' not found"
fi
;;
"show")
if [[ -f "$CONTENT_TEMPLATES_DIR/$template_name.txt" ]]; then
echo "Template '$template_name' content:"
cat "$CONTENT_TEMPLATES_DIR/$template_name.txt"
else
echo "❌ Template '$template_name' not found"
fi
;;
*)
echo "Usage: manage_content_templates [create|list|delete|show] [template_name] [content]"
;;
esac
}
# Example template creation
create_default_templates() {
# Support contact template
manage_content_templates "create" "support_contact" "IT Support: help@company.com | Phone: +1-555-0123 | Portal: https://support.company.com"
# Meeting link template
manage_content_templates "create" "meeting_link" "Join our meeting: https://meet.company.com/{{USER}}-{{TIMESTAMP}}"
# Security reminder
manage_content_templates "create" "security_reminder" "Security Reminder: Never share passwords or sensitive information via clipboard. Report suspicious activity to security@company.com"
# Emergency contact
manage_content_templates "create" "emergency_contact" "Emergency IT Support: +1-555-HELP (4357) | Available 24/7 | Incident Report: security@company.com"
}
create_default_templates
Clipboard History Management
#!/bin/bash
# Advanced clipboard history with encryption
manage_clipboard_history() {
local action="$1"
local history_file="$CACHE_DIR/clipboard_history.enc"
local max_history_items=50
echo "=== Clipboard History Management ==="
case "$action" in
"save")
local current_content
current_content=$(pbpaste)
if [[ -n "$current_content" ]]; then
# Create history entry
local timestamp
timestamp=$(date '+%Y-%m-%d %H:%M:%S')
local content_hash
content_hash=$(echo "$current_content" | md5)
# Encrypt and save if sensitive content handling is enabled
if [[ "$ENCRYPT_SENSITIVE_CONTENT" == "true" ]]; then
echo "$timestamp|$content_hash|$(echo "$current_content" | base64)" >> "$history_file.tmp"
else
echo "$timestamp|$content_hash|$current_content" >> "$history_file.tmp"
fi
# Keep only last N items
tail -$max_history_items "$history_file.tmp" > "$history_file"
rm "$history_file.tmp"
echo "✅ Clipboard content saved to history"
log_action "Clipboard history saved - Hash: $content_hash"
fi
;;
"list")
if [[ -f "$history_file" ]]; then
echo "Recent clipboard history:"
cat "$history_file" | while IFS='|' read -r timestamp hash content; do
if [[ "$ENCRYPT_SENSITIVE_CONTENT" == "true" ]]; then
content=$(echo "$content" | base64 -d | head -c 50)
else
content=$(echo "$content" | head -c 50)
fi
echo "[$timestamp] $hash: ${content}..."
done
else
echo "No clipboard history found"
fi
;;
"restore")
local item_number="$2"
if [[ -f "$history_file" && -n "$item_number" ]]; then
local line_content
line_content=$(sed -n "${item_number}p" "$history_file")
if [[ -n "$line_content" ]]; then
local content
content=$(echo "$line_content" | cut -d'|' -f3-)
if [[ "$ENCRYPT_SENSITIVE_CONTENT" == "true" ]]; then
content=$(echo "$content" | base64 -d)
fi
echo "$content" | pbcopy
echo "✅ Clipboard restored from history item $item_number"
log_action "Clipboard restored from history item $item_number"
else
echo "❌ History item $item_number not found"
fi
else
echo "❌ Invalid item number or no history file"
fi
;;
"clear")
if [[ -f "$history_file" ]]; then
rm "$history_file"
echo "✅ Clipboard history cleared"
log_action "Clipboard history cleared"
else
echo "No history file to clear"
fi
;;
*)
echo "Usage: manage_clipboard_history [save|list|restore|clear] [item_number]"
;;
esac
}
# Auto-save clipboard changes to history
auto_save_clipboard() {
if [[ "$MONITOR_CLIPBOARD_CHANGES" == "true" ]]; then
# Save current content to history
manage_clipboard_history "save"
fi
}
# Example usage:
# manage_clipboard_history "list"
# manage_clipboard_history "restore" 3
Cross-Application Clipboard Policies
#!/bin/bash
# Application-specific clipboard policies
manage_app_policies() {
local action="$1"
local app_name="$2"
local policy_type="$3"
local policies_file="$CACHE_DIR/app_policies.conf"
echo "=== Application Clipboard Policies ==="
case "$action" in
"set")
# Set policy for specific application
if [[ -z "$app_name" || -z "$policy_type" ]]; then
echo "❌ Application name and policy type required"
return 1
fi
# Remove existing policy
grep -v "^$app_name:" "$policies_file" > "$policies_file.tmp" 2>/dev/null || touch "$policies_file.tmp"
# Add new policy
echo "$app_name:$policy_type" >> "$policies_file.tmp"
mv "$policies_file.tmp" "$policies_file"
echo "✅ Policy set for $app_name: $policy_type"
log_action "App policy set - $app_name: $policy_type"
;;
"get")
if [[ -f "$policies_file" && -n "$app_name" ]]; then
local policy
policy=$(grep "^$app_name:" "$policies_file" | cut -d':' -f2)
if [[ -n "$policy" ]]; then
echo "Policy for $app_name: $policy"
else
echo "No specific policy for $app_name (using default)"
fi
else
echo "No policies configured"
fi
;;
"list")
if [[ -f "$policies_file" ]]; then
echo "Configured application policies:"
cat "$policies_file" | while IFS=':' read -r app policy; do
echo " $app: $policy"
done
else
echo "No policies configured"
fi
;;
"remove")
if [[ -f "$policies_file" && -n "$app_name" ]]; then
grep -v "^$app_name:" "$policies_file" > "$policies_file.tmp"
mv "$policies_file.tmp" "$policies_file"
echo "✅ Policy removed for $app_name"
log_action "App policy removed - $app_name"
else
echo "❌ No policy found for $app_name"
fi
;;
*)
echo "Usage: manage_app_policies [set|get|list|remove] [app_name] [policy_type]"
echo "Policy types: allow, block, monitor, restricted"
;;
esac
}
# Check application policy before clipboard operation
check_app_policy() {
local app_name="$1"
local operation="$2"
local policies_file="$CACHE_DIR/app_policies.conf"
if [[ -f "$policies_file" ]]; then
local policy
policy=$(grep "^$app_name:" "$policies_file" | cut -d':' -f2)
case "$policy" in
"block")
echo "❌ Application $app_name is blocked from clipboard operations"
return 1
;;
"restricted")
echo "⚠️ Application $app_name has restricted clipboard access"
# Additional checks could be implemented here
return 0
;;
"monitor")
echo "🔍 Monitoring clipboard access for $app_name"
audit_log "MONITORED_ACCESS" "N/A" "$app_name"
return 0
;;
"allow"|*)
return 0
;;
esac
else
# Default policy
return 0
fi
}
# Example policy setup
setup_default_policies() {
manage_app_policies "set" "Terminal" "monitor"
manage_app_policies "set" "Script Editor" "restricted"
manage_app_policies "set" "TextEdit" "allow"
manage_app_policies "set" "Mail" "allow"
manage_app_policies "set" "Slack" "allow"
manage_app_policies "set" "Suspicious App" "block"
}
setup_default_policies
Monitoring and Compliance
Real-time Clipboard Monitoring
#!/bin/bash
# Advanced clipboard monitoring with alerts
advanced_clipboard_monitor() {
echo "=== Advanced Clipboard Monitoring ==="
local monitor_pid_file="$CACHE_DIR/clipboard_monitor.pid"
local alert_threshold=10 # Alert after 10 sensitive content detections per hour
local sensitive_count=0
local hour_start=$(date +%H)
# Store monitor PID
echo $$ > "$monitor_pid_file"
echo "Starting advanced clipboard monitoring..."
echo "Monitor PID: $$"
# Cleanup function
cleanup() {
echo "Stopping clipboard monitor..."
rm -f "$monitor_pid_file"
exit 0
}
trap cleanup SIGTERM SIGINT
local previous_content=""
while true; do
local current_content
current_content=$(pbpaste 2>/dev/null || echo "")
local current_hour
current_hour=$(date +%H)
# Reset counter each hour
if [[ "$current_hour" != "$hour_start" ]]; then
sensitive_count=0
hour_start="$current_hour"
fi
# Check for content changes
if [[ "$current_content" != "$previous_content" && -n "$current_content" ]]; then
local timestamp
timestamp=$(date '+%Y-%m-%d %H:%M:%S')
echo "[$timestamp] Clipboard content changed"
# Get current application
local current_app
current_app=$(osascript -e 'tell application "System Events" to get name of first application process whose frontmost is true' 2>/dev/null || echo "Unknown")
# Check for sensitive content
if violations=$(detect_sensitive_data "$current_content"); then
((sensitive_count++))
echo "⚠️ SECURITY ALERT: Sensitive data detected!"
echo "Application: $current_app"
echo "Violations: $violations"
# Log security event
log_action "SECURITY ALERT: Sensitive data in clipboard - App: $current_app - Violations: $violations"
audit_log "SENSITIVE_DETECTED" "$(echo "$current_content" | md5)" "$current_app"
# Check alert threshold
if [[ $sensitive_count -ge $alert_threshold ]]; then
echo "🚨 COMPLIANCE ALERT: Sensitive content threshold exceeded ($sensitive_count violations this hour)"
log_action "COMPLIANCE ALERT: Sensitive content threshold exceeded - $sensitive_count violations"
# Could trigger additional security measures here
# send_security_alert "$current_app" "$violations"
fi
fi
# Check application policy
check_app_policy "$current_app" "copy"
# Auto-save to history if enabled
if [[ "$MONITOR_CLIPBOARD_CHANGES" == "true" ]]; then
auto_save_clipboard
fi
previous_content="$current_content"
fi
sleep 1
done
}
# Start monitoring in background
start_clipboard_monitor() {
local monitor_pid_file="$CACHE_DIR/clipboard_monitor.pid"
if [[ -f "$monitor_pid_file" ]]; then
local existing_pid
existing_pid=$(cat "$monitor_pid_file")
if kill -0 "$existing_pid" 2>/dev/null; then
echo "Clipboard monitor already running (PID: $existing_pid)"
return 0
else
echo "Cleaning up stale monitor PID file"
rm -f "$monitor_pid_file"
fi
fi
echo "Starting clipboard monitor in background..."
advanced_clipboard_monitor &
local monitor_pid=$!
echo "Clipboard monitor started (PID: $monitor_pid)"
return 0
}
# Stop monitoring
stop_clipboard_monitor() {
local monitor_pid_file="$CACHE_DIR/clipboard_monitor.pid"
if [[ -f "$monitor_pid_file" ]]; then
local monitor_pid
monitor_pid=$(cat "$monitor_pid_file")
if kill -0 "$monitor_pid" 2>/dev/null; then
kill "$monitor_pid"
echo "Clipboard monitor stopped (PID: $monitor_pid)"
rm -f "$monitor_pid_file"
else
echo "Monitor process not found"
rm -f "$monitor_pid_file"
fi
else
echo "No monitor PID file found"
fi
}
# Example usage:
# start_clipboard_monitor
# stop_clipboard_monitor
Compliance Reporting and Audit
#!/bin/bash
# Comprehensive compliance reporting
generate_compliance_report() {
local report_period="${1:-daily}"
local output_format="${2:-json}"
echo "=== Generating Compliance Report ==="
echo "Period: $report_period"
echo "Format: $output_format"
local report_file="$CACHE_DIR/compliance_report_${report_period}_$(date +%Y%m%d_%H%M%S).$output_format"
# Calculate date range
local start_date
local end_date
end_date=$(date +%Y-%m-%d)
case "$report_period" in
"daily")
start_date=$(date +%Y-%m-%d)
;;
"weekly")
start_date=$(date -d '7 days ago' +%Y-%m-%d 2>/dev/null || date -v-7d +%Y-%m-%d)
;;
"monthly")
start_date=$(date -d '30 days ago' +%Y-%m-%d 2>/dev/null || date -v-30d +%Y-%m-%d)
;;
*)
start_date=$(date +%Y-%m-%d)
;;
esac
# Analyze audit logs
local total_operations=0
local security_violations=0
local blocked_operations=0
local unique_apps=0
if [[ -f "$AUDIT_LOG" ]]; then
# Filter logs by date range
local filtered_logs
filtered_logs=$(awk -v start="$start_date" -v end="$end_date" '$1 >= start && $1 <= end' "$AUDIT_LOG")
total_operations=$(echo "$filtered_logs" | wc -l)
security_violations=$(echo "$filtered_logs" | grep -c "SENSITIVE" || echo 0)
blocked_operations=$(echo "$filtered_logs" | grep -c "BLOCKED" || echo 0)
unique_apps=$(echo "$filtered_logs" | awk '{print $4}' | sort -u | wc -l)
fi
# Generate report based on format
if [[ "$output_format" == "json" ]]; then
cat > "$report_file" << EOF
{
"report_type": "clipboard_compliance",
"period": "$report_period",
"date_range": {
"start": "$start_date",
"end": "$end_date"
},
"generated": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
"device_info": {
"hostname": "$(hostname)",
"user": "$(whoami)",
"os_version": "$(sw_vers -productVersion)"
},
"compliance_metrics": {
"total_clipboard_operations": $total_operations,
"security_violations": $security_violations,
"blocked_operations": $blocked_operations,
"unique_applications": $unique_apps,
"compliance_score": $(( 100 - (security_violations * 10) - (blocked_operations * 5) ))
},
"policy_status": {
"monitoring_enabled": $MONITOR_CLIPBOARD_CHANGES,
"content_filtering": $FILTER_SENSITIVE_DATA,
"access_control": $RESTRICT_CLIPBOARD_ACCESS,
"audit_logging": $AUDIT_CLIPBOARD_ACCESS
},
"recommendations": [
$([ $security_violations -gt 5 ] && echo '"Increase security training for users",' || echo "")
$([ $blocked_operations -gt 10 ] && echo '"Review application access policies",' || echo "")
"Regular policy review and updates"
]
}
EOF
else
# Plain text format
cat > "$report_file" << EOF
MacFleet Clipboard Compliance Report
===================================
Generated: $(date)
Period: $report_period ($start_date to $end_date)
Device: $(hostname) ($(whoami))
COMPLIANCE METRICS:
- Total clipboard operations: $total_operations
- Security violations: $security_violations
- Blocked operations: $blocked_operations
- Unique applications: $unique_apps
- Compliance score: $(( 100 - (security_violations * 10) - (blocked_operations * 5) ))%
POLICY STATUS:
- Monitoring enabled: $MONITOR_CLIPBOARD_CHANGES
- Content filtering: $FILTER_SENSITIVE_DATA
- Access control: $RESTRICT_CLIPBOARD_ACCESS
- Audit logging: $AUDIT_CLIPBOARD_ACCESS
RECOMMENDATIONS:
EOF
if [[ $security_violations -gt 5 ]]; then
echo "- Increase security training for users" >> "$report_file"
fi
if [[ $blocked_operations -gt 10 ]]; then
echo "- Review application access policies" >> "$report_file"
fi
echo "- Regular policy review and updates" >> "$report_file"
fi
echo "Compliance report generated: $report_file"
log_action "Compliance report generated: $report_file"
}
# Example usage:
# generate_compliance_report "weekly" "json"
# generate_compliance_report "monthly" "txt"
Important Configuration Notes
macOS Clipboard Security
- Pasteboard types - Support for different data formats
- Application sandboxing - Clipboard access restrictions
- Privacy permissions - User consent requirements
- Secure coding - Protection against injection attacks
Enterprise Integration Points
- MDM integration - Deploy clipboard policies via configuration profiles
- SIEM integration - Send audit logs to security systems
- Identity management - Integrate with corporate directory services
- Compliance frameworks - Support for regulatory requirements
Best Practices for Enterprise
-
Security-First Approach
- Filter sensitive content automatically
- Monitor clipboard operations continuously
- Implement application access controls
- Maintain comprehensive audit trails
-
User Experience Balance
- Provide clear feedback on policy violations
- Allow legitimate business workflows
- Minimize performance impact
- Offer self-service compliance tools
-
Policy Management
- Define clear clipboard usage policies
- Regularly review and update rules
- Train users on security requirements
- Monitor compliance metrics
-
Incident Response
- Detect sensitive data exposure quickly
- Provide automated remediation options
- Generate compliance reports regularly
- Integrate with security incident workflows
Troubleshooting Common Issues
- Permission errors - Check accessibility and automation permissions
- Application blocks - Review application access policies
- Content filtering - Adjust sensitivity detection rules
- Performance impact - Optimize monitoring frequency
- Audit log growth - Implement log rotation and archival
Remember to test clipboard management procedures thoroughly and ensure they align with your organization's security policies and compliance requirements before deploying across your entire MacFleet.