-
Notifications
You must be signed in to change notification settings - Fork 0
/
cryptimg
executable file
·114 lines (96 loc) · 2.5 KB
/
cryptimg
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
#!/bin/bash
set -e
verify_img_name() {
IMG_NAME=${1%.cryptimg.bin}
IMG_FILE="$IMG_NAME.cryptimg.bin"
[[ ! "$IMG_NAME" =~ ^[a-z0-9-]+$ ]] && echo "invalid name '$IMG_NAME'" && exit 1 || true
case "$2" in
exists) [ ! -f "$IMG_FILE" ] && echo "'$IMG_FILE' not found" && exit 1 || true ;;
*) [ -f "$IMG_FILE" ] && echo "'$IMG_FILE' already exists" && exit 1 || true ;;
esac
}
verify_size() {
SIZE=$1
[[ ! "$SIZE" =~ ^[0-9]+[MGT]$ ]] && echo "invalid size '$SIZE' (..M, ..G, ..T)" && exit 1 || true
}
luks_init() {
IMG_UUID="$(cryptsetup luksUUID "$IMG_FILE").cryptimg"
IMG_DEV="/dev/mapper/$IMG_UUID"
}
luks_open() {
if [ ! -b "$IMG_DEV" ]; then
if [ "$1" == "ro" ]; then
sudo cryptsetup -r luksOpen "$IMG_FILE" "$IMG_UUID"
else
sudo cryptsetup luksOpen "$IMG_FILE" "$IMG_UUID"
fi
fi
}
luks_close() {
if [ -b "$IMG_DEV" ]; then
sudo cryptsetup luksClose "$IMG_UUID"
fi
}
img_umount() {
if [ -b "$IMG_DEV" ] && [ -d "$IMG_NAME" ]; then
BK_DEVNO=$(mountpoint -qx "$IMG_DEV" || true)
FS_DEVNO=$(mountpoint -qd "$IMG_NAME" || true)
if [ -n "$BK_DEVNO" ] && [ "$BK_DEVNO" == "$FS_DEVNO" ]; then
sudo umount "$IMG_DEV"
fi
fi
if [ -d "$IMG_NAME" ]; then
rmdir "$IMG_NAME" || true
fi
}
img_mount() {
if ! mountpoint -qd "$IMG_NAME"; then
mkdir "$IMG_NAME"
sudo mount "$IMG_DEV" "$IMG_NAME"
fi
}
cmd_create() {
verify_img_name "$1"
verify_size "$2"
echo "creating disk image..."
fallocate -l "$SIZE" "$IMG_FILE"
sudo cryptsetup -qy luksFormat "$IMG_FILE"
echo "unlock to continue..."
luks_init
luks_open
echo "creating ext4 filesystem..."
sudo mkfs.ext4 "$IMG_DEV"
echo "mounting..."
img_mount
echo "done"
}
cmd_mount() {
verify_img_name "$1" exists
luks_init
luks_open "$2"
img_mount
}
cmd_umount() {
verify_img_name "$1" exists
luks_init
img_umount
luks_close
}
cmd_dump() {
verify_img_name "$1" exists
cryptsetup luksDump "$IMG_FILE"
}
case "$1" in
create) cmd_create $2 $3 ;;
mount) cmd_mount $2 ;;
mount-ro) cmd_mount $2 ro ;;
umount) cmd_umount $2 ;;
dump) cmd_dump $2 ;;
*)
echo "usage: ${0##*/} create <name> <size>"
echo " ${0##*/} mount <name>"
echo " ${0##*/} mount-ro <name>"
echo " ${0##*/} umount <name>"
echo " ${0##*/} dump <name>"
;;
esac