-
Notifications
You must be signed in to change notification settings - Fork 2
/
qcrypt
executable file
·1409 lines (1218 loc) · 49.8 KB
/
qcrypt
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
#
#See usage().
#
#Copyright (C) 2020 David Hobach GPLv3
#version: 0.9
#
#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with this program. If not, see <https://www.gnu.org/licenses/>.
#
#init blib
source blib
b_checkVersion 1 5 || { >&2 echo "This script depends on blib (https://github.com/3hhh/blib) version 1.5 or higher. Please install a supported version." ; exit 1 ; }
eval "$B_SCRIPT"
b_import "args"
b_import "traps"
b_import "fs"
b_import "arr"
b_import "keys"
b_import "os/qubes4/dom0"
#environment variable: user interaction mode (mostly for password prompts)
#may be one of: auto|gui|tty
#example: `export QCRYPT_UI_MODE="tty"`
QCRYPT_UI_MODE="${QCRYPT_UI_MODE:-auto}"
#distinguish the B_E exit code from the "normal" error
B_RC=6
#default options for b_dom0_qvmRun & b_dom0_exec*
#shellcheck disable=SC2034
B_DOM0_QVM_RUN_PARAMS=("--no-gui")
#shellcheck disable=SC2088
QCRYPT_FOLDER="~/.qcrypt"
QCRYPT_KEYS="$QCRYPT_FOLDER/keys"
#array of destination VMs, parsed by parseDestinations()
declare -a DSTS
#some global arrays required by statusAllC
declare -a S_CAND
declare -A S_DATA
declare -A S_HOPS
declare -A S_BLOCK
function usage {
echo "
Usage: $B_SCRIPT_NAME [options] [command] [source vm] [source file] [key id] [destination vm 1] .. [destination vm n]
Manage files encrypted with multiple encryption layers in Qubes OS dom0. Each layer is supposed to be decrypted inside a dedicated
destination VM until the final destination/target VM can decrypt to the plaintext. The source VM doesn't decrypt itself.
For most threat models it should suffice to have 1-2 layers of encryption. Each layer of course has a performance impact.
- 1 layer can make sense if you don't trust your [source vm], but totally trust [destination vm 1]/the target VM to never become compromised.
- 2 layers can make sense, if you don't trust [source vm], totally trust [destination vm 1] to only do its encrypting and decrypting job (it
should be used exclusively for that) and only have mediocre trust in [destination vm 2]/the target VM. This way attacks starting from the
target VM attempting to leak information by not doing its encryption job properly (e.g. by not encrypting at all) are prevented by
[destination vm 1] doing its encryption job properly.
- More layers can make sense if you want to trust the middle encryption/decryption VMs less and share your trust among them.
[source vm] The VM where to find the data to decrypt ([source file]).
[source file] Full path to the encrypted file inside the [source vm].
[key id] An identifying string for the keys to use. Each VM must have its own key saved under that identifier.
The identifier is the same for all VMs though. Keys are stored locally inside each VM at $QCRYPT_KEYS.
The identifier may only consist of numbers and characters.
If you lose the keys, you lose all encrypted data. So better create a backup.
[destination vm 1 .. n] Layer of VMs to use for decryption in exactly that order. Each VM must have a matching decryption key.
Recommendation: All destination VMs except of the final one should be dedicated to this particular qcrypt chain as
qcrypt open/close may require to start or stop the VMs at will. Moreover it'll further increase the security level.
[command] may be one of:
open
Map the [source file] in [source vm] to a device, attach it to [destination vm 1], then decrypt it there. Afterwards attach the result
to [destination vm 2], decrypt there and so on.
All VMs except for the source and final destination VM may be started automatically during the process.
Options:
-a Autostart all VMs required to be running for this operation (default: only autostart intermediate VMs).
--mp [path] After all layers of encryptions are decrypted in [vm n], attempt to mount the decrypted data to [path].
Otherwise the plaintext device is not mounted.
--inj [vm] [key] Inject the given [key] (full path) from dom0 into the [vm] before opening. This can be useful for disposable VMs.
The parameter can be specified multiple times. Won't override existing keys.
If the [key] resides inside a dom0 blib key store, you can use keystore://[store directory]. To use the default key
store, just use keystore:// .
--cy [vm] [opt] Pass the options [opt] to cryptsetup when the encrypted device for the given [vm] is opened. This parameter may be
specified multiple times. Multiple options can be concatenated; spaces in arguments may require escaping though. Should
be used by experts only.
--ro Attach all involved devices in read-only mode (default: r/w).
status
Check the online and decryption status of the [source vm], all intermediary VMs and the target VM. A non-zero status code indicates the
number of missing steps towards decryption in the target VM.
Invoking the status command without any other parameters will make $B_SCRIPT_NAME attempt to find all potential encryption chains.
Options:
--mp [path] Check whether the final device is mounted at the given [path]. If an empty [path] is specified, check whether it is
mounted somewhere. Without this parameter, the exit code does not include the mount status.
luksInit
Create a new encrypted container in [source vm] as [source file] ([source file] must be a non-existing file path here) and pass the
required keys to the intermediary VMs (path: $QCRYPT_KEYS) under the [key id]. Existing keys are never overwritten, but the algorithm
will abort further processing. Only [destination vm n] will be able to access the plaintext.
Currently only luks containers are supported.
The initial container creation will happen in dom0.
Options:
-a Autostart all VMs required to be running for this operation (default: error out on stopped VMs).
--size [size] Size to allocate for the container (default: 1G). Supported units: K, M, G, T.
--wd [dir] Use the given directory in dom0 for all files temporarily created during the init process (default: /tmp/). Its capacity
must be larger than the --size parameter. /tmp/ in Qubes OS usually only fits 2G.
--ks [size] Size of the keys to deploy in bytes (default: 100).
--bak [folder] Create an unencrypted backup of all keys in the given dom0 folder (default: no backup).
--keystore [dir] Copy all keys to the encrypted blib key store found inside the dom0 directory [dir] (default: not used).
Use '//' for the default key store at $(b_keys_getDefaultStore).
--fs [type] Generate the given file system type with mkfs in the decrypted container (default: ext4).
--enkey [device] Block device to use as entropy source for the key generation (default: /dev/random).
--encon [device] Block device to use as entropy source for the container initialization (default: /dev/urandom).
--cy [vm] [opt] See open. The [vm] must be the one for which the container is created.
close
Detach the [source file] from [destination vm n] and all intermediary VMs. Exits with a zero status code if and only if all remnants
on all VMs were detached.
Options:
--sd Shut down any VMs preventing a successful close operation. This can be useful if the close operation fails due to
Qubes OS or libxenlight errors.
--force Bypass any checks and attempt to close the given chain. This should be used if a previous detach only happened partially
or you shut down one of the involved VMs without closing before.
Important: This may shut down all involved destination VMs.
help
print this help"
exit 1
}
#checkDependencies
#Checks whether the current bash environment suffices the dependency requirements to run this script.
#returns: Nothing, but errors out, if the dependencies are not met.
#@B_E
function checkDependencies {
b_deps "head" "cryptsetup" "qvm-prefs" "qvm-block" "qvm-check" "losetup" \
"df" "mktemp" "mkfs" "chmod" "readlink"
local vmDeps="cryptsetup
losetup
findmnt
head
tar
xargs"
b_dom0_setVMDeps "$vmDeps"
}
#getSourceDeviceType [source file]
#Function meant to run in the source VM in order to obtain the source device type.
#[source file]: as passed to openC
#returns: exit code of 0 = file & no loop device created, 7 = file, loop device exists, 8 = device, other = error
function getSourceDeviceType {
local sourceFile="$1"
if [ -f "$sourceFile" ] ; then
local out=""
out="$(losetup -j "$sourceFile")" || exit 9
[ -z "$out" ] && exit 0 || exit 7
elif [ -b "$sourceFile" ] ; then
exit 8
else
#error
exit 9
fi
}
#getKeyPath [vm] [key ID]
#Obtain the key path from the given key id.
#returns: key path and sets a non-zero exit code on errors
#@B_E
function getKeyPath {
local vm="$1"
local keyId="$2"
local vmUser=""
vmUser="$(qvm-prefs "$vm" default_user)" || { B_ERR="Failed to retrieve the default user for the VM $vm." ; B_E ; }
echo "${QCRYPT_KEYS/#~/\/home\/$vmUser}/$keyId"
}
#parseAndCheckArgs "$@"
#Parse all arguments of this script, apply some normalisations and do some preliminary option checks.
#@B_E
function parseAndCheckArgs {
b_args_init 0 "--mp" 1 "--inj" 2 "--size" 1 "--wd" 1 "--ks" 1 "--bak" 1 "--fs" 1 "--enkey" 1 "--encon" 1 "--cy" 2 "--keystore" 1
b_args_setOptionParamSeparator "<aosep>"
b_args_parse "$@"
assertCorrectParams
}
#getCanonicalFileParameter [parameter index] [fallback]
#Make the given parameter a canonical file path.
#[parameter index]: index for b_args_get (default: 2)
#returns: Sets a zero exit code only on successful canonicalisation.
#shellcheck disable=SC2120
function getCanonicalFileParameter {
local ind="${1:-2}"
local fb="$2"
#canonicalize the file (users may pass e.g. /foo//bar --> /foo/bar however is expected by qcrypt)
local file=
file="$(b_args_get "$ind" "$fb")" || { echo "$file" ; return $? ; }
if [ -n "$file" ] ; then
readlink -m "$file" || { B_ERR="Failed to canonicalize the file: $file" ; B_E ; }
fi
return 0
}
#assertCorrectParams
#Checks whether the command-line parameters are valid and if not, errors out.
#@B_E
function assertCorrectParams {
local cmd="$(b_args_get 0)"
local numArgs="$(b_args_getCount)"
local numOpts="$(b_args_getOptionCount)"
case "$cmd" in
"open")
b_args_assertOptions "-a" "--mp" "--inj" "--ro" "--cy"
;;
"luksInit")
#NOTE: we must also check for the supported luksFormat options here
b_args_assertOptions "-a" "--size" "--wd" "--ks" "--bak" "--fs" "--enkey" "--encon" "--cy" "--keystore"
;;
"close")
b_args_assertOptions "--sd" "--force"
;;
"status")
[ $numArgs -eq 1 ] && [ $numOpts -eq 0 ] && return 0
b_args_assertOptions "--mp"
;;
*)
usage
;;
esac
[ $numArgs -lt 5 ] && usage
local keyId="$(b_args_get 3)"
local keyRegex='^[0-9a-zA-Z_+.-]+$'
[[ "$keyId" =~ $keyRegex ]] || { B_ERR="The given key ID $keyId appears to be invalid." ; B_E ; }
#ensure all regular arguments are non-empty
local i=
for ((i=0;i<$numArgs;i++)) ; do
[ -z "$(b_args_get $i)" ] && B_ERR="Found argument #$(($i +1)) to be empty." && B_E
done
return 0
}
#ensureClosed [source vm] [source file] [key id] [destination vm 1] ... [destination vm n]
#Ensure that the given chain is fully closed (nothing attached anywhere, no open luks devices) and an open operation should succeed.
#returns: Nothing, but calls [B_E](#B_E) on errors.
#@B_E
function ensureClosed {
local state=""
local ret=
state="$(b_args_parse "status" "$@" ; statusSingleC)"
ret=$?
[[ "$state" == *"ERROR"* ]] && B_ERR="Failed to retrieve the chain state."$'\n'"$state" && B_E
[ $ret -eq 0 ] && B_ERR="The chain is already open." && B_E
local re='device mounted:[[:space:]]+no'
[[ ! "$state" =~ $re ]] && B_ERR="The chain appears to be mounted. Overall state:"$'\n'"$state" && B_E
#count "device attached: no" & "device decrypted: no"
local reAttached='device attached:[[:space:]]+no'
local reDecrypted='device decrypted:[[:space:]]+no'
local devAttachedNoCnt=0
local devDecryptedCnt=0
local line=
while IFS= read -r line ; do
if [[ "$line" =~ $reAttached ]] ; then
(( devAttachedNoCnt++ ))
elif [[ "$line" =~ $reDecrypted ]] ; then
(( devDecryptedCnt++ ))
fi
done <<< "$state"
local numDest=$(( $# - 3 ))
if [ $devAttachedNoCnt -eq $numDest ] && [ $devDecryptedCnt -eq $numDest ] ; then
return 0
else
B_ERR="The chain is partially open. Please --force close it first. Overall state:"$'\n'"$state"
B_E
fi
}
#parseCryptsetupParams [map name] [destination VM 1] ... [destination VM n]
#[map name]: Name of the map to return.
#returns: A string which can be eval'ed to a map of VM --> additional cryptsetup options (all in one string, escaped) for that VM.
#@B_E
function parseCryptsetupParams {
local mapName="$1"
shift
declare -A ret=()
local i=0
local vm=
local par=
while b_args_getOption "--cy" "" "$i" > /dev/null ; do
vm="$(b_args_getOption "--cy" "" "$i" 0)" || { B_ERR="Failed to retrieve the VM for the cryptsetup option $i." ; B_E ; }
par="$(b_args_getOption "--cy" "" "$i" 1)" || { B_ERR="Failed to retrieve the parameter for the cryptsetup option $i." ; B_E ; }
b_arr_contains "$vm" "$@" || { B_ERR="The cryptsetup option VM $vm is not part of the destination VMs." ; B_E ; }
#NOTE: we don't escape here as the user is allowed to concatenate parameters himself --> he needs to escape himself (but cryptsetup appears to have almost no options that might require escaping)
ret["$vm"]="${ret["$vm"]} $par"
i=$(($i +1))
done
ret="$(declare -p ret 2> /dev/null)"
echo "${ret/declare -A ret/declare -A $mapName}"
}
#parseDestinations
#Updates the [DSTS](#DSTS) array from the current command-line arguments (using the args module).
#returns: Nothing.
function parseDestinations {
DSTS=()
local i=
local numArgs="$(b_args_getCount)"
for ((i=4;i<$numArgs;i++)) ; do
DSTS+=("$(b_args_get "$i")")
done
return 0
}
#initKeysModule [store dir]
function initKeysModule {
b_keys_init "$B_SCRIPT_NAME" 0 "$QCRYPT_UI_MODE" "" "" "$1"
}
#retrieveFromKeyStore run as root
function retrieveFromKeyStore_root {
local vm="$1"
local keyId="$2"
local storeDir="$3"
initKeysModule "$storeDir"
b_keys_get "${vm}_$keyId"
}
#retrieveFromKeyStore [vm] [key id] [store dir]
#Retrieve the path to the given key in dom0 from the key store.
#[vm]: VM for which to get the key.
#[key id]: ID of the given key.
#[store dir]: Directory of the key store to use (optional).
#returns: Path to the key (may not exist) and sets a zero exit code on success.
#@B_E
function retrieveFromKeyStore {
local vm="$1"
local keyId="$2"
local storeDir="$3"
b_execFuncAs "root" "retrieveFromKeyStore_root" "fs" "multithreading/mtx" "dmcrypt" "keys" - - "$@" || { B_ERR="Failed to retrieve the key $keyId for the VM $vm from the key store $storeDir." ; B_E ; }
}
#see open @usage
#@B_E
function openC {
local rwFlag=0
local autostart=1
declare -A injections
#parse params
local sourceVM="$(b_args_get 1)"
local sourceFile=
sourceFile="$(getCanonicalFileParameter)" || { B_ERR="Failed to canonicalize the source file parameter." ; B_E ; }
local keyId="$(b_args_get 3)"
parseDestinations
b_args_getOption "-a" > /dev/null && autostart=0
b_args_getOption "--ro" > /dev/null && rwFlag=1
local mountPoint="$(b_args_getOption "--mp")"
local i=0
local injTarget=
local injKey=
while b_args_getOption "--inj" "" "$i" > /dev/null ; do
injTarget="$(b_args_getOption "--inj" "" "$i" 0)" || { B_ERR="Failed to retrieve the target VM for the injection $i." ; B_E ; }
injKey="$(b_args_getOption "--inj" "" "$i" 1)" || { B_ERR="Failed to retrieve the key for the injection $i." ; B_E ; }
b_arr_contains "$injTarget" "${DSTS[@]}" || { B_ERR="The injection VM $injTarget is not part of the destination VMs." ; B_E ; }
if [[ "$injKey" == "keystore://"* ]] ; then
local storeDir="${injKey#keystore:/}"
injKey="$(retrieveFromKeyStore "$injTarget" "$keyId" "$storeDir")" || { B_ERR="Could not resolve injection: Failed to retrieve the key $keyId for the VM $injTarget from the key store $storeDir." ; B_E ; }
fi
injections["$injTarget"]="$injKey"
[ -f "$injKey" ] || { B_ERR="No such file: $injKey" ; B_E ; }
i=$(($i +1))
done
local coptStr=
coptStr="$(parseCryptsetupParams "copt" "${DSTS[@]}")" || { B_ERR="Failed to parse the cryptsetup parameters." ; B_E ; }
eval "$coptStr" || { B_ERR="Programming error?!" ; B_E ; }
#make sure that the open doesn't f*ck things up
b_info "Checking whether the chain is fully closed..."
b_setErrorHandler 'b_defaultErrorHandler 1 1 1'
ensureClosed "$sourceVM" "$sourceFile" "$keyId" "${DSTS[@]}"
b_resetErrorHandler 1
if [[ "$B_ERR" == "The chain is already open." ]] ; then
b_info "$B_ERR Nothing to do."
B_ERR=""
return 0
fi
B_E
#start all necessary VMs or check that they are running
if [ $autostart -eq 0 ] ; then
b_info "Starting the VMs $sourceVM ${DSTS[*]}..." 0 1
b_dom0_ensureRunning "$sourceVM" "${DSTS[@]}"
b_info "Done." 1 0
else
#check source & dest and only autostart intermediate VMs
b_dom0_isRunning "$sourceVM" "${DSTS[-1]}"
declare -a interm=("${DSTS[@]::${#DSTS[@]}-1}")
if [ ${#interm[@]} -gt 0 ] ; then
b_info "Starting the intermediate VMs ${interm[*]}..." 0 1
b_dom0_ensureRunning "${interm[@]}"
b_info "Done." 1 0
fi
fi
#create a source device if needed
b_info "Preparing the source VM ${sourceVM}..."
b_silence b_dom0_execFuncIn "$sourceVM" "" "getSourceDeviceType" - - "$sourceFile"
case $? in
0)
#all good
;;
7)
#existing loop device
b_dom0_removeUnusedLoopDevice "$sourceVM" "$sourceFile" 1 || { B_ERR="$sourceFile inside $sourceVM is either in use by Qubes OS or by the VM itself. Please check qvm-block ls. Backing off..." ; B_E ; }
#all good
;;
*)
B_ERR="Failed to identify the source device type or the source is in an invalid state. Maybe the file doesn't exist?!"
B_E
esac
#it is a file --> we need to create a loop device
local toCreate="$sourceFile"
sourceFile="$(b_dom0_createLoopDeviceIfNecessary "$sourceVM" "$toCreate")" || { B_ERR="Failed to create a loop device for the file $toCreate in the VM $sourceVM." ; B_E ; }
#inject keys (if necessary)
local injTarget=""
local injKey=""
local keyPath=""
for injTarget in "${!injections[@]}" ; do
injKey="${injections["$injTarget"]}"
keyPath="$(getKeyPath "$injTarget" "$keyId")"
b_info "Injecting the dom0 key $injKey into the VM $injTarget ($keyPath)..." 0 1
local ret=2
b_setBE 1
#NOTE: we never overwrite!
b_dom0_copy "$injKey" "$injTarget" "$keyPath" 1 1 2> /dev/null
ret=$?
b_resetErrorHandler 1
if [ $ret -eq 0 ] ; then
b_info "Done." 1 0
else
if [[ "$B_ERR" == *"blib_dom0_copyPrepareTarget failed"* ]] ; then
#ignore errors caused due to existing files
B_ERR=""
b_info "Likely injected before." 1 0
else
b_info "Failed." 1 0
B_E
fi
fi
done
#attach & decrypt
local attachFrom="$sourceVM"
local attachFromDevice="$sourceFile"
local mpTo=""
local mapperName="$keyId"
local i=
local lastInd=$(( ${#DSTS[@]} -1 ))
for ((i=0;i<=$lastInd;i++)) ; do
local attachTo="${DSTS[$i]}"
local attachToDevice=""
[ $i -eq $lastInd ] && mpTo="$mountPoint" || mpTo=""
b_info "Attaching to ${attachTo}..."
attachToDevice="$(b_dom0_crossAttachDevice "$attachFrom" "$attachFromDevice" "$attachTo" "$rwFlag")" || { B_ERR="Failed to attach the device $attachFromDevice from the VM $attachFrom to the VM $attachTo." ; B_E ; }
keyPath="$(getKeyPath "$attachTo" "$keyId")" || { B_ERR="Failed to retrieve the key file path inside the VM $attachTo for the key ID $keyId." ; B_E ; }
#NOTE: we use the key ID as device mapper name
b_info "Decrypting inside ${attachTo}..."
#shellcheck disable=SC2154
b_dom0_openCrypt "$attachTo" "$attachToDevice" "$mapperName" "$rwFlag" "$mpTo" "$keyPath" "${copt["$attachTo"]}" || { B_ERR="Failed to decrypt the device $attachToDevice inside the VM $attachTo using the key file $keyPath." ; B_E ; }
#special case: last run
if [ $i -eq $lastInd ] ; then
[ -n "$mpTo" ] && b_info "Mounted the decrypted data to: $mpTo"
else
#update vars
#NOTE: unfortunately /dev/mapper/xyz is a symlink to /dev/dm-[0-9]+ and Qubes only accepts the latter to identify the backend --> we need to find that name from qvm-block
#example for /dev/mapper/foo:
#testing-vm:dm-2 foo
local qvmBlockInfo=""
qvmBlockInfo="$(b_dom0_parseQvmBlock "map")" || { B_ERR="Failed to parse qvm-block ls." ; B_E ; }
attachFromDevice="$(b_dom0_getQvmBlockInfo "$qvmBlockInfo" "device id" "backend" "$attachTo" "description" "$mapperName" "frontend-dev" "")" || { B_ERR="Failed to find the correct backend device ID for the mapper $mapperName inside the VM $attachTo." ; B_E ; }
attachFrom="$attachTo"
fi
done
b_info "Open done."
return 0
}
#ensureFileDoesNotExistIn [vm] [file]
#Makes sure the given file doesn't exist in the given VM and errors out otherwise.
#@B_E
function ensureFileDoesNotExistIn {
local vm="$1"
local file="$2"
local fileEsc=""
printf -v fileEsc '%q' "$file"
local cmd="[ -e $fileEsc ] && exit 5 || exit 0"
local ret=-1
b_silence b_dom0_qvmRun "$vm" "$cmd"
ret=$?
[ $ret -eq 5 ] && B_ERR="There already appears to exist a file named $file in the VM $vm. Will not overwrite." && B_E
[ $ret -ne 0 ] && B_ERR="Failed to execute a command in the VM $vm." && B_E
return 0
}
#checkAvailableSpace [directory] [required space (bytes)]
#Check whether the given directory provides enough space.
#returns: A zero exit code, if enough space is available and a non-zero exit code otherwise.
#@B_E
function checkAvailableSpace {
local dir="$1"
local req="$2"
local avail=""
avail="$(df -B1 --output=avail "$dir")" || { B_ERR="Failed to run df on the directory $dir." ; B_E ; }
local line=
while IFS= read -r line ; do
[[ "$line" =~ ^([0-9]+) ]] && avail="${BASH_REMATCH[1]}" && break
done <<< "$avail"
[ $avail -gt $req ]
}
#see create @usage
#@B_E
function luksInitC {
#parse params
local sourceVM="$(b_args_get 1)"
local sourceFile=
sourceFile="$(getCanonicalFileParameter)" || { B_ERR="Failed to canonicalize the source file parameter." ; B_E ; }
local keyId="$(b_args_get 3)"
parseDestinations
local autostart=1
b_args_getOption "-a" > /dev/null && autostart=0
local size="$(b_args_getOption "--size" "1073741824")"
size="$(b_fs_parseSize "$size")" || { B_ERR="Failed to parse the --size parameter: $size" ; B_E ; }
local workingDir="$(b_args_getOption "--wd" "/tmp")"
mkdir -p "$workingDir" || { B_ERR="Failed to create $workingDir." ; B_E ; }
[ -d "$workingDir" ] || { B_ERR="No directory: $workingDir" ; B_E ; }
local keySize="$(b_args_getOptionInt "--ks" "100")"
local enKey="$(b_args_getOption "--enkey" "/dev/random")"
[ -c "$enKey" ] || { B_ERR="No valid entropy source: $enKey" ; B_E ; }
local enCon="$(b_args_getOption "--encon" "/dev/urandom")"
[ -c "$enCon" ] || { B_ERR="No valid entropy source: $enCon" ; B_E ; }
local keyBackupFolder="$(b_args_getOption "--bak")"
if [ -n "$keyBackupFolder" ] ; then
mkdir -p "$keyBackupFolder" || { B_ERR="Failed to create $keyBackupFolder." ; B_E ; }
[ -d "$keyBackupFolder" ] || { B_ERR="No directory: $keyBackupFolder" ; B_E ; }
fi
local keyStore="$(b_args_getOption "--keystore")"
if [ -n "$keyStore" ] ; then
[[ "$keyStore" == "//" ]] && keyStore="$(b_keys_getDefaultStore)"
[ ! -d "$keyStore" ] && [ -e "$keyStore" ] && B_ERR="No directory: $keyStore" && B_E
fi
local fsType="$(b_args_getOption "--fs" "ext4")"
local coptStr=
coptStr="$(parseCryptsetupParams "copt" "${DSTS[@]}")" || { B_ERR="Failed to parse the cryptsetup parameters." ; B_E ; }
eval "$coptStr" || { B_ERR="Programming error?!" ; B_E ; }
#luks2 has high memory requirements, which we need to fix (https://gitlab.com/cryptsetup/cryptsetup/-/issues/372)
local dst=
for dst in "${DSTS[@]}" ; do
local opts="${copt["$dst"]}"
if [[ "$opts" != *"--type"** ]] && [[ "$opts" != *"--pbkdf-memory"* ]] ; then
#limit the memory requirements to 10MB
copt["$dst"]="$opts --pbkdf-memory 10240"
fi
done
#safety checks
b_info "Doing some safety checks..."
# a. we need to be root in dom0
b_enforceUser "root"
# b. we need to have enough space in dom0
checkAvailableSpace "$workingDir" "$size" || { B_ERR="$workingDir provides less space than required by the --size parameter." ; B_E ; }
# c. all necessary VMs must run
[ $autostart -eq 0 ] && b_dom0_ensureRunning "$sourceVM" "${DSTS[@]}" || b_dom0_isRunning "$sourceVM" "${DSTS[@]}"
# d. make sure the source VM doesn't already have a file named $sourceFile
ensureFileDoesNotExistIn "$sourceVM" "$sourceFile"
# e. make sure the key ID is not used in any of the destination VMs
local dst=""
local vmKeyPath=""
declare -A vmKeyPaths
for dst in "${DSTS[@]}" ; do
vmKeyPath="$(getKeyPath "$dst" "$keyId")" || { B_ERR="Failed to retrieve the key file path inside the VM $dst for the key ID $keyId." ; B_E ; }
vmKeyPaths["$dst"]="$vmKeyPath"
ensureFileDoesNotExistIn "$dst" "$vmKeyPath"
done
#init container
local dom0Container=""
local cmd=""
dom0Container="$(mktemp -p "$workingDir")" || { B_ERR="Failed to create a temporary file." ; B_E ; }
printf -v cmd 'rm -f %q' "$dom0Container"
b_traps_add "$cmd" EXIT || { B_ERR="Failed to register a cleanup trap." ; B_E ; }
b_info "Initializing the luks container (this may take a while)..."
head -c $size < "$enCon" > "$dom0Container" || { B_ERR="Failed to initialize the container at $dom0Container." ; B_E ; }
#create a loop device for the container
local dom0ContainerLoop=""
dom0ContainerLoop="$(losetup -f --show "$dom0Container")" || { B_ERR="Failed to create a loop device." ; B_E ; }
printf -v cmd 'losetup -d %q' "$dom0ContainerLoop"
b_traps_prepend "$cmd" EXIT || { B_ERR="Failed to register a cleanup trap." ; B_E ; }
#generate key files & add encryption layers
local dom0KeyFile=""
declare -A dom0KeyFiles
local curDevice="$dom0ContainerLoop"
for dst in "${DSTS[@]}" ; do
#generate key
b_info "Generating the key for the VM ${dst}..."
dom0KeyFile="$(mktemp -p "$workingDir")" || { B_ERR="Failed to create a temporary file." ; B_E ; }
printf -v cmd 'b_fs_removeRelativelySafely %q' "$dom0KeyFile"
b_traps_add "$cmd" EXIT || { B_ERR="Failed to register a cleanup trap." ; B_E ; }
head -c "$keySize" < "$enKey" > "$dom0KeyFile" || { B_ERR="Failed to initialize the key for the VM $dst at $dom0KeyFile." ; B_E ; }
dom0KeyFiles["$dst"]="$dom0KeyFile"
#format
b_info "Generating the encryption layer for the VM ${dst}..."
cryptsetup -q --key-file "$dom0KeyFile" ${copt["$dst"]} luksFormat "$curDevice" || { B_ERR="Failed to run cryptsetup luksFormat." ; B_E ; }
#open the newly created layer
b_info "Switching to the next encryption layer..."
local luksName="$dst-$keyId"
cryptsetup open --type luks --key-file "$dom0KeyFile" "$curDevice" "$luksName" || { B_ERR="Failed to open the encryption layer created for the VM $dst." ; B_E ; }
printf -v cmd 'cryptsetup close %q' "$luksName"
b_traps_prepend "$cmd" EXIT || { B_ERR="Failed to register a cleanup trap." ; B_E ; }
curDevice="/dev/mapper/$luksName"
done
#optional: generate file system
if [ -n "$fsType" ] ; then
b_info "Creating the file system..."
mkfs -t "$fsType" "$curDevice" &> /dev/null || { B_ERR="Failed to create the file system of type $fsType on $curDevice." ; B_E ; }
fi
#optional: create a backup of the keys in dom0
#NOTE: if this fails, we don't need to pass all the stuff to the VMs
if [ -n "$keyBackupFolder" ] ; then
b_info "Backing up all keys to $keyBackupFolder..."
for dst in "${DSTS[@]}" ; do
dom0KeyFile="${dom0KeyFiles["$dst"]}"
local bakFile="$keyBackupFolder/${dst}_$keyId"
[ -e "$bakFile" ] && B_ERR="A file called $bakFile already exists. Rejecting to overwrite." && B_E
cp "$dom0KeyFile" "$bakFile" || { B_ERR="Failed to copy the key file $dom0KeyFile to $bakFile." ; B_E ; }
chmod 666 "$bakFile"
done
fi
#optional: copy the keys to the key store
if [ -n "$keyStore" ] ; then
b_info "Adding the keys to the blib key store $keyStore..."
initKeysModule "$keyStore"
for dst in "${DSTS[@]}" ; do
dom0KeyFile="${dom0KeyFiles["$dst"]}"
b_keys_add "${dst}_$keyId" "$dom0KeyFile"
done
fi
#pass the keys to the VMs
for dst in "${DSTS[@]}" ; do
dom0KeyFile="${dom0KeyFiles["$dst"]}"
vmKeyPath="${vmKeyPaths["$dst"]}"
b_info "Passing the key $dom0KeyFile to the VM $dst as $vmKeyPath..."
b_dom0_copy "$dom0KeyFile" "$dst" "$vmKeyPath" 1 1 || { B_ERR="Failed to copy the key file $dom0KeyFile." ; B_E ; }
done
#pass the container to the source VM
b_info "Copying the encrypted container to the VM $sourceVM at ${sourceFile}..."
sync
b_dom0_copy "$dom0Container" "$sourceVM" "$sourceFile" 1 1 || { B_ERR="Failed to copy the encrypted container to the source VM $sourceVM." ; B_E ; }
sync
b_info "Luks init done."
b_info "Cleaning up... (this is not hanging)"
return 0
}
#closeDecryptedData [mapper name]
#Closes the given luks container inside a target VM.
#[mapper name]: Name of the device mapper to close.
#returns: 11, if the device mapper did not exist (wasn't open), 22 on cryptsetup errors during closing
function closeDecryptedData {
local mapperName="$1"
local mapperNameEsc=""
printf -v mapperNameEsc '%q' "$mapperName"
! [ -b /dev/mapper/$mapperNameEsc ] && exit 11
cryptsetup close $mapperNameEsc || exit 22
exit 0
}
#closeSourceLoop [source vm] [source file]
#@B_E
function closeSourceLoop {
local sourceVM="$1"
local sourceFile="$2"
local ret=
b_info "Closing the loop device inside $sourceVM..." 0 1
b_setBE 1
b_dom0_execFuncIn "$sourceVM" "" "detachLoop" - - "$sourceFile" &> /dev/null
ret=$?
b_resetErrorHandler
if [ $ret -eq 17 ] ; then
b_info "No loop device found. All good." 1 0
elif [ $ret -eq 0 ] ; then
b_info "Done." 1 0
else
#last action, no need for force
B_ERR="Failed to close."
B_E
fi
return 0
}
#cleanClose [force flag] [shutdown flag] [source VM] [source file] [key id] [destination 1] ... [destination n]
#Attempt to perform a "clean" close without shutting down any VMs.
#returns: Exits with a zero status code if and only if all remnants on all VMs were detached.
#@B_E
function cleanClose {
local force="$1" #currently cannot be 0
local shutdown="$2"
local sourceVM="$3"
local sourceFile="$4"
local keyId="$5"
shift 5
declare -a dsts=("$@")
#NOTE: we use the key ID as luks mapper name
local mapperName="$keyId"
local mapperNameEsc=""
printf -v mapperNameEsc '%q' "$mapperName"
#attempt umount in the final destination VM
local err=""
local dst="${dsts[*]: -1}"
local ret=-1
b_info "Umounting the plaintext device inside ${dst}..." 0 1
local cmd="findmnt -n -o TARGET -S /dev/mapper/$mapperNameEsc | head -n1 | xargs umount -A -R || exit 17"
b_setBE 1
b_dom0_qvmRun "$dst" "$cmd" &> /dev/null
ret=$?
b_resetErrorHandler
if [ $ret -eq 17 ] ; then
b_info "Was not mounted. All good." 1 0
elif [ $ret -eq 0 ] ; then
b_info "Done." 1 0
else
err="Failed to umount."
[ $force -eq 0 ] && b_info "$err Proceeding anyway..." 1 0 || { B_ERR="$err No point in proceeding." ; B_E ; }
fi
#cryptsetup close & detach afterwards in all VMs (if necessary)
local qvmBlockInfo=""
qvmBlockInfo="$(b_dom0_parseQvmBlock "map")" || { B_ERR="Failed to parse qvm-block ls." ; B_E ; }
local i=
local desc=
for ((i=${#dsts[@]}-1;i >= 0;i--)) ; do
local vm="${dsts[$i]}"
#close
b_info "Closing the dm-crypt device inside ${vm}..." 0 1
b_setBE 1
b_dom0_execFuncIn "$vm" "" "closeDecryptedData" - - "$mapperName" &> /dev/null
ret=$?
b_resetErrorHandler
case $ret in
0)
b_info "Done." 1 0
;;
11)
b_info "Was not open. All good." 1 0
;;
*)
err="Failed to close the dm-crypt device (status: $ret)."
[ $force -eq 0 ] && b_info "$err Proceeding anyway..." 1 0 || { B_ERR="$err No point in proceeding." ; B_E ; }
esac
#detach
#example qvm-block ls output:
#result of `qcrypt open -- disp287 /tmp/foo4 foo4 testing-pers d-testing`
#BACKEND:DEVID DESCRIPTION USED BY
#disp287:loop0 /tmp/foo4 testing-pers (read-only=no, frontend-dev=xvdi)
#testing-pers:dm-0 foo4 d-testing (read-only=no, frontend-dev=xvdi)
#foo4 is the /dev/mapper/foo4 name inside testing-pers providing a symlink to /dev/dm-0 and used by d-testing as /dev/xvdi
#--> we'd have to detach:
# qvm-block d d-testing testing-pers:dm-0
# qvm-block d testing-pers disp287:loop0
#--> resulting in an empty "used by" column
[ $i -eq 0 ] && desc="$sourceFile" || desc="$mapperName"
b_info "Detaching the device from the VM $vm..." 0 1
local backend=""
backend="$(b_dom0_getQvmBlockInfo "$qvmBlockInfo" "id" "description" "$desc" "used by" "$vm")"
[ $? -eq $B_RC ] && { B_ERR="Failed to parse qvm-block ls." ; B_E ; }
if [ -z "$backend" ] ; then
b_info "Was not attached. All good." 1 0
else
qvm-block d "$vm" "$backend" &> /dev/null
if [ $? -eq 0 ] ; then
b_info "Done." 1 0
else
if [ $shutdown -eq 0 ] ; then
#similar to what --force does, but we attempted to properly detach it before
b_info "Failed, trying to shutdown... " 1 1
b_dom0_ensureHalted "$vm"
b_info "Done." 1 0
else
err="Failed to detach the backend $backend from the VM $vm. No point in proceeding."
[ $force -eq 0 ] && b_info "$err Proceeding anyway..." 1 0 || { B_ERR="$err No point in proceeding." ; B_E ; }
fi
fi
fi
done
closeSourceLoop "$sourceVM" "$sourceFile"
[ -z "$err" ]
}
#dirtyClose [source VM] [source file] [key id] [destination 1] ... [destination n]
#Attempt to perform a "dirty" close by simply shutting down all destination VMs.
#returns: Exits with a zero status code if and only if all remnants on all VMs were detached.
#@B_E
function dirtyClose {
local sourceVM="$1"
local sourceFile="$2"
local keyId="$3"
shift 3
declare -a dsts=("$@")
local i=
for ((i=${#dsts[@]}-1;i >= 0;i--)) ; do
local vm="${dsts[$i]}"
#NOTES:
# - using qvm-block in any way is likely to trigger Qubes OS bug #4784
# - we better shut down one after another as this will give Qubes OS some time to do the device detach cleanup (and in order)
b_info "Shutting down the VM ${vm}..." 0 1
b_dom0_ensureHalted "$vm"
#give Qubes OS some time to clean up the mess (i.e. do the detach)
sleep 0.2
b_info "Done." 1 0
done
closeSourceLoop "$sourceVM" "$sourceFile"
return 0
}
#see close @usage
#@B_E
function closeC {
local force=1
local shutdown=1
#parse params
b_args_getOption "--force" > /dev/null && force=0
b_args_getOption "--sd" > /dev/null && shutdown=0
local sourceVM="$(b_args_get 1)"
local sourceFile=
sourceFile="$(getCanonicalFileParameter)" || { B_ERR="Failed to canonicalize the source file parameter." ; B_E ; }
local keyId="$(b_args_get 3)"
parseDestinations
#make sure the given chain is valid by checking its status
#NOTE: we also check that the chain is mounted as it might otherwise be incomplete (missing target VM) and we don't want a partial closure
if [ $force -ne 0 ] ; then
b_info "Checking the validity of the chain..." 0 1
local state=""
state="$(b_args_parse "status" "$sourceVM" "$sourceFile" "$keyId" "${DSTS[@]}" ; statusSingleC)" || { B_ERR="The chain has a bad status - check it below. If you want to continue nonetheless, use --force."$'\n'"$state" ; B_E ; }
b_info "Done. All good." 1 0
cleanClose "$force" "$shutdown" "$sourceVM" "$sourceFile" "$keyId" "${DSTS[@]}"
else
b_info "Force mode. Thus attempting a dirty close..."
# Reasoning: Qubes OS bug #4784 (https://github.com/QubesOS/qubes-issues/issues/4784) will make the system unusable until the next reboot, if any of the destination VMs are shut down and the above "clean" close is attempted afterwards.
# Available workarounds:
# 1. Never close and re-use the leftover open devices from previous qcrypt open operations. <-- not chosen
# 2. Perform the below "dirty" close by shutting down all destination VMs _without_ using qvm-block at all. This prevents bug #4784 from being triggered as of Qubes OS 4.0.1. <-- chosen
dirtyClose "$sourceVM" "$sourceFile" "$keyId" "${DSTS[@]}"
fi
b_info "Close done."
return $ret
}
#detachLoop [file]
#Detach the loop device associated with the given file, if it exists.
#returns: an exit code of 17, if it doesn't exist; an exit code of 0 on success and a non-zero exit code on failure
function detachLoop {
local filePath="$1"
local found="$(losetup -n -O NAME -j "$filePath")"
if [ -z "$found" ] ; then
exit 17
else
losetup -d "$found"
fi
}
#getVMStatus [key path] [mapper name] [device name] [mount path]
#Get the encryption state for the VM this function is running in.
#[device name]: Name of the _encrypted_ attached device; may be empty, if no device is attached.
#returns: 0 = key is available & device decrypted & mounted at the mount path (or somewhere, if not specified), 1 = key is available & device decrypted & not mounted, 2 = key available & device not decrypted, 3 = key unavailable & device not decrypted, 9 = other error
function getVMStatus {
local keyPath="$1"
local mapperName="$2"
local mapperPath="/dev/mapper/$mapperName"
local devName="$3"
local mp="$4"
local mpList=""
local keyAvailable=-1
[ -f "$keyPath" ] && keyAvailable=0 || keyAvailable=1
#special case: no device
[ -z "$devName" ] && return $(( $keyAvailable +2 ))
local cryptAvailable=-1
cryptsetup status "$mapperName" &> /dev/null && cryptAvailable=0 || cryptAvailable=1
if [ $keyAvailable -eq 0 ] ; then
if [ $cryptAvailable -eq 0 ] ; then
mpList="$(findmnt -l -o TARGET -n -S "$mapperPath")" || return 1
if [ -z "$mp" ] ; then
return 0