-
Notifications
You must be signed in to change notification settings - Fork 0
/
encrypt-draft.sh
executable file
·605 lines (550 loc) · 19.3 KB
/
encrypt-draft.sh
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
#!/bin/bash
DEBUG=false
SYMMETRIC_OPTIONS="--no-symkey-cache --s2k-cipher-algo AES256 --s2k-digest-algo SHA512 --s2k-count 65011700 --pinentry-mode loopback"
USAGE="
-- Encryption options --
decrypt - Decrypt the given file using the specified keyfile and journal entry to stdout.
Required Flags:
--entry : Specify the file entry to decrypt using the specified keyfile.
--keyfile : Supply a key file containing the user generated password
for the symeteric encryption of given journal entry.
--key-from-url: Supply a URL containing encrypted symetric key for decryption
--proxy : Should proxy via Tor be enabled for key-from-url operations?
Enabling this option allows use of tor hidden service urls.
--secret : Prompts user for answers to paremeters instead of requiring
them to input on command line to protect from bash history.
encrypt - Encrypts a given file using decrypted symetric key specified.
Optional flags:
--type : Specify the type of journal entry to encrypt (new or archive)
The default assumes type 'new'
--config_path : Supply a path to the files root path if not already in current path
--keyfile : Supply a key file containing the user generated password
for the symeteric encryption of given journal entry.
Default assumes 'key.asc' in current path
--key-from-url: Supply a URL containing encrypted symetric key for decryption
--proxy : Should proxy via Tor be enabled for key-from-url operations?
Enabling this option allows use of tor hidden service urls.
--secret : Prompts user for answers to paremeters instead of requiring
them to input on command line to protect from bash history.
backup - Creates an encrypted backup archive
Optional flags:
--config_path : Supply a path to the journal root path if not already in current path
--backup_path : Supply a path of where to write the encrypted tar archive to
Default assumes 'HOME/jbackup' which should be an external mounted device
--keyfile : Supply a key file containing the password for the symeteric encryption
of the backup archive to be created.
Default assumes 'backup_key.asc' in current path
--key-from-url: Supply a URL containing encrypted symetric key for archive encryption
--proxy : Should proxy via Tor be enabled for key-from-url operations?
Enabling this option allows use of tor hidden service urls.
--secret : Prompts user for answers to paremeters instead of requiring
them to input on command line to protect from bash history.
-- Misc options --
version - Shows the script version
newkey - Generates a new symetric key for a given recipient
newdraft - Create a new draft file for the current day.
"
#: Shows the version of the script
version(){
printf "\nThis is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org/>
GnuPG is copyrighted by The GnuPG Project and is licenced under the
Creative Commons Attribution-ShareAlike 3.0 Unported License. While refrenced
in the code of the script, this script in no way modifies the terms of the
GnuPG licence or its libraries.
\n"
info_msg "Version: 0.1.0-alpha"
}
newDraft(){
safety_check
if [ -f "$draftfile" ];
then
fail_out "Draft file aready exists"
else
printf "$(date +%A%t%B%t%d%t%Y%n)%s\n\n" > "$draftfile" 2>&1
success_msg "New draft completed successfully... Exiting"
fi
}
safety_check(){
debug_msg "${CURRENT_FP}"
debug_msg "${BACKUP_FP}"
debug_msg "Decrypted Password: ${SECRET}"
debug_msg "Base Path: ${BASE}"
debug_msg "Current Path: ${JOURNAL_BASE}"
debug_msg "Current Backup Path: ${BACKUP_FP}"
## Check to see if ${CURRENT_FP} is set, if not set set ${BASE} to current path
if [[ -z "${CURRENT_FP+x}" ]]; then
BASE="$(pwd -P)"
[[ -n "${BASE}" ]] || error_msg "Safety Check: Could not set BASE"
else
BASE="${CURRENT_FP}"
fi
## Check to see if ${BACKUP_FP} is set, if not set ${BACKUP} to /backup
if [[ -z ${BACKUP_FP+x} ]]; then
BACKUP="${HOME}/jbackup"
[[ -n "${BACKUP}" ]] || error_msg "Safety Check: Could not set BACKUP path"
else
BACKUP="${BACKUP_FP}"
fi
JOURNAL_BASE="${BASE}/$(date +%Y)/$(date +%B)"
efile="${JOURNAL_BASE}/$(date +%b_%d).asc"
draftfile="${BASE}/draft/$(date +%F).txt"
debug_msg "New Base Path: ${BASE}"
debug_msg "New Current Path: ${JOURNAL_BASE}"
debug_msg "New Backup Path: ${BACKUP}"
debug_msg "Script Option Command is $_op"
if [[ -n "${DISABLE_SAFETY_CHECK_CFG}" && ${DISABLE_SAFETY_CHECK_CFG} == "true" ]]; then
info_msg "Skipping file safety checks"
else
if [[ ! -d "${JOURNAL_BASE}" || ! -d "${BASE}/draft/" ]]; then
info_msg "Creating paths.."
mkdir -p "${BASE}"/draft/ || error_msg "Safety Check: Failed to create DRAFT directory"
mkdir -p "${JOURNAL_BASE}" || error_msg "Safety Check: Failed to create BASE directory"
stopped_msg "Try again"
exit 0
elif [[ -f "$efile" && $TYPE != "new" ]]; then
if [ -s "$efile" ]; then
debug_msg "Encrypted destination will be $efile"
fail_out "Safety Check: Encrypted Journal exists and not empty"
else
error_msg "Saftey Check: Encrypted Journal exists but empty..."
exit 2;
fi
else
info_msg "Safey Checks passed, continuing..."
lastBackup
return 0
fi
fi
}
encryptDraft(){
safety_check
debug_msg "$draftfile"
info_msg "Formatting File"
if [ -f "$draftfile" ]; then
doEncrypt
else
error_msg "Today's Draft is missing, please check current path..."
fi
if [ -n "$(ls -A "${BASE}"/draft/)" ]; then
warn_msg "Draft directory not empty!"
read -r -p "Would you like to encrypt old draft entries? [Y/n] " ans
case $ans in
[yY]) encryptOld ;;
[nN])
exit 0
;;
*)
fail_out "Invalid Input"
;;
esac
else
success_msg "There were no file candiates for encryption found... Exiting"
exit 0
fi
}
shredSource(){
info_msg "Shredding Draft..."
if [[ -f $efile ]]
then
shred -ufz -n 35 "$draftfile" || warn_msg "Could not complete shred operation"
success_msg "Shred action completed successfully"
else
fail_out "Shred Action failed, please check previous encryption operation"
fi
}
encryptOld() {
safety_check
shopt -s globstar
for draft in "${BASE}"/draft/*.txt;
do
debug_msg "Current File: ${draft}"
[[ -e "${draft}" ]] || fail_out "Draft directory empty"
local entrydate
entrydate=$(echo "${draft}" |awk -F/ 'NF{ print $NF }'|cut -f1 -d'.')
Year=$(date -d "${entrydate}" +%Y)
Month=$(date -d "${entrydate}" +%B)
Day=$(date -d "${entrydate}" +%b_%d)
efile="${BASE}/${Year}/${Month}/${Day}.asc"
if [[ ! -d "${BASE}/${Year}/${Month}" ]]; then
mkdir -p "${BASE}/${Year}/${Month}" || fail_out "Could not create path..."
fi
local draftfile
draftfile="${draft}" || fail_out "Could not read draft"
doEncrypt
done
success_msg "Completed archive encryption operations"
}
doEncrypt(){
info_msg "Encrypting Entry in ${draftfile} ..."
(fold -s -w 72 | gpg2 -ac --batch ${SYMMETRIC_OPTIONS} --passphrase "${SECRET}" -o "${efile}")< "${draftfile}" || error_msg "Encryption Failed"
info_msg "Journal entry successfully encrypted... "
## Possible at later time to add date/time check to ensure that the created file is actualy a new file, not old.
if [[ -f $efile && -s $efile ]]; then
shredSource || warn_message "Unable to complete shred action"
elif [[ -f $efile && ! -s $efile ]]; then
fail_out "An error occured, encrypted journal is empty... "
else
fail_out "Encrypted Journal Entry currently exists, please verify destination path."
fi
}
randpw(){ tr -s -dc '[:alnum:]' '[:alnum:]' < /dev/urandom | head -c "${1:-$(shuf -i 64-96 -n1)}";echo;}
V3SecretKey(){ head -c 3705 /dev/random | uuencode -m - | head -n 66 | tail -n 65;echo; }
# Add random length for better deniability of knowing key ^ shuf -i 64-96 -n1
newKey(){
secret=$(randpw)
info_msg "Where should we output the new key? Specify a location or type stdout to output to screen"
read -rp "Enter Absolute Path: " keylocation
read -rp "Who is recipient of the key? " recipient
debug_msg "Generated Key is: $secret"
[[ $keylocation == /* || $keylocation == "stdout" ]] || fail_out "You did not give an absolute path, we are unable to resolve relative paths"
if [[ $keylocation == "stdout" ]]; then
echo "$secret" | gpg2 -ea -R "$recipient" -
else
local keyfile
keyfile=$(readlink -f "$keylocation")
debug_msg "Keyfile: $keyfile"
[[ -n $keyfile ]] || error_msg "Keyfile path empty"
echo "$secret" | gpg2 -ea --batch -o "$keyfile" -R "$recipient" -
if [[ -f $keyfile ]]; then
success_msg "Secret Key successfully written to $keyfile"
else
error_msg "Unable to write secret to file."
fi
fi
}
newBackupKey(){
info_msg "Where should we output the new key? Specify a location or type stdout to output to screen"
read -rp "Enter Absolute Path: " keylocation
#read -rp "Who is recipient of the key? " recipient
[[ $keylocation == /* || $keylocation == "stdout" ]] || fail_out "You did not give an absolute path, we are unable to resolve relative paths"
if [[ $keylocation == "stdout" ]]; then
printf "%s" "$(V3SecretKey)" | gpg2 -ca ${SYMMETRIC_OPTIONS} - || fail_out "Unable to complete encryption of generated key"
else
bkeyfile=$(readlink -f "$keylocation")
debug_msg "Keyfile: $bkeyfile"
#debug_msg "Recipient: $recipient"
[[ -n $bkeyfile ]] || error_msg "Keyfile path empty"
printf "%s" "$(V3SecretKey)" | gpg2 -ca ${SYMMETRIC_OPTIONS} -o "${bkeyfile}" - || fail_out "Unable to complete encryption of generated key"
if [[ -f $bkeyfile ]]; then
success_msg "Secret Key successfully written to $bkeyfile"
else
error_msg "Unable to write secret to file."
fi
fi
}
encrypt(){
checkKey
if [[ -n $TYPE && $TYPE == "new" ]]; then
encryptDraft
elif [[ -n $TYPE && $TYPE == "archive" || $TYPE == "old" ]]; then
encryptOld
else
info_msg "No type specififed, assuming new"
encryptDraft
fi
}
decrypt(){
checkKey
debug_msg "File Entry: ${ENTRY}"
debug_msg "Password: ${SECRET}"
# We print the entry with printf to stdout instead of decrypting to file for security of the entry
printf "$(gpg2 -dq --batch --pinentry-mode loopback --passphrase "${SECRET}" "${ENTRY}")%s\n"
}
backup(){
trap 'find ${TMPDIR} -type f -exec shred -ufz -n 35 {} \; && rmdir ${TMPDIR}' EXIT
checkKey
warn_msg "Unit Tests for BACKUP Incomplete"
safety_check
local DIR
local DSIZE
DIR="${BASE}/draft/"
DSIZE=$(du -sh "${BASE}")
if [ ! "$(ls -A "$DIR")" ]; then
info_msg "Backup of ${BASE} to ${BACKUP} in progress"
#tar -cfz ${BASE} | gpg2 -b -c --batch ${SYMMETRIC_OPTIONS} --pinentry-mode loopback --passphrase ${SECRET} -o ${BACKUP}/backup.tgz.gpg
tar -cfz "${BASE}"| bzip2 | aespipe -w 10 -e aes256 -H sha512 -K "${KEYFILE}" > ${BACKUP}/backup_$(date +%F)_enc.tar.bz2
local DVD_DEFAULT
DVD_DEFAULT='n'
read -e -rp "Backup of ${BASE} complete, would you like to create an offline encrypted backup on CD/DVD? (n/Y)" DVD
local DVD=${DVD:-${DVD_DEFAULT}}
local DVD=${DVD,,}
debug_msg "Burn DVD: ${DVD}"
if [[ ${DVD} == 'y' || ${DVD} == 'yes' ]]; then
checkPkgs
info_msg "Please insert a CD or DVD in drive before prceeding."
info_msg "Estimated Size is ${DSIZE}"
#Check if space is free to write image to temp space
read -rp "Press any key to continue... " -n1 -s
info_msg "Writing data in ${BASE} to disk, please wait"
TMPDIR=$(mktemp -d)
debug_msg "Our Temporary Path is: $TMPDIR"
genisoimage -quiet -r "${BASE}" | aespipe -w 5 -e aes256 -H sha512 -K "${KEYFILE}" > ${BACKUP}/documents_enc.iso
#wodim dev=/dev/dvdrw ${TMPDIR}/documents.iso || fail_out "Unable to burn image to disk, please try again"
#shred -ufvz -n 35 ${TMPDIR}/documents.iso || fail_out "Unable to complete shred action, please verify file deletion."
#rm -rf $TMPDIR || fail_out "We could not remove the temproary directory, you should consider manually removing"
info_msg "Backup file written to ${BACKUP}"
else
info_msg "Backup complete, have a nice day!"
exit 0
fi
else
fail_out "Take action ${DIR} is not Empty"
fi
}
lastBackup(){
local newest
newest=$(find "${BACKUP}" -type f -printf "%T@ %p\n" | sort -n | cut -d' ' -f 2- | tail -n 1)
if [[ -n ${newest} ]]; then
local last
local cur
local sub
local nxt
last=$(date -r "${newest}" +%s)
cur=$(date +%s)
sub=$((cur-last))
nxt=$((cur+1209600))
if [[ ${sub} -ge 1209600 ]]; then
warn_msg "Last backup is older than TWO WEEKS! Run backup ASAP!!"
else
info_msg "Next backup should not exceed $(date -d @${nxt})"
fi
else
fail_out "Could not find latest backup, is ${BACKUP} mounted?"
fi
}
is_secret(){
if [[ -n ${TOPSECRET} && ${TOPSECRET,,} == 'true' && -z ${KEY_URL} ]]; then
read -r -e -p "Please type the URL you'd like to keep secret: " URL
KEY_URL=$URL
debug_msg "Secret URL: ${KEY_URL}"
fi
}
checkKey(){
is_secret
if [[ -n ${KEYFILE} && ${DISABLE_SAFETY_CHECK_CFG} != "true" ]]; then
SECRET=$(gpg2 -dq --batch "${KEYFILE}" | tr -d '[:space:]')
elif [[ -n ${KEY_URL} ]]; then
if [[ -n ${PROXY} && ${PROXY,,} == 'true' || ${PROXY,,} == 'yes' ]]; then
debug_msg "URL: ${KEY_URL}"
debug_msg "Proxy enabled: ${PROXY}"
SECRET=$(curl -s --socks5-hostname '127.0.0.1:9050' "${KEY_URL}" | gpg2 -dq --batch - | tr -d '[:space:]')
else
SECRET=$(curl -s "${KEY_URL}" | gpg2 -dq --batch - | tr -d '[:space:]')
fi
else
fail_out "Key option is required, specify key."
fi
}
checkPkgs(){
# Check that packages for dvd burning of encrypted iso are installed
local SUPPORTED
SUPPORTED=$(dpkg -s aespipe wodim genisoimage &> /dev/null)$?
#SUPPORTED=$(yum -q aespipe wodim genisoimage &> /dev/null)$? ## Detection for Redhat Family
if [[ ! ${SUPPORTED} -eq 0 ]]; then
debug_msg "Supported Exit status: ${SUPPORTED}"
fail_out "Action not supportted, please install aespipe, genisoimage and wodim packages for your distribution"
else
info_msg "Supported packages installed, continuing backup..."
fi
}
#: Mimic codes
GREEN='\e[0;32m'
CYAN='\e[0;36m'
YELLOW='\e[1;33m'
RED='\e[0;31m'
BLUE='\e[1;94m'
WARN='\e[1;5;31m'
NC='\e[0m' # No Color
ERROR_SIG="[${RED}ERROR${NC}]\n"
INFO_SIG="[${GREEN}INFO${NC}]\n"
STOPPED_SIG="[${YELLOW}STOPPED${NC}]\n"
SUCCESS_SIG="[${CYAN}SUCCESS${NC}]\n"
DEBUG_SIG="[${BLUE}DEBUG${NC}]\n"
WARN_SIG="[${WARN}WARNING${NC}]\n"
#: Helper functions
usage() {
echo "Usage: $0 <command> <options>"
echo "${USAGE}"
exit 1
}
error_msg() {
strlen=${#1}
cols=$(($(tput cols) - "${strlen}"))
printf "%${strlen}s %${cols}b" "$1" "${ERROR_SIG}"
}
info_msg() {
strlen=${#1}
cols=$(($(tput cols) - "${strlen}"))
printf "%${strlen}s %${cols}b" "$1" "${INFO_SIG}"
}
stopped_msg() {
strlen=${#1}
cols=$(($(tput cols) - "${strlen}"))
printf "%${strlen}s %${cols}b" "$1" "${STOPPED_SIG}"
}
success_msg() {
strlen=${#1}
cols=$(($(tput cols) - "${strlen}"))
printf "%${strlen}s %${cols}b" "$1" "${SUCCESS_SIG}"
}
debug_msg(){
strlen=${#1}
cols=$(($(tput cols) - "${strlen}"))
if [[ ${DEBUG} != false ]]; then
printf "%${strlen}s %${cols}b" "$1" "${DEBUG_SIG}"
fi
}
warn_msg(){
strlen=${#1}
cols=$(($(tput cols) - "${strlen}"))
printf "%${strlen}s %${cols}b" "$1" "${WARN_SIG}"
}
fail_out(){
error_msg "$@"
exit 1
}
check_uid() {
if [[ $(id -u) -lt 1000 ]] ; then echo "Please run as USER" ; exit 1 ; fi
}
### ARGUMENTS ###
handle_args(){
#Possible Use later, save for posterity and future use.
#: The first argument is the operation being performed (e.g. encrypt, decrypt, or backup).
local _op=$1
shift
###
### #: 2.x agents read a cached agent ID from bootstrap.cfg - by reusing this file, we can reuse previous agent ID.
if [ "$_op" == "backup" ] || [ "$_op" == "backupstatus" ]; then
DISABLE_SAFETY_CHECK_CFG=true
fi
# As long as there is at least one more argument, keep looping
while [[ $# -gt 0 ]]; do
local _key="$1"
case "${_key}" in
-t|--type)
shift
TYPE="$1"
;;
-t=*|--type=*)
TYPE="${_key#*=}"
;;
-k|--keyfile)
shift
KEYFILE="$1"
;;
-k=*|--keyfile=*)
KEYFILE="${_key#*=}"
;;
-u|--key-from-url)
shift
KEY_URL="$1"
;;
-u=*|--key-from-url=*)
KEY_URL="${_key#*=}"
;;
-c|--config_path)
shift
CURRENT_FP="$1"
;;
-c=*|--config_path=*)
CURRENT_FP="${_key#*=}"
;;
-b|--backup_path)
shift
BACKUP_FP="$1"
;;
-b=*|--backup_path=*)
BACKUP_FP="${_key#*=}"
;;
-e|--entry)
shift
ENTRY="$1"
;;
-e=*|--entry=*)
ENTRY="${_key#*=}"
;;
-p|--proxy)
shift
PROXY="true"
;;
-p=*|--proxy=*)
PROXY="${_key#*=}"
;;
-s|--secret)
shift
TOPSECRET="true"
;;
-s=*|--secret=*)
TOPSECRET="${_key#*=}"
;;
*)
# Error on unknown options
fail_out "Unknown option '${_key}'"
;;
esac
# Shift after checking all the cases to get the next option
shift
done
}
############
### MAIN ###
############
[ $# -lt 1 ] && usage
check_uid
case "$1" in
#: main opts
encrypt)
handle_args "$@"
encrypt
;;
decrypt)
handle_args "$@"
decrypt
;;
backup)
handle_args "$@"
backup
;;
#: misc opts
version)
version
;;
newkey)
newKey
;;
newbackupkey)
newBackupKey
;;
newdraft)
newDraft
;;
backupstatus)
lastBackup
;;
help)
usage
;;
*)
usage
;;
esac
exit 0