-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDiskEncrypter_Enhanced.sh
More file actions
executable file
·1326 lines (1091 loc) · 54.7 KB
/
DiskEncrypter_Enhanced.sh
File metadata and controls
executable file
·1326 lines (1091 loc) · 54.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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
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
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/bash
# Created by Thijs Xhaflaire, on 01/10/2022
# Modified on 12/07/2023
# Fixed and improved for macOS 15+ compatibility - 12/03/2025
# Enhanced with comprehensive logging and dry-run mode
# v2.2 - 12/04/2025 - Fixed read-only mount re-prompt issue (corrected field name from "Read-Only Volume" to "Volume Read-Only")
# - Added NTFS volume support alongside ExFAT/FAT volumes
# v2.3 - 12/09/2025 - Auto-mount unencrypted disks as read-only before prompting user
# - Updated dialog options: "Keep Read-Only", "Eject", "Encrypt"
# - Improved user workflow with safer default (read-only mount)
## Managed Preferences
settingsPlist="/Library/Managed Preferences/com.custom.diskencrypter.plist"
###########################################
########## COMMAND LINE ARGUMENTS #########
###########################################
show_usage() {
cat << EOF
Usage: $(basename "$0") [OPTIONS]
Monitors and enforces encryption on external drives.
OPTIONS:
-d, --dry-run Enable dry-run mode (no actual disk operations)
-l, --log-level LEVEL Set log level: 0=minimal, 1=normal, 2=verbose, 3=debug
-h, --help Show this help message
EXAMPLES:
$(basename "$0") # Run with defaults
$(basename "$0") --dry-run # Test without making changes
$(basename "$0") -l 2 # Run with verbose logging
$(basename "$0") -d -l 3 # Dry-run with debug logging
NOTES:
- Command-line arguments override plist settings
- Without arguments, defaults from plist are used
- Plist location: $settingsPlist
EOF
exit 0
}
# Parse command-line arguments
DRY_RUN_CLI=""
LOG_LEVEL_CLI=""
while [[ $# -gt 0 ]]; do
case $1 in
-d|--dry-run)
DRY_RUN_CLI="yes"
shift
;;
-l|--log-level)
if [[ -z "$2" ]] || ! [[ "$2" =~ ^[0-3]$ ]]; then
echo "ERROR: --log-level requires a value between 0 and 3" >&2
exit 1
fi
LOG_LEVEL_CLI="$2"
shift 2
;;
-h|--help)
show_usage
;;
*)
echo "ERROR: Unknown option: $1" >&2
echo "Use --help for usage information" >&2
exit 1
;;
esac
done
###########################################
############ DRY RUN SETTING ##############
###########################################
## Priority: 1) Command-line, 2) Plist, 3) Default
if [[ -n "$DRY_RUN_CLI" ]]; then
DRY_RUN="$DRY_RUN_CLI"
else
DRY_RUN_RAW=$( /usr/libexec/PlistBuddy -c "Print :dryRun" "$settingsPlist" 2>/dev/null )
if [[ $? -ne 0 ]] || [[ -z "$DRY_RUN_RAW" ]]; then
DRY_RUN="no"
else
DRY_RUN="$DRY_RUN_RAW"
fi
fi
## Verbose logging level
## 0 = minimal, 1 = normal, 2 = verbose, 3 = debug
## Priority: 1) Command-line, 2) Plist, 3) Default
if [[ -n "$LOG_LEVEL_CLI" ]]; then
LOG_LEVEL="$LOG_LEVEL_CLI"
else
LOG_LEVEL_RAW=$( /usr/libexec/PlistBuddy -c "Print :logLevel" "$settingsPlist" 2>/dev/null )
if [[ $? -ne 0 ]] || [[ -z "$LOG_LEVEL_RAW" ]] || ! [[ "$LOG_LEVEL_RAW" =~ ^[0-3]$ ]]; then
LOG_LEVEL=1
else
LOG_LEVEL="$LOG_LEVEL_RAW"
fi
fi
###########################################
############ LOGGING FUNCTIONS ############
###########################################
# Get current timestamp in ISO 8601 format
get_timestamp() {
date +"%Y-%m-%d %H:%M:%S"
}
log_error() {
echo "[$(get_timestamp)] ERROR: $*" >&2
logger -p user.error "DiskEncrypter [ERROR]: $*"
}
log_warn() {
echo "[$(get_timestamp)] WARNING: $*" >&2
logger -p user.warning "DiskEncrypter [WARN]: $*"
}
log_info() {
if [[ $LOG_LEVEL -ge 1 ]]; then
echo "[$(get_timestamp)] INFO: $*"
logger -p user.info "DiskEncrypter [INFO]: $*"
fi
}
log_verbose() {
if [[ $LOG_LEVEL -ge 2 ]]; then
echo "[$(get_timestamp)] VERBOSE: $*"
logger -p user.notice "DiskEncrypter [VERBOSE]: $*"
fi
}
log_debug() {
if [[ $LOG_LEVEL -ge 3 ]]; then
echo "[$(get_timestamp)] DEBUG: $*"
logger -p user.debug "DiskEncrypter [DEBUG]: $*"
fi
}
log_operation() {
local operation=$1
shift
if [[ "$DRY_RUN" == "yes" ]]; then
echo "[DRY RUN] Would execute: $operation $*"
logger "DiskEncrypter [DRY RUN]: Would execute: $operation $*"
else
log_info "Executing: $operation"
log_debug "Full command: $operation $*"
fi
}
###########################################
############ GLOBAL TRACKING ###############
###########################################
# Array to track all encrypted volumes in this session
declare -a ENCRYPTED_VOLUMES=()
# Function to add encrypted volume to tracking array
track_encrypted_volume() {
local volumeName=$1
local volumeID=$2
local volumeType=$3
ENCRYPTED_VOLUMES+=("$volumeName|$volumeID|$volumeType")
log_debug "Added to tracking: $volumeName ($volumeID) [$volumeType]"
}
# Function to show summary dialog of all encrypted volumes
show_encryption_summary() {
local count=${#ENCRYPTED_VOLUMES[@]}
if [[ $count -eq 0 ]]; then
return
fi
log_info "Showing encryption summary for $count volume(s)"
# Build summary message
local summaryMessage=""
if [[ $count -eq 1 ]]; then
summaryMessage="The following volume was encrypted during this session:\\n\\n"
else
summaryMessage="The following $count volumes were encrypted during this session:\\n\\n"
fi
# Add each encrypted volume to the message
for entry in "${ENCRYPTED_VOLUMES[@]}"; do
IFS='|' read -r volName volID volType <<< "$entry"
summaryMessage+="• \"$volName\" ($volID)\\n Type: $volType\\n\\n"
done
summaryMessage+="All encryption processes are running in the background and will complete shortly."
# Show summary dialog
if [[ "$DRY_RUN" != "yes" ]] && [[ -f "$notificationApp" ]]; then
runDialogAsUser \
--title "Encryption Summary" \
--message "$summaryMessage" \
--icon "$iconPath" \
--button1text "OK" \
--timer 15
else
log_info "ENCRYPTION SUMMARY:"
for entry in "${ENCRYPTED_VOLUMES[@]}"; do
IFS='|' read -r volName volID volType <<< "$entry"
log_info " - \"$volName\" ($volID) [$volType]"
done
fi
}
###########################################
############ SETTINGS FUNCTIONS ###########
###########################################
readSetting() {
local key=$1
local defaultValue=$2
if ! value=$( /usr/libexec/PlistBuddy -c "Print :$key" "$settingsPlist" 2>/dev/null ); then
value="$defaultValue"
fi
echo "$value"
}
readSettingsFile(){
log_debug "Reading settings from $settingsPlist"
## USER NOTIFICATION SETTINGS
notifyUser=$( readSetting notifyUser "yes" )
notifyUserHint=$( readSetting notifyUserHint "yes" )
downloadSwiftDialog=$( readSetting downloadSwiftDialog "yes" )
notificationApp=$( readSetting notificationApp "/usr/local/bin/dialog" )
## swiftDialog Customization
companyName=$( readSetting companyName "Jamf" )
iconPath=$( readSetting iconPath "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/FileVaultIcon.icns" )
batteryIconPath=$( readSetting batteryIconPath "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/AlertStopIcon.icns")
## General text section
title=$( readSetting title "Unencrypted Removable Media Device detected" )
subTitleBattery=$( readSetting subTitleBattery "The Mac is not connected to AC Power and therefore the removable media device can't be encrypted, plug in the AC adapter and try again")
batteryExitMainButton=$( readSetting batteryExitMainButton "Quit" )
subTitlePassword=$( readSetting subTitlePassword "This volume has been mounted as read-only for your protection. To write files, you must encrypt the disk. Securely store the password - if lost, the data will be inaccessible!" )
mainButtonLabelPassword=$( readSetting mainButtonLabelPassword "Encrypt" )
subTitleConversion=$( readSetting subTitleConversion "This volume has been mounted as read-only for your protection. To write files, you must encrypt the disk. This volume will be converted to APFS before encryption. Securely store the password - if lost, the data will be inaccessible!" )
mainButtonLabelConversion=$( readSetting mainButtonLabelConversion "Encrypt" )
subTitleEXFAT=$( readSetting subTitleEXFAT "This volume has been mounted as read-only for your protection. To write files, you must encrypt the disk. WARNING: This volume type requires erasure - ALL EXISTING DATA WILL BE LOST! Securely store the password - if lost, the data will be inaccessible!" )
mainButtonLabelEXFAT=$( readSetting mainButtonLabelEXFAT "Erase and Encrypt" )
exitButtonLabel=$( readSetting exitButtonLabel "Eject" )
## Password text and REGEX requirements
secondTitlePassword=$( readSetting secondTitlePassword "Enter the password you want to use to encrypt the removable media" )
placeholderPassword=$( readSetting placeholderPassword "Enter password here" )
secondaryButtonLabelPassword=$( readSetting secondaryButtonLabelPassword "Keep Read-Only" )
passwordRegex=$( readSetting passwordRegex "^[^\s]{4,}$" )
passwordRegexErrorMessage=$( readSetting passwordRegexErrorMessage "The provided password does not meet the requirements, please use at leasts 4 characters" )
## Hint text and REGEX requirements
subTitleHint=$( readSetting subTitleHint "Optionally you can specify a hint, a password hint is a sort of reminder that helps the user remember their password." )
mainButtonLabelHint=$( readSetting mainButtonLabelHint "Encrypt" )
secondaryButtonLabelHint=$( readSetting secondaryButtonLabelHint "Encrypt w/o hint" )
secondTitleHint=$( readSetting secondTitleHint "Enter the hint you want to set" )
placeholderHint=$( readSetting placeholderHint "Enter hint here" )
hintRegex=$( readSetting hintRegex "^[^\s]{6,}$" )
hintRegexErrorMessage=$( readSetting hintRegexErrorMessage "The provided hint does not meet the requirements, please use a stronger hint that contains 6 characters" )
## Progress bar text
titleProgress=$( readSetting titleProgress "Disk Encryption Progress" )
subTitleProgress=$( readSetting subTitleProgress "Please wait while the external disk is being encrypted." )
mainButtonLabelProgress=$( readSetting mainButtonLabelProgress "Exit" )
log_verbose "Settings loaded: notifyUser=$notifyUser, DRY_RUN=$DRY_RUN, LOG_LEVEL=$LOG_LEVEL"
}
###########################################
############ UTILITY FUNCTIONS ############
###########################################
cleanup() {
log_debug "Cleaning up sensitive data from memory"
unset Password
unset Passphrase
}
trap cleanup EXIT
checkFullDiskAccess() {
log_verbose "Checking for Full Disk Access permission"
if ! diskutil list >/dev/null 2>&1; then
log_error "This script requires Full Disk Access permission"
exit 1
fi
log_verbose "Full Disk Access permission verified"
}
installSwiftDialog() {
if [[ "$downloadSwiftDialog" == "yes" ]] && [[ ! -f "$notificationApp" ]]; then
log_info "swiftDialog not installed, downloading and installing"
expectedDialogTeamID="PWA5E9TQ59"
log_verbose "Fetching latest swiftDialog release URL"
LOCATION=$(/usr/bin/curl -s https://api.github.com/repos/bartreardon/swiftDialog/releases/latest | grep browser_download_url | grep .pkg | grep -v debug | awk '{ print $2 }' | sed 's/,$//' | sed 's/"//g')
if [[ -z "$LOCATION" ]]; then
log_error "Failed to get swiftDialog download URL"
return 1
fi
log_debug "Download URL: $LOCATION"
if [[ "$DRY_RUN" == "yes" ]]; then
log_operation "curl" "-L $LOCATION -o /tmp/swiftDialog.pkg"
log_operation "installer" "-pkg /tmp/swiftDialog.pkg -target /"
return 0
fi
log_verbose "Downloading swiftDialog package"
/usr/bin/curl -L "$LOCATION" -o /tmp/swiftDialog.pkg
if [[ ! -f /tmp/swiftDialog.pkg ]]; then
log_error "Failed to download swiftDialog"
return 1
fi
log_verbose "Verifying package signature"
teamID=$(/usr/sbin/spctl -a -vv -t install "/tmp/swiftDialog.pkg" 2>&1 | awk '/origin=/ {print $NF }' | tr -d '()')
if [[ "$expectedDialogTeamID" = "$teamID" ]] || [[ "$expectedDialogTeamID" = "" ]]; then
log_info "swiftDialog Team ID verification succeeded (TeamID: $teamID)"
/usr/sbin/installer -pkg /tmp/swiftDialog.pkg -target /
else
log_error "swiftDialog Team ID verification failed. Expected: $expectedDialogTeamID, Got: $teamID"
/bin/rm /tmp/swiftDialog.pkg
return 1
fi
log_verbose "Cleaning up swiftDialog.pkg"
/bin/rm /tmp/swiftDialog.pkg
else
log_debug "swiftDialog already installed at $notificationApp"
fi
return 0
}
runDialogAsUser() {
# Run swiftDialog in the logged-in user's GUI session
# This is critical when running as root via LaunchDaemon
if [[ -n "$loggedInUserUID" ]]; then
# Use launchctl asuser to run in user's GUI session
/bin/launchctl asuser "$loggedInUserUID" sudo -u "$loggedInUser" "$notificationApp" "$@"
else
# Fallback to simple sudo -u
/usr/bin/sudo -u "$loggedInUser" "$notificationApp" "$@"
fi
}
checkACPower() {
log_verbose "Checking power source status"
if [[ $(pmset -g ps | head -1) =~ "AC Power" ]]; then
log_info "Device is connected to AC Power, proceeding"
return 0
else
log_warn "Device is connected to battery and not charging, exiting"
if [[ "$notifyUser" == "yes" ]] && [[ -f "$notificationApp" ]]; then
runDialogAsUser --title "$title" --message "$subTitleBattery" --button1text "$batteryExitMainButton" --icon "$batteryIconPath"
fi
return 1
fi
}
###########################################
############ DISK OPERATIONS ##############
###########################################
mountReadOnly() {
local VolumeID=$1
local volumeName=$2
log_info "Auto-mounting volume as read-only: $VolumeID ($volumeName)"
# Unmount first
log_operation "diskutil unmountDisk" "$VolumeID"
if [[ "$DRY_RUN" != "yes" ]]; then
diskutil unmountDisk "$VolumeID" 2>/dev/null
fi
# Mount as read-only
log_operation "diskutil mount readOnly" "$VolumeID"
if [[ "$DRY_RUN" != "yes" ]]; then
if diskutil mount readOnly "$VolumeID"; then
log_info "Successfully mounted $VolumeID ($volumeName) as read-only"
return 0
else
log_error "Failed to mount $VolumeID as read-only"
return 1
fi
fi
return 0
}
processAPFSDisk() {
local DiskID=$1
local VolumeID=$2
local volumeName=$3
log_info "Processing APFS disk: $DiskID (Volume: $VolumeID, Name: '$volumeName')"
# Install swiftDialog first if needed
if ! installSwiftDialog; then
log_error "Failed to install swiftDialog"
exit 1
fi
# Show user dialog FIRST to get their choice
if [[ "$notifyUser" == "yes" ]] && [[ -f "$notificationApp" ]]; then
log_verbose "Displaying options dialog to user for volume: $volumeName ($VolumeID)"
# Construct custom message including volume name
customMessage="Unencrypted volume detected: \"$volumeName\" ($VolumeID)\n\n$subTitlePassword"
if [[ "$DRY_RUN" == "yes" ]]; then
log_operation "swiftDialog" "password prompt"
Password="DRY_RUN_PASSWORD"
dialogExitCode=0
else
dialog=$(runDialogAsUser --title "$title" --message "$customMessage" --button1text "$mainButtonLabelPassword" --button2text "$secondaryButtonLabelPassword" --infobuttontext "$exitButtonLabel" --quitoninfo --icon "$iconPath" --textfield "$secondTitlePassword",prompt="$placeholderPassword",regex="$passwordRegex",regexerror="$passwordRegexErrorMessage",secure=true,required=yes)
dialogExitCode=$?
Password=$(echo "$dialog" | grep "$secondTitlePassword" | awk -F " : " '{print $NF}')
fi
else
log_error "User notification is disabled or swiftDialog is not available"
exit 1
fi
case $dialogExitCode in
0)
log_info "User chose to encrypt disk $DiskID"
# Check AC Power only when user chooses to encrypt
if ! checkACPower; then
exit 1
fi
if [[ -z "$Password" ]] && [[ "$DRY_RUN" != "yes" ]]; then
log_error "Password is empty, cannot proceed"
exit 1
fi
log_verbose "Password received (length: ${#Password} characters)"
if [[ "$notifyUserHint" == "yes" ]] && [[ -f "$notificationApp" ]]; then
log_verbose "Displaying hint prompt to user"
if [[ "$DRY_RUN" == "yes" ]]; then
log_operation "swiftDialog" "hint prompt"
Passphrase="DRY_RUN_HINT"
else
hintDialog=$(runDialogAsUser --title "$title" --message "$subTitleHint" --button1text "$mainButtonLabelHint" --button2text "$secondaryButtonLabelHint" --icon "$iconPath" --textfield "$secondTitleHint",prompt="$placeholderHint",regex="$hintRegex",regexerror="$hintRegexErrorMessage")
Passphrase=$(echo "$hintDialog" | grep "$secondTitleHint" | awk -F " : " '{print $NF}')
fi
if [[ -n "$Passphrase" ]]; then
log_verbose "Hint provided by user"
else
log_verbose "No hint provided by user"
fi
fi
if [[ "$notifyUser" == "yes" ]] && [[ -f "$notificationApp" ]] && [[ -n "$Password" ]]; then
if [[ "$DRY_RUN" != "yes" ]]; then
# Include volume name in progress message
progressMessage="Encrypting volume: \"$volumeName\" ($VolumeID)\n\n$subTitleProgress"
runDialogAsUser --title "$titleProgress" --message "$progressMessage" --icon "$iconPath" --button1text "$mainButtonLabelProgress" --timer 60 --progresstext "Encrypting \"$volumeName\" ($VolumeID)..." &
dialogPID=$!
log_debug "Progress dialog PID: $dialogPID"
fi
log_operation "diskutil unmountDisk" "$VolumeID"
[[ "$DRY_RUN" != "yes" ]] && diskutil unmountDisk "$VolumeID" 2>/dev/null
log_operation "diskutil mount" "$VolumeID"
[[ "$DRY_RUN" != "yes" ]] && diskutil mount "$VolumeID"
log_operation "diskutil apfs encryptVolume" "$VolumeID -user disk"
if [[ "$DRY_RUN" == "yes" ]]; then
log_info "DRY RUN: Encryption would start for $VolumeID"
encryptSuccess=true
else
if diskutil apfs encryptVolume "$VolumeID" -user "disk" -passphrase "$Password"; then
encryptSuccess=true
else
encryptSuccess=false
fi
fi
if [[ "$encryptSuccess" == true ]]; then
log_info "Encryption started successfully for $VolumeID"
if [[ -n "$Passphrase" ]]; then
log_verbose "Setting passphrase hint"
sleep 5
log_operation "diskutil unmountDisk" "$DiskID"
[[ "$DRY_RUN" != "yes" ]] && diskutil unmountDisk "$DiskID" 2>/dev/null
log_operation "diskutil apfs unlockVolume" "$VolumeID"
if [[ "$DRY_RUN" == "yes" ]] || diskutil apfs unlockVolume "$VolumeID" -passphrase "$Password"; then
log_operation "diskutil apfs setPassphraseHint" "$VolumeID"
if [[ "$DRY_RUN" != "yes" ]]; then
diskutil apfs setPassphraseHint "$VolumeID" -user "disk" -hint "$Passphrase"
fi
log_info "Passphrase hint set successfully"
else
log_warn "Failed to unlock volume for hint setting"
fi
fi
# Show success dialog instead of just killing progress dialog
if [[ "$DRY_RUN" != "yes" ]]; then
kill $dialogPID 2>/dev/null
runDialogAsUser \
--title "Encryption Complete" \
--message "Volume \"$volumeName\" ($VolumeID) has been successfully encrypted.\n\nThe encryption process is running in the background and will complete shortly." \
--icon "$iconPath" \
--button1text "OK" \
--timer 10
fi
# Track this encrypted volume for summary
track_encrypted_volume "$volumeName" "$VolumeID" "APFS"
log_info "APFS disk encryption workflow completed successfully"
return 0
else
log_error "Encryption failed for $VolumeID"
if [[ "$DRY_RUN" != "yes" ]]; then
kill $dialogPID 2>/dev/null
runDialogAsUser \
--title "Encryption Failed" \
--message "Failed to encrypt volume \"$volumeName\" ($VolumeID).\n\nPlease check the system logs for details." \
--icon "$iconPath" \
--button1text "OK"
fi
return 1
fi
fi
;;
2)
log_info "$loggedInUser decided to keep $DiskID mounted as read-only"
# Volume is already mounted read-only from discovery phase
return 2
;;
3)
log_info "$loggedInUser decided to eject $DiskID"
log_operation "diskutil unmountDisk" "$DiskID"
[[ "$DRY_RUN" != "yes" ]] && diskutil unmountDisk "$DiskID" 2>/dev/null
return 3
;;
esac
}
processHFSDisk() {
local DiskID=$1
local VolumeID=$2
local volumeName=$3
log_info "Processing HFS disk: $DiskID (Volume: $VolumeID, Name: '$volumeName')"
log_warn "HFS volume requires conversion to APFS before encryption"
# Install swiftDialog first if needed
if ! installSwiftDialog; then
log_error "Failed to install swiftDialog"
exit 1
fi
# Show user dialog FIRST to get their choice
if [[ "$notifyUser" == "yes" ]] && [[ -f "$notificationApp" ]]; then
log_verbose "Displaying conversion options to user for volume: $volumeName ($VolumeID)"
# Construct custom message including volume name
customMessage="Unencrypted HFS+ volume detected: \"$volumeName\" ($VolumeID)\n\n$subTitleConversion"
if [[ "$DRY_RUN" == "yes" ]]; then
log_operation "swiftDialog" "conversion prompt"
Password="DRY_RUN_PASSWORD"
dialogExitCode=0
else
dialog=$(runDialogAsUser --title "$title" --message "$customMessage" --button1text "$mainButtonLabelConversion" --button2text "$secondaryButtonLabelPassword" --infobuttontext "$exitButtonLabel" --quitoninfo --icon "$iconPath" --textfield "$secondTitlePassword",prompt="$placeholderPassword",regex="$passwordRegex",regexerror="$passwordRegexErrorMessage",secure=true,required=yes)
dialogExitCode=$?
Password=$(echo "$dialog" | grep "$secondTitlePassword" | awk -F " : " '{print $NF}')
fi
else
log_error "User notification is disabled or swiftDialog is not available"
exit 1
fi
case $dialogExitCode in
0)
log_info "User chose to convert and encrypt disk $DiskID"
# Check AC Power only when user chooses to encrypt
if ! checkACPower; then
exit 1
fi
if [[ -z "$Password" ]] && [[ "$DRY_RUN" != "yes" ]]; then
log_error "Password is empty, cannot proceed"
exit 1
fi
if [[ "$notifyUserHint" == "yes" ]] && [[ -f "$notificationApp" ]]; then
if [[ "$DRY_RUN" == "yes" ]]; then
Passphrase="DRY_RUN_HINT"
else
hintDialog=$(runDialogAsUser --title "$title" --message "$subTitleHint" --button1text "$mainButtonLabelHint" --button2text "$secondaryButtonLabelHint" --icon "$iconPath" --textfield "$secondTitleHint",prompt="$placeholderHint",regex="$hintRegex",regexerror="$hintRegexErrorMessage")
Passphrase=$(echo "$hintDialog" | grep "$secondTitleHint" | awk -F " : " '{print $NF}')
fi
fi
if [[ "$notifyUser" == "yes" ]] && [[ -f "$notificationApp" ]] && [[ -n "$Password" ]]; then
if [[ "$DRY_RUN" != "yes" ]]; then
# Include volume name in progress message
progressMessage="Converting and encrypting volume: \"$volumeName\" ($VolumeID)\n\n$subTitleProgress"
runDialogAsUser --title "$titleProgress" --message "$progressMessage" --icon "$iconPath" --button1text "$mainButtonLabelProgress" --timer 60 --progresstext "Converting and encrypting \"$volumeName\" ($VolumeID)..." &
dialogPID=$!
fi
log_operation "diskutil unmountDisk" "$VolumeID"
[[ "$DRY_RUN" != "yes" ]] && diskutil unmountDisk "$VolumeID" 2>/dev/null
log_operation "diskutil mount" "$VolumeID"
[[ "$DRY_RUN" != "yes" ]] && diskutil mount "$VolumeID"
log_operation "diskutil apfs convert" "$VolumeID"
if [[ "$DRY_RUN" == "yes" ]]; then
log_info "DRY RUN: Conversion to APFS would proceed"
convertSuccess=true
NewDiskID="disk99"
NewVolumeID="disk99s1"
else
if diskutil apfs convert "$VolumeID"; then
convertSuccess=true
log_info "Conversion to APFS successful"
sleep 2
NewDiskID=$(diskutil list "$DiskID" | grep -o 'Container disk[0-9]*' | awk '{print $2}')
NewVolumeID="${NewDiskID}s1"
log_info "New APFS container: $NewDiskID, Volume: $NewVolumeID"
else
convertSuccess=false
fi
fi
if [[ "$convertSuccess" == true ]]; then
log_operation "diskutil apfs encryptVolume" "$NewVolumeID -user disk"
if [[ "$DRY_RUN" == "yes" ]] || diskutil apfs encryptVolume "$NewVolumeID" -user "disk" -passphrase "$Password"; then
log_info "Encryption started successfully for $NewVolumeID"
if [[ -n "$Passphrase" ]]; then
sleep 5
log_operation "diskutil unmountDisk" "$NewDiskID"
[[ "$DRY_RUN" != "yes" ]] && diskutil unmountDisk "$NewDiskID" 2>/dev/null
if [[ "$DRY_RUN" == "yes" ]] || diskutil apfs unlockVolume "$NewVolumeID" -passphrase "$Password"; then
log_operation "diskutil apfs setPassphraseHint" "$NewVolumeID"
[[ "$DRY_RUN" != "yes" ]] && diskutil apfs setPassphraseHint "$NewVolumeID" -user "disk" -hint "$Passphrase"
log_info "Passphrase hint set successfully"
fi
fi
# Show success dialog instead of just killing progress dialog
if [[ "$DRY_RUN" != "yes" ]]; then
kill $dialogPID 2>/dev/null
runDialogAsUser \
--title "Encryption Complete" \
--message "Volume \"$volumeName\" ($NewVolumeID) has been successfully converted to APFS and encrypted.\n\nThe encryption process is running in the background and will complete shortly." \
--icon "$iconPath" \
--button1text "OK" \
--timer 10
fi
# Track this encrypted volume for summary
track_encrypted_volume "$volumeName" "$NewVolumeID" "HFS+ (Converted)"
log_info "HFS conversion and encryption workflow completed successfully"
return 0
else
log_error "Encryption failed for $NewVolumeID"
if [[ "$DRY_RUN" != "yes" ]]; then
kill $dialogPID 2>/dev/null
runDialogAsUser \
--title "Encryption Failed" \
--message "Failed to encrypt volume \"$volumeName\" ($NewVolumeID).\n\nPlease check the system logs for details." \
--icon "$iconPath" \
--button1text "OK"
fi
return 1
fi
else
log_error "APFS conversion failed"
if [[ "$DRY_RUN" != "yes" ]]; then
kill $dialogPID 2>/dev/null
runDialogAsUser \
--title "Conversion Failed" \
--message "Failed to convert volume \"$volumeName\" ($VolumeID) to APFS.\n\nPlease check the system logs for details." \
--icon "$iconPath" \
--button1text "OK"
fi
return 1
fi
fi
;;
2)
log_info "$loggedInUser decided to keep $DiskID mounted as read-only"
# Volume is already mounted read-only from discovery phase
return 2
;;
3)
log_info "$loggedInUser decided to eject $DiskID"
log_operation "diskutil unmountDisk" "$DiskID"
[[ "$DRY_RUN" != "yes" ]] && diskutil unmountDisk "$DiskID" 2>/dev/null
return 3
;;
esac
}
processExFATDisk() {
local DiskID=$1
local VolumeID=$2
local volumeName=$3
log_info "Processing ExFAT/FAT disk: $DiskID (Volume: $VolumeID, Name: '$volumeName')"
log_warn "ExFAT/FAT volume requires erasure - ALL DATA WILL BE LOST"
# Install swiftDialog first if needed
if ! installSwiftDialog; then
log_error "Failed to install swiftDialog"
exit 1
fi
# Show user dialog FIRST to get their choice
if [[ "$notifyUser" == "yes" ]] && [[ -f "$notificationApp" ]]; then
log_verbose "Displaying erase warning to user for volume: $volumeName ($VolumeID)"
# Construct custom message including volume name
customMessage="Unencrypted ExFAT/FAT volume detected: \"$volumeName\" ($VolumeID)\n\n$subTitleEXFAT"
if [[ "$DRY_RUN" == "yes" ]]; then
log_operation "swiftDialog" "erase prompt"
Password="DRY_RUN_PASSWORD"
dialogExitCode=0
else
dialog=$(runDialogAsUser --title "$title" --message "$customMessage" --button1text "$mainButtonLabelEXFAT" --button2text "$secondaryButtonLabelPassword" --infobuttontext "$exitButtonLabel" --quitoninfo --icon "$iconPath" --textfield "$secondTitlePassword",prompt="$placeholderPassword",regex="$passwordRegex",regexerror="$passwordRegexErrorMessage",secure=true,required=yes)
dialogExitCode=$?
Password=$(echo "$dialog" | grep "$secondTitlePassword" | awk -F " : " '{print $NF}')
fi
else
log_error "User notification is disabled or swiftDialog is not available"
exit 1
fi
case $dialogExitCode in
0)
log_info "User chose to erase and encrypt disk $DiskID"
log_warn "DESTRUCTIVE OPERATION: Erasing all data on $DiskID ($volumeName)"
# Check AC Power only when user chooses to encrypt
if ! checkACPower; then
exit 1
fi
if [[ -z "$Password" ]] && [[ "$DRY_RUN" != "yes" ]]; then
log_error "Password is empty, cannot proceed"
exit 1
fi
if [[ "$notifyUserHint" == "yes" ]] && [[ -f "$notificationApp" ]]; then
if [[ "$DRY_RUN" == "yes" ]]; then
Passphrase="DRY_RUN_HINT"
else
hintDialog=$(runDialogAsUser --title "$title" --message "$subTitleHint" --button1text "$mainButtonLabelHint" --button2text "$secondaryButtonLabelHint" --icon "$iconPath" --textfield "$secondTitleHint",prompt="$placeholderHint",regex="$hintRegex",regexerror="$hintRegexErrorMessage")
Passphrase=$(echo "$hintDialog" | grep "$secondTitleHint" | awk -F " : " '{print $NF}')
fi
fi
if [[ "$notifyUser" == "yes" ]] && [[ -f "$notificationApp" ]] && [[ -n "$Password" ]]; then
if [[ "$DRY_RUN" != "yes" ]]; then
# Include volume name in progress message
progressMessage="Erasing and encrypting volume: \"$volumeName\" ($VolumeID)\n\n$subTitleProgress"
runDialogAsUser --title "$titleProgress" --message "$progressMessage" --icon "$iconPath" --button1text "$mainButtonLabelProgress" --timer 60 --progresstext "Erasing and encrypting \"$volumeName\"..." &
dialogPID=$!
fi
safeVolumeName="${volumeName// /_}"
if [[ -z "$safeVolumeName" ]]; then
safeVolumeName="EncryptedDisk"
fi
log_debug "Safe volume name: $safeVolumeName"
log_operation "diskutil eraseDisk APFS" "$safeVolumeName $DiskID"
if [[ "$DRY_RUN" == "yes" ]]; then
log_warn "DRY RUN: Disk would be erased here - ALL DATA WOULD BE LOST"
eraseSuccess=true
NewDiskID="disk99"
NewVolumeID="disk99s1"
else
if diskutil eraseDisk APFS "$safeVolumeName" "$DiskID"; then
eraseSuccess=true
log_info "Disk erased and formatted successfully"
sleep 2
NewDiskID=$(diskutil list "$DiskID" | grep -o 'Container disk[0-9]*' | awk '{print $2}')
NewVolumeID=$(diskutil list "$NewDiskID" | grep "APFS Volume" | head -1 | awk '{print $NF}' | sed 's/^//')
if [[ -z "$NewVolumeID" ]]; then
NewVolumeID="${NewDiskID}s1"
fi
log_info "New APFS container: $NewDiskID, Volume: $NewVolumeID"
else
eraseSuccess=false
fi
fi
if [[ "$eraseSuccess" == true ]]; then
log_operation "diskutil apfs encryptVolume" "$NewVolumeID -user disk"
if [[ "$DRY_RUN" == "yes" ]] || diskutil apfs encryptVolume "$NewVolumeID" -user "disk" -passphrase "$Password"; then
log_info "Encryption started successfully for $NewVolumeID"
if [[ -n "$Passphrase" ]]; then
sleep 5
log_operation "diskutil unmountDisk" "$NewDiskID"
[[ "$DRY_RUN" != "yes" ]] && diskutil unmountDisk "$NewDiskID" 2>/dev/null
if [[ "$DRY_RUN" == "yes" ]] || diskutil apfs unlockVolume "$NewVolumeID" -passphrase "$Password"; then
log_operation "diskutil apfs setPassphraseHint" "$NewVolumeID"
[[ "$DRY_RUN" != "yes" ]] && diskutil apfs setPassphraseHint "$NewVolumeID" -user "disk" -hint "$Passphrase"
log_info "Passphrase hint set successfully"
fi
fi
# Show success dialog instead of just killing progress dialog
if [[ "$DRY_RUN" != "yes" ]]; then
kill $dialogPID 2>/dev/null
runDialogAsUser \
--title "Encryption Complete" \
--message "Volume \"$volumeName\" has been successfully erased, formatted as APFS, and encrypted.\n\nThe encryption process is running in the background and will complete shortly." \
--icon "$iconPath" \
--button1text "OK" \
--timer 10
fi
# Track this encrypted volume for summary
track_encrypted_volume "$volumeName" "$NewVolumeID" "ExFAT (Erased)"
log_info "ExFAT erase and encryption workflow completed successfully"
return 0
else
log_error "Encryption failed for $NewVolumeID"
if [[ "$DRY_RUN" != "yes" ]]; then
kill $dialogPID 2>/dev/null
runDialogAsUser \
--title "Encryption Failed" \
--message "Failed to encrypt volume \"$volumeName\".\n\nPlease check the system logs for details." \
--icon "$iconPath" \
--button1text "OK"
fi
return 1
fi
else
log_error "Disk erase failed"
if [[ "$DRY_RUN" != "yes" ]]; then
kill $dialogPID 2>/dev/null
runDialogAsUser \
--title "Erase Failed" \
--message "Failed to erase and format volume \"$volumeName\" ($VolumeID).\n\nPlease check the system logs for details." \
--icon "$iconPath" \
--button1text "OK"
fi
return 1
fi
fi
;;
2)
log_info "$loggedInUser decided to keep $DiskID mounted as read-only"
# Volume is already mounted read-only from discovery phase
return 2
;;
3)
log_info "$loggedInUser decided to eject $DiskID"
log_operation "diskutil unmountDisk" "$DiskID"
[[ "$DRY_RUN" != "yes" ]] && diskutil unmountDisk "$DiskID" 2>/dev/null
return 3
;;
esac
}
###########################################
########## LOG ROTATION FUNCTION ###########
###########################################
rotate_logs() {
local log_file="/var/log/diskencrypter.log"
local error_log_file="/var/log/diskencrypter_error.log"
local archive_dir="/var/log/diskencrypter_archives"
local today=$(date +"%Y-%m-%d")
# Create archive directory if it doesn't exist
if [[ ! -d "$archive_dir" ]]; then
mkdir -p "$archive_dir" 2>/dev/null
chmod 755 "$archive_dir" 2>/dev/null
fi
# Check if logs need rotation (if they have entries from previous days)
if [[ -f "$log_file" ]]; then
# Get the date of the first log entry (if it exists)
local first_log_date=$(head -1 "$log_file" 2>/dev/null | grep -oE '[0-9]{4}-[0-9]{2}-[0-9]{2}' | head -1)
# If log exists and has a date, and it's not today, rotate it
if [[ -n "$first_log_date" ]] && [[ "$first_log_date" != "$today" ]]; then
local archive_name="diskencrypter_${first_log_date}.log"
# Archive the old log with compression
if [[ -s "$log_file" ]]; then
gzip -c "$log_file" > "$archive_dir/$archive_name.gz" 2>/dev/null
: > "$log_file" # Truncate the log file
echo "[$(date +"%Y-%m-%d %H:%M:%S")] INFO: Log rotated, archived to $archive_dir/$archive_name.gz" >> "$log_file"
fi
fi
fi
# Rotate error log
if [[ -f "$error_log_file" ]]; then
local first_error_date=$(head -1 "$error_log_file" 2>/dev/null | grep -oE '[0-9]{4}-[0-9]{2}-[0-9]{2}' | head -1)
if [[ -n "$first_error_date" ]] && [[ "$first_error_date" != "$today" ]]; then
local error_archive_name="diskencrypter_error_${first_error_date}.log"
if [[ -s "$error_log_file" ]]; then
gzip -c "$error_log_file" > "$archive_dir/$error_archive_name.gz" 2>/dev/null
: > "$error_log_file"
echo "[$(date +"%Y-%m-%d %H:%M:%S")] INFO: Error log rotated, archived to $archive_dir/$error_archive_name.gz" >> "$error_log_file"
fi
fi
fi
# Clean up archives older than 30 days
if [[ -d "$archive_dir" ]]; then
find "$archive_dir" -name "*.log.gz" -type f -mtime +30 -delete 2>/dev/null
fi
}
###########################################
############ MAIN EXECUTION ###############
###########################################
main() {
# Rotate logs at the start of each run
rotate_logs
# Determine configuration source
local dryRunSource="default"
local logLevelSource="default"
[[ -n "$DRY_RUN_CLI" ]] && dryRunSource="command-line"
[[ -z "$DRY_RUN_CLI" ]] && [[ -n "$DRY_RUN_RAW" ]] && dryRunSource="plist"
[[ -n "$LOG_LEVEL_CLI" ]] && logLevelSource="command-line"
[[ -z "$LOG_LEVEL_CLI" ]] && [[ -n "$LOG_LEVEL_RAW" ]] && logLevelSource="plist"
log_info "========================================="
log_info "DiskEncrypter Script Starting"
log_info "Version: 2.3 (Auto Read-Only Mount)"
log_info "========================================="
log_info "DRY RUN MODE: $DRY_RUN (source: $dryRunSource)"
log_info "LOG LEVEL: $LOG_LEVEL (source: $logLevelSource)"
log_info " 0=minimal, 1=normal, 2=verbose, 3=debug"
log_info "========================================="
if [[ "$DRY_RUN" == "yes" ]]; then
log_warn "*** DRY RUN MODE ENABLED - NO ACTUAL OPERATIONS WILL BE PERFORMED ***"