-
Notifications
You must be signed in to change notification settings - Fork 0
/
fast_luks_data
executable file
·537 lines (440 loc) · 17.1 KB
/
fast_luks_data
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
#!/bin/bash
# Bash script for managing LUKS volumes in Linux:
# You can create a virtual encrypted Linux FS volume from a file block.
# Helps you mount and unmount LUKS partitions.
#
# Author: Marco Tangaro
# Mail: [email protected]
# Home institution: IBIOM-CNR, ELIXIR-ITALY
#
# Please find the original script here:
# https://github.com/JohnTroony/LUKS-OPs/blob/master/luks-ops.sh
# All credits to John Troon.
#
# The script is able to detect the $device only if it is mounted.
# Otherwise it will use default $device and $mountpoint.
STAT="fast-luks"
LOGFILE="/tmp/luks$now.log"
SUCCESS_FILE="/tmp/fast-luks.success"
# Defaults
cipher_algorithm='aes-xts-plain64'
keysize='256'
hash_algorithm='sha256'
device='/dev/vdc'
cryptdev='datacrypt'
mountpoint='/opt/nextcloud/data'
filesystem='ext4'
paranoic=false
non_interactive=false
foreground=false
# luks ini file
luks_cryptdev_file='/etc/luks/luks-cryptdev_data.ini'
# lockfile configuration
LOCKDIR=/var/run/fast_luks
PIDFILE=${LOCKDIR}/fast-luks.pid
################################################################################
# VARIABLES
constant="luks_"
cryptdev=$(cat < /dev/urandom | tr -dc "[:lower:]" | head -c 8)
logs=$(cat < /dev/urandom | tr -dc "[:lower:]" | head -c 4)
temp_name="$constant$logs"
now=$(date +"-%b-%d-%y-%H%M%S")
################################################################################
# FUNCTIONS
#____________________________________
# Intro banner
# bash generate random 32 character alphanumeric string (upper and lowercase)
function intro(){
NEW_PWD=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 8 | head -n 1)
until [[ $NEW_PWD =~ ^([a-zA-Z+]+[0-9+]+)$ ]]; do
NEW_PWD=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 8 | head -n 1)
done
echo "========================================================="
echo " ELIXIR-Italy"
echo " Filesystem encryption script"
echo ""
echo "A password with at least 8 alphanumeric string is needed"
echo "There's no way to recover your password."
echo "Example (automatic random generated passphrase):"
echo " ${NEW_PWD}"
echo ""
echo "You will be required to insert your password 3 times:"
echo " 1. Enter passphrase"
echo " 2. Verify passphrase"
echo " 3. Unlock your volume"
echo ""
echo "========================================================="
}
#____________________________________
# Log levels:
# DEBUG
# INFO
# WARNING
# ERROR
# usege: logs(loglevel, statement, logfile)
# log levels
time=$(date +"%Y-%m-%d %H:%M:%S")
info="INFO "$time
debug="DEBUG "$time
warn="WARNING "$time
error="ERROR "$time
# echo functions
function echo_debug(){ echo -e "$debug [$STAT] $1"; }
function echo_info(){ echo -e "$info [$STAT] $1"; }
function echo_warn(){ echo -e "$warn [$STAT] $1"; }
function echo_error(){ echo -e "$error [$STAT] $1"; }
# Logs functions
function logs_debug(){ echo_debug "$1" >> $LOGFILE 2>&1; }
function logs_info(){ echo_info "$1" >> $LOGFILE 2>&1; }
function logs_warn(){ echo_warn "$1" >> $LOGFILE 2>&1; }
function logs_error(){ echo_error "$1" >> $LOGFILE 2>&1; }
#____________________________________
# Lock/UnLock Section
# http://wiki.bash-hackers.org/howto/mutex
# "trap -l" for signal summary
# exit codes and text for them - additional features nobody needs :-)
ENO_SUCCESS=0; ETXT[0]="ENO_SUCCESS"
ENO_GENERAL=1; ETXT[1]="ENO_GENERAL"
ENO_LOCKFAIL=2; ETXT[2]="ENO_LOCKFAIL"
ENO_RECVSIG=3; ETXT[3]="ENO_RECVSIG"
function lock(){
# start un/locking attempt
trap 'ECODE=$?; echo "[$STAT] Exit: ${ETXT[ECODE]}($ECODE)" >&2' 0
echo -n "[$STAT]: " >&2
if mkdir "${LOCKDIR}" &>/dev/null; then
# lock succeeded, I'm storing the PID
echo "$$" >"${PIDFILE}"
echo -e "\n$info [$STAT] Starting log file."
else
# lock failed, check if the other PID is alive
OTHERPID="$(cat "${PIDFILE}")"
# if cat isn't able to read the file, another instance is probably
# about to remove the lock -- exit, we're *still* locked
# Thanks to Grzegorz Wierzowiecki for pointing out this race condition on
# http://wiki.grzegorz.wierzowiecki.pl/code:mutex-in-bash
if [ $? != 0 ]; then
echo "$error [$STAT] Another script instance is active: PID ${OTHERPID} " >&2
exit ${ENO_LOCKFAIL}
fi
if ! kill -0 $OTHERPID &>/dev/null; then
# lock is stale, remove it and restart
echo "$debug [$STAT] Removing fake lock file of nonexistant PID ${OTHERPID}" >&2
rm -rf "${LOCKDIR}"
echo "$debug [$STAT] Restarting LUKS script" >&2
exec "$0" "$@"
else
# lock is valid and OTHERPID is active - exit, we're locked!
echo "$error [$STAT] Lock failed, PID ${OTHERPID} is active" >&2
echo "$error [$STAT] Another $STAT process is active" >&2
echo "$error [$STAT] If you're sure $STAT is not already running," >&2
echo "$error [$STAT] You can remove $LOCKDIR and restart $STAT" >&2
exit ${ENO_LOCKFAIL}
fi
fi
}
#____________________________________
function unlock(){
# lock succeeded, install signal handlers before storing the PID just in case
# storing the PID fails
trap 'ECODE=$?;
echo "$debug [$STAT] Removing lock. Exit: ${ETXT[ECODE]}($ECODE)" >> "$LOGFILE" 2>&1
rm -rf "${LOCKDIR}"' 0
# the following handler will exit the script upon receiving these signals
# the trap on "0" (EXIT) from above will be triggered by this trap's "exit" command!
trap 'echo "$debug [$STAT] Killed by signal." >> "$LOGFILE" 2>&1
exit ${ENO_RECVSIG}' 1 2 3 15
}
#___________________________________
function info(){
echo_debug "LUKS header information for $device"
echo_debug "Cipher algorithm: ${cipher_algorithm}"
echo_debug "Hash algorithm ${hash_algorithm}"
echo_debug "Keysize: ${keysize}"
echo_debug "Device: ${device}"
echo_debug "Crypt device: ${cryptdev}"
echo_debug "Mapper: /dev/mapper/${cryptdev}"
echo_debug "Mountpoint: ${mountpoint}"
echo_debug "File system: ${filesystem}"
}
#____________________________________
# Install cryptsetup
function install_cryptsetup(){
if [[ -r /etc/os-release ]]; then
. /etc/os-release
echo_info "$ID"
if [ "$ID" = "ubuntu" ]; then
echo_info "Distribution: Ubuntu. Using apt."
apt-get install -y cryptsetup pv
else
echo_info "Distribution: CentOS. Using yum."
yum install -y cryptsetup-luks pv
fi
else
echo_info "Not running a distribution with /etc/os-release available."
fi
}
#____________________________________
# Check cryptsetup installation
function check_cryptsetup(){
echo ""
echo_info "Check if the required applications are installed..."
type -P dmsetup &>/dev/null || echo_info "dmestup is not installed. Installing..." #TODO add install device_mapper
type -P cryptsetup &>/dev/null || { echo_info "cryptsetup is not installed. Installing.."; install_cryptsetup >> "$LOGFILE" 2>&1; echo_info "cryptsetup installed."; }
}
#____________________________________
# Check volume
function check_vol(){
logs_debug "Checking storage volume."
if [ $(mount | grep -c $mountpoint) == 1 ]; then
device=$(df -P $mountpoint | tail -1 | cut -d' ' -f 1)
logs_debug "Device name: $device"
elif [ $(mount | grep -c $mountpoint) == 0 ]; then
if [[ -b $device ]]; then
logs_debug "External volume on $device. Using it for encryption."
if [[ ! -d $mountpoint ]]; then
logs_debug "Creating $mountpoint"
mkdir -p $mountpoint
logs_debug "Device name: $device"
logs_debug "Mountpoint: $mountpoint"
fi
else
logs_error "Device not mounted, exiting!"
logs_error "Please check logfile: "
logs_error "No device mounted to $mountpoint: "
df -h >> "$LOGFILE" 2>&1
unlock # unlocking script instance
exit 1
fi
fi
}
#____________________________________
# Umount volume
function umount_vol(){
logs_info "Umounting device."
umount $mountpoint
logs_info "$device umounted, ready for encryption!"
}
#____________________________________
function setup_device(){
logs_info "Using $cipher_algorithm algorithm to luksformat the volume."
logs_debug "Start cryptsetup"
info >> "$LOGFILE" 2>&1
logs_debug "Cryptsetup full command:"
logs_debug "cryptsetup -v --cipher $cipher_algorithm --key-size $keysize --hash $hash_algorithm --iter-time 2000 --use-urandom --verify-passphrase luksFormat $device --batch-mode"
cryptsetup -v --cipher $cipher_algorithm --key-size $keysize --hash $hash_algorithm --iter-time 2000 --use-urandom --verify-passphrase luksFormat $device --batch-mode
ecode=$?
if [ $ecode != 0 ]; then
logs_error "Command cryptsetup failed! Mounting $device to $mountpoint and exiting.." #TODO redirect exit code
mount $device $mountpoint
unlock
exit 1
fi
}
#____________________________________
function open_device(){
echo ""
echo_info "Open LUKS volume."
if [ ! -b /dev/mapper/${cryptdev} ]; then
cryptsetup luksOpen $device $cryptdev
else
echo_error "Crypt device already exists! Please check logs: $LOGFILE"
logs_error "Unable to luksOpen device. "
logs_error "/dev/mapper/${cryptdev} already exists."
logs_error "Mounting $device to $mountpoint again."
mount $device $mountpoint >> "$LOGFILE" 2>&1
unlock # unlocking script instance
exit 1
fi
}
#____________________________________
function encryption_status(){
echo ""
echo_info "Check $cryptdev status with cryptsetup status"
cryptsetup -v status $cryptdev
}
#____________________________________
# Create block file
# https://wiki.archlinux.org/index.php/Dm-crypt/Device_encryption
# https://wiki.archlinux.org/index.php/Dm-crypt/Drive_preparation
# https://wiki.archlinux.org/index.php/Disk_encryption#Preparing_the_disk
#
# Before encrypting a drive, it is recommended to perform a secure erase of the disk by overwriting the entire drive with random data.
# To prevent cryptographic attacks or unwanted file recovery, this data is ideally indistinguishable from data later written by dm-crypt.
function wipe_data(){
echo ""
echo_info "Wiping disk data by overwriting the entire drive with random data"
echo_info "This might take time depending on the size & your machine!"
#dd if=/dev/zero of=/dev/mapper/${cryptdev} bs=1M status=progress
pv -tpreb /dev/zero | dd of=/dev/mapper/${cryptdev} bs=1M status=progress;
echo_info "Block file /dev/mapper/${cryptdev} created."
echo_info "Wiping done."
}
#____________________________________
function create_fs(){
echo ""
echo_info "Creating filesystem..."
mkfs.${filesystem} /dev/mapper/${cryptdev} #Do not redirect mkfs, otherwise no interactive mode!
if [ $? != 0 ]; then
echo_error "While creating ${filesystem} filesystem. Please check logs: $LOGFILE"
echo_error "Command mkfs failed!"
unlock
exit 1
fi
}
#____________________________________
function mount_vol(){
echo ""
echo_info "Mounting encrypted device..."
mount /dev/mapper/${cryptdev} $mountpoint
df -Hv >> "$LOGFILE" 2>&1
}
#____________________________________
function create_cryptdev_ini_file(){
echo "# This file has been generated using fast_luks.sh script" > ${luks_cryptdev_file}
echo "# https://github.com/mtangaro/galaxycloud-testing/blob/master/fast_luks.sh" >> ${luks_cryptdev_file}
echo "# The device name could change after reboot, please use UUID instead." >> ${luks_cryptdev_file}
echo "# LUKS provides a UUID \(Universally Unique Identifier\) \for each device." >> ${luks_cryptdev_file}
echo "# This, unlike the device name \(eg: /dev/vdb\), is guaranteed to remain constant" >> ${luks_cryptdev_file}
echo "# as long as the LUKS header remains intact." >> ${luks_cryptdev_file}
echo "#" >> ${luks_cryptdev_file}
echo "# LUKS header information for $device" >> ${luks_cryptdev_file}
echo -e "# luks-${now}\n" >> ${luks_cryptdev_file}
echo "[luks]" >> ${luks_cryptdev_file}
echo "cipher_algorithm = ${cipher_algorithm}" >> ${luks_cryptdev_file}
echo "hash_algorithm = ${hash_algorithm}" >> ${luks_cryptdev_file}
echo "keysize = ${keysize}" >> ${luks_cryptdev_file}
echo "device = ${device}" >> ${luks_cryptdev_file}
echo "uuid = $(cryptsetup luksUUID ${device})" >> ${luks_cryptdev_file}
echo "cryptdev = ${cryptdev}" >> ${luks_cryptdev_file}
echo "mapper = /dev/mapper/${cryptdev}" >> ${luks_cryptdev_file}
echo "mountpoint = ${mountpoint}" >> ${luks_cryptdev_file}
echo "filesystem = ${filesystem}" >> ${luks_cryptdev_file}
# Update Log file
dmsetup info /dev/mapper/${cryptdev}
cryptsetup luksDump $device
}
#____________________________________
function end_encrypt_procedure(){
echo ""
# send signal to unclok waiting condition for automation software (e.g Ansible)
echo "LUKS encryption completed." > $SUCCESS_FILE # WARNING DO NOT MODFIFY THIS LINE, THIS IS A CONTROL STRING FOR ANSIBLE
echo_info "SUCCESSFUL."
}
#____________________________________
#FIXME cryptsetup (temporary version)
function encrypt(){
# Check which virtual volume is mounted to /export
check_vol
# Umount volume.
umount_vol >> "$LOGFILE" 2>&1
# Setup a new dm-crypt device
setup_device
# Create mapping
open_device
# Check status
encryption_status >> "$LOGFILE" 2>&1
if [[ $foreground == false ]]; then
# Run this in background.
echo_info "Run script in backgroud."
(
# Wipe data for security
# WARNING This is going take time, depending on VM storage. Currently commented out
if [[ $paranoic == true ]]; then wipe_data >> "$LOGFILE" 2>&1; fi
# Create filesystem
create_fs >> "$LOGFILE" 2>&1
# Mount volume
mount_vol >> "$LOGFILE" 2>&1
# Create ini file
create_cryptdev_ini_file >> "$LOGFILE" 2>&1
# LUKS encryption finished. Print end dialogue.
end_encrypt_procedure >> "$LOGFILE" 2>&1
) &
elif [[ $foreground == true ]]; then
echo_info "Run script in foreground."
if [[ $paranoic == true ]]; then wipe_data; fi
create_fs
mount_vol
create_cyptdev_ini_file
end_encrypt_procedure
fi # end foregroud if
# Unlock once done.
unlock >> "$LOGFILE" 2>&1
}
################################################################################
# Main script
# Check if script is run as root
if [[ $(/usr/bin/id -u) -ne 0 ]]; then
logs_error "Not running as root."
exit 1
fi
# Create lock file. Ensure only single instance running.
lock "$@"
# If running script with no arguments then loads defaults values.
if [ $# -lt 1 ]; then
logs_warn "No inputs. Using defaults values."
info >> "$LOGFILE" 2>&1
fi
# Parse CLI options
while [ $# -gt 0 ]
do
case $1 in
-c|--cipher) cipher_algorithm="$2"; shift;;
-k|--keysize) keysize="$2"; shift;;
-a|--hash_algorithm) hash_algorithm="$2"; shift;;
-d|--device) device="$2"; shift ;;
-e|--cryptdev) cryptdev="$2"; shift ;;
-m|--mountpoint) mountpoint="$2"; shift ;;
-p|--passphrase) passphrase="$2"; shift ;; #TODO to be implemented passphrase option for web-UI
-f|--filesystem) filesystem="$2"; shift ;;
--paranoic-mode) paranoic=true;;
# TODO implement non-interactive mode. Allow to pass password from command line.
# TODO Currently it just avoid to print intro and deny random password generation.
# TODO Allow to inject passphrase from command line (not secure)
# TODO create a "--passphrase" option to inject password.
--non-interactive) non_interactive=true;;
--foreground) foreground=true;; # run script in foregrond, allowing to use it on ansible playbooks.
--default) DEFAULT=YES;;
-h|--help) print_help=true;;
-*) echo >&2 "usage: $0 [--help] [print all options]"
exit 1;;
*) echo >&2 "Loading defaults"; DEFAULT=YES;; # terminate while loop
esac
shift
logs_debug "Custom options:"
info >> "$LOGFILE" 2>&1
done
if [[ -n $1 ]]; then
logs_info "Last line of file specified as non-opt/last argument:"
tail -1 $1
fi
# Print Help
if [[ $print_help = true ]]
then
echo ""
usage="$(basename "$0"): a bash script to automate LUKS file system encryption.\n
usage: fast-luks [-h]\n
\n
optionals argumets:\n
-h, --help \t\tshow this help text\n
-c, --cipher \t\tset cipher algorithm [default: aes-xts-plain64]\n
-k, --keysize \t\tset key size [default: 256]\n
-a, --hash_algorithm \tset hash algorithm used for key derivation\n
-d, --device \t\tset device [default: /dev/vdb]\n
-e, --cryptdev \tset crypt device [default: cryptdev]\n
-m, --mountpoint \tset mount point [default: /export]\n
-f, --filesystem \tset filesystem [default: ext4]\n
--paranoic-mode \twipe data after encryption procedure. This take time [default: false]\n
--non-interactive \tnon-interactive mode, only command line [default: false]\n
--foregroun \t\trun script in foreground [default: false]\n
--default \t\tload default values\n"
echo -e $usage
logs_info "Just printing help."
unlock
exit 0
fi
# Print intro
if [[ $non_interactive == false ]]; then intro; fi
# Check if the required applications are installed
check_cryptsetup
# Encrypt volume
encrypt