]> git.scottworley.com Git - overonion/blob - overonion
5eb26b68f42c23335cb2ef6dfa9690a3452973ff
[overonion] / overonion
1 #!/bin/bash
2
3 umask 077
4
5 hash_dir=$(mktemp -d)
6
7 function die() {
8 echo "$*" >&2
9 exit 1
10 }
11
12 if (( $# != 2));then
13 die "usage: overonion e|d keyfile"
14 fi
15 mode=$1
16 if [[ "$mode" != e && "$mode" != d ]];then
17 die "Use 'e' for encrypt or 'd' for decrypt"
18 fi
19 keyfile=$2
20 if [[ ! -e "$keyfile" ]];then
21 die "Keyfile not found"
22 fi
23 if [[ ! -r "$keyfile" ]];then
24 die "Cannot read keyfile"
25 fi
26
27 num_layers=$(wc -l < "$keyfile")
28 if (( num_layers < 20 ));then
29 die "Keyfile doesn't have enough layers to be an onion"
30 fi
31
32 hash_fields=$(awk '/^openssl-dgst / { print NF }' "$keyfile" | uniq )
33
34 if [[ "$mode" == e ]];then
35 first_layer=$num_layers
36 next_layer=-1
37 openssl_decrypt=""
38 if [[ "$hash_fields" != 4 ]];then
39 die "Refusing to encrypt with already-used key"
40 fi
41 else
42 first_layer=1
43 next_layer=1
44 openssl_decrypt="-d"
45 if [[ "$hash_fields" != 5 ]];then
46 die "Key does not appear to have been used for encryption (it has no embedded hashes). Refusing to decrypt."
47 fi
48 fi
49
50 function go() {
51 layer=$1
52 if (( layer == 0 || layer > num_layers ));then
53 cat
54 else
55 operation=$(sed -n "${layer}{;s/ .*//;p;}" "$keyfile")
56 if [[ "$operation" == openssl-enc ]];then
57 openssl enc $openssl_decrypt "-$(sed -rn "${layer}s/[^ ]+ ([^ ]+) .*/\\1/p" "$keyfile")" \
58 -pass fd:37 37< <(sed -rn "${layer}s/^[^ ]+ [^ ]+ //p" "$keyfile")
59 elif [[ "$operation" == reverse ]];then
60 reverse
61 elif [[ "$operation" == openssl-dgst ]];then
62 tee >(echo "$(sed -n "${layer}p" "$keyfile") $(
63 {
64 awk -vlayer="$layer" 'NR == layer { print $3 }' "$keyfile" | base64 -d
65 cat
66 awk -vlayer="$layer" 'NR == layer { print $4 }' "$keyfile" | base64 -d
67 } |
68 openssl dgst -binary "-$(sed -rn "${layer}s/^[^ ]+ ([^ ]+).*/\\1/p" "$keyfile")" |
69 base64 --wrap=0)" > "$hash_dir/$layer")
70 else
71 die "Unknown operation"
72 fi |
73 go $(( layer + next_layer ))
74 fi
75 }
76
77 go "$first_layer"
78
79 for hash_result in "$hash_dir"/*;do
80 layer=$(basename "$hash_result")
81 if [[ "$mode" == e ]];then
82 # Add the hashes to keyfile
83 key_aside_dir=$(mktemp -d "$keyfile.XXXXXXXXXX")
84 key_aside="$key_aside_dir/key.orig"
85 mv "$keyfile" "$key_aside"
86 sed "${layer}s,.*,$(< "$hash_result")," "$key_aside" > "$keyfile"
87 shred -u "$key_aside"
88 rmdir "$key_aside_dir"
89 else
90 # Verify the hashes
91 if [[ "$(awk '{ print $5 == $6 ? "hash ok" : "mismatch" }' "$hash_result")" != "hash ok" ]];then
92 die "Hash check $layer failed"
93 fi
94 fi
95 done
96
97 rm -r "$hash_dir"