-
Notifications
You must be signed in to change notification settings - Fork 5
/
encfsgui_helper.py
603 lines (510 loc) · 19.6 KB
/
encfsgui_helper.py
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
import os
import platform
import sys
import time
import datetime
import string
import subprocess
import inspect
import traceback
from PyQt5 import uic
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import *
from PyQt5 import QtCore
try:
import base64
import hashlib
from Crypto import Random
from Crypto.Cipher import AES
except:
oops = QApplication([])
QtWidgets.QMessageBox.critical(None,"Error loading pycrypto library","This version of pyencfsgui requires the 'pycrypto' library.\n\nPlease install using\n'python3 -m pip install pycrypto --user'\n")
sys.exit(1)
import encfsgui_globals
from encfsgui_globals import *
import cgetmasterkey
from cgetmasterkey import CMasterKeyWindow
#################################
### METHODS, HELPER FUNCTIONS ###
#################################
def getCurDir():
print_debug("Start %s" % inspect.stack()[0][3])
curdir = "./"
try:
os.chdir(os.path.dirname(os.path.abspath(sys.argv[0])))
curdir = os.getcwd()
except Exception as e:
print_debug("Unable to determine current directory: %s" % str(e))
pass
return curdir
def getNow():
return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
def getVersion():
thisversion = ""
versionlines = readfile("version.txt")
for thisline in versionlines:
if not thisline.strip() == "":
thisversion = thisline.strip()
break
return thisversion
def readfile(filename):
print_debug("Start %s" % inspect.stack()[0][3])
print_debug("Reading %s" % filename)
contents = []
try:
f = open(filename,"r")
contents = f.readlines()
f.close()
print_debug("Read %d lines" % len(contents))
except Exception as e:
print_debug("Unable to read file %s: %s" % (filename, str(e)))
pass
return contents
def writefile(filename,contents):
f = open(filename,'a')
for l in contents:
f.write("%s\n" % l)
f.close()
return
def createFile(filename):
f = open(filename,'w+')
f.write("# file created at %s\n" % getNow())
f.close()
return
def print_debug(line):
if encfsgui_globals.debugmode:
#try:
# print("%s - DEBUG : %s" % (getNow(), str(line)))
#except Exception:
# print(traceback.format_exc())
writefile(encfsgui_globals.logfile, ["%s : %s" % (getNow(), str(line)) ] )
return
def getTmpName():
return datetime.datetime.now().strftime("%Y%m%d%H%M%S")
def getEncFSVersion():
print_debug("Start %s" % inspect.stack()[0][3])
encfsversion = ""
oscmd = encfsgui_globals.g_Settings["encfspath"]
cmdargs = '--version'
cmdoutput = execOSCmd("%s %s" % (oscmd,cmdargs ))
outputline = cmdoutput[0]
for line in cmdoutput:
if line.startswith("encfs "):
outputline = line
break
outputparts = outputline.split(" ")
encfsversion = outputparts[-1].replace('\n','')
return encfsversion
def getGoCryptFSVersion():
print_debug("Start %s" % inspect.stack()[0][3])
gocryptfsversion = ""
oscmd = encfsgui_globals.g_Settings["gocryptfspath"]
cmdargs = '--version'
cmdoutput = execOSCmd("%s %s" % (oscmd,cmdargs ))
outputline = cmdoutput[0]
for line in cmdoutput:
if line.startswith("gocryptfs "):
outputline = line
break
outputparts = outputline.split(";")
gocryptfspart = outputparts[0]
versionparts = gocryptfspart.split(" ")
gocryptfsversion = versionparts[-1].replace('\n','')
return gocryptfsversion
def ifExists(encfsapp="encfs"):
print_debug("Start %s" % inspect.stack()[0][3])
encbinfound = False
dictkey = "%spath" % encfsapp
if dictkey in encfsgui_globals.g_Settings:
encbinpath = encfsgui_globals.g_Settings[dictkey]
if os.path.exists(encbinpath):
encbinfound = True
return encbinfound
def getOSType():
return platform.system()
def ismacOS():
if "darwin" in getOSType().lower():
return True
else:
return False
def isLinux():
if "linux" in getOSType().lower():
return True
else:
return False
def isWindows():
if "windows" in getOSType().lower():
return True
else:
return False
def runwhich(binarytofind):
whichlocation = ""
if binarytofind != "":
cmd = ["which",binarytofind]
cmdlines, cmdretval = execOSCmdRetVal(cmd)
# get the first line that contains the binarytofind
for line in cmdlines:
if binarytofind in line:
if os.path.exists(line.strip()):
whichlocation = line.strip()
break
return whichlocation
def execOSCmd(cmd):
print_debug("Start %s" % inspect.stack()[0][3])
if not cmd.startswith("sh -c"):
print_debug("Executing [ %s ]" % cmd)
else:
print_debug("Note: A part of the command below will not shown because it might contain sensitive information (password)")
cmdparts = cmd.split("|")
if len(cmdparts) > 1:
print_debug("Executing [ %s ]" % cmdparts[1])
p = subprocess.Popen('%s' % cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
shell=True)
outputobj = iter(p.stdout.readline, b'')
outputlines = []
for l in outputobj:
thisline = l.decode()
outputlines.append(thisline.replace('\\n','').replace("'",""))
return outputlines
def execOSCmdRetVal(cmdarray):
print_debug("Start %s" % inspect.stack()[0][3])
print_debug("Executing %s" % cmdarray)
returncode = 0
outputlines = []
p = subprocess.run(cmdarray, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
returncode = p.returncode
outputobj = p.stdout.split('\n')
for thisline in outputobj:
outputlines.append(thisline.replace('\\n','').replace("'",""))
print_debug("Return code: %s" % str(returncode))
return outputlines, returncode
def execOScmdAsync(cmdarray):
print_debug("Start %s" % inspect.stack()[0][3])
print_debug("Executing %s" % cmdarray)
p = subprocess.Popen(cmdarray)
#p.terminate()
return
def openFolder(foldername):
print_debug("Start %s" % inspect.stack()[0][3])
if ismacOS():
subprocess.call(["open", "-R", foldername + "/"])
elif isLinux():
subprocess.call(["xdg-open", foldername + "/"])
return
def getKeyChainPassword(volumename):
print_debug("Start %s" % inspect.stack()[0][3])
objname = "EncFSGUI_%s" % volumename
cmd = "sh -c \"security find-generic-password -a '%s' -s '%s' -w login.keychain\"" % (objname, objname)
passarr = execOSCmd(cmd)
password = str(passarr[0]).replace("\n","").strip()
return password
def autoUpdate():
#return values:
# -1 = error
# 0 = ok, no update
# 1 = update found
updateresult = 0 # up to date
print_debug("Start %s" % inspect.stack()[0][3])
cmdarr = ["git","pull"]
gitoutput, gitretval = execOSCmdRetVal(cmdarr)
if (encfsgui_globals.debugmode):
print_debug("Git output:")
if gitretval != 0:
updateresult = -1
else:
updatefound = False
for l in gitoutput:
if (encfsgui_globals.debugmode):
print_debug(" >> %s" % l)
if ":" in l and not "fatal" in l and not "not staged" in l and not "hint:" in l:
updatefound = True
break
if updatefound:
updateresult = 1 # update found
return updateresult, gitoutput
def getExpectScriptContents(scripttype, insertbreak = False):
print_debug("Start %s" % inspect.stack()[0][3])
scriptcontents = ""
if scripttype == "encfs":
# header
newline = "#!/usr/bin/env expect\n"
scriptcontents += newline
newline = "set passwd [lindex $argv 0]\n"
scriptcontents += newline
newline = "set timeout 10\n"
scriptcontents += newline
# launch encfs
newline = "spawn \"$ENCFSBIN\" -v \"$ENCPATH\" \"$MOUNTPATH\"\n"
scriptcontents += newline
# activate expert mode
newline = "expect \"Please choose from one of the following options:\"\n"
scriptcontents += newline
newline = "expect \"?>\"\n"
scriptcontents += newline
newline = "send \"x\\n\"\n"
scriptcontents += newline
# set cipher algorithm
newline = "expect \"Enter the number corresponding to your choice: \"\n"
scriptcontents += newline
newline = "send \"$CIPHERALGO\\n\"\n"
scriptcontents += newline
# select cipher keysize
newline = "expect \"Selected key size:\"\n"
scriptcontents += newline
newline = "send \"$CIPHERKEYSIZE\\n\"\n"
scriptcontents += newline
# select filesystem block size
newline = "expect \"filesystem block size:\"\n"
scriptcontents += newline
newline = "send \"$BLOCKSIZE\\n\"\n"
scriptcontents += newline
# select encoding algo
newline = "expect \"Enter the number corresponding to your choice: \"\n"
scriptcontents += newline
newline = "send \"$ENCODINGALGO\\n\"\n"
scriptcontents += newline
if (insertbreak):
newline = "break\n"
scriptcontents += newline
# filename IV chaining
newline = "expect \"Enable filename initialization vector chaining?\"\n"
scriptcontents += newline
newline = "send \"$IVCHAINING\\n\"\n"
scriptcontents += newline
# per filename IV
newline = "expect \"Enable per-file initialization vectors?\"\n"
scriptcontents += newline
newline = "send \"$PERFILEIV\\n\"\n"
scriptcontents += newline
# file to IV header chaining can only be used when both previous options are enabled
# which means it might slide to the next option right away
newline = "expect {\n"
scriptcontents += newline
newline = "\t\"Enable filename to IV header chaining?\" {\n"
scriptcontents += newline
newline = "\t\tsend \"$FILETOIVHEADERCHAINING\\n\"\n"
scriptcontents += newline
newline = "\t\texpect \"Enable block authentication code headers\"\n"
scriptcontents += newline
newline = "\t\tsend \"$BLOCKAUTHCODEHEADERS\\n\"\n"
scriptcontents += newline
newline = "\t\t}\n"
scriptcontents += newline
newline = "\t\"Enable block authentication code headers\" {\n" #space matters
scriptcontents += newline
newline = "\t\tsend \"$BLOCKAUTHCODEHEADERS\\n\"\n"
scriptcontents += newline
newline = "\t\t}\n"
scriptcontents += newline
newline = "\t}\n"
scriptcontents += newline
# add random bytes to each block header
newline = "expect \"Select a number of bytes, from 0 (no random bytes) to 8: \"\n"
scriptcontents += newline
newline = "send \"0\\n\"\n"
scriptcontents += newline
# file-hole pass-through
newline = "expect \"Enable file-hole pass-through?\"\n"
scriptcontents += newline
newline = "send \"\\n\"\n"
scriptcontents += newline
# password
newline = "expect \"New Encfs Password: \"\n"
scriptcontents += newline
newline = "send \"$passwd\\n\"\n"
scriptcontents += newline
newline = "expect \"Verify Encfs Password: \"\n"
scriptcontents += newline
newline = "send \"$passwd\\n\"\n"
scriptcontents += newline
newline = "puts \"\\nDone.\\n\"\n"
scriptcontents += newline
newline = "expect \"\\n\"\n"
scriptcontents += newline
newline = "sleep x\n"
scriptcontents += newline
if scripttype == "gocryptfs":
# header
newline = "#!/usr/bin/env expect\n"
scriptcontents += newline
newline = "set passwd [lindex $argv 0]\n"
scriptcontents += newline
newline = "set timeout 10\n"
scriptcontents += newline
# launch encfs
newline = "spawn \"$GOCRYPTFSBIN\" $EXTRAOPTS -init \"$ENCPATH\" \n"
scriptcontents += newline
# password
newline = "expect \"Password:\"\n"
scriptcontents += newline
newline = "send \"$passwd\\n\"\n"
scriptcontents += newline
newline = "expect \"Repeat:\"\n"
scriptcontents += newline
newline = "send \"$passwd\\n\"\n"
scriptcontents += newline
newline = "expect \"\\n\"\n"
scriptcontents += newline
newline = "sleep x\n"
scriptcontents += newline
return scriptcontents
def determineFileNameEncodings():
print_debug("Start %s" % inspect.stack()[0][3])
encodings = []
# create 2 new tmp folders
tmpname = getTmpName()
cwd = os.getcwd()
tmpfolder_enc = os.path.join(cwd, tmpname+"_enc")
tmpfolder_mnt = os.path.join(cwd, tmpname+"_mnt")
if os.path.exists(tmpfolder_enc):
os.removedirs(tmpfolder_enc)
if os.path.exists(tmpfolder_mnt):
os.removedirs(tmpfolder_mnt)
os.mkdir(tmpfolder_enc)
os.mkdir(tmpfolder_mnt)
if os.path.exists(encfsgui_globals.g_Settings["encfspath"]):
# try to create an encrypted volume, and parse output to determine the available fileencoding options
# argument True is needed to insert 'break' after getting the encoding options
scriptcontents = getExpectScriptContents("encfs",True)
password = "boguspassword"
# replace variables in the script
scriptcontents = scriptcontents.replace("$ENCFSBIN", encfsgui_globals.g_Settings["encfspath"])
scriptcontents = scriptcontents.replace("$ENCPATH", tmpfolder_enc)
scriptcontents = scriptcontents.replace("$MOUNTPATH", tmpfolder_mnt)
if not str(getEncFSVersion()).startswith("1.9."):
scriptcontents = scriptcontents.replace("$CIPHERALGO", "1")
else:
scriptcontents = scriptcontents.replace("$CIPHERALGO", "1")
scriptcontents = scriptcontents.replace("$CIPHERKEYSIZE", "128")
scriptcontents = scriptcontents.replace("$BLOCKSIZE", "1024")
scriptcontents = scriptcontents.replace("$ENCODINGALGO", "1")
scriptcontents = scriptcontents.replace("$IVCHAINING","")
scriptcontents = scriptcontents.replace("$PERFILEIV","")
scriptcontents = scriptcontents.replace("$FILETOIVHEADERCHAINING","y")
scriptcontents = scriptcontents.replace("$BLOCKAUTHCODEHEADERS","")
scriptcontents = scriptcontents.replace("sleep x","expect eof")
expectfilename = "expect.encfsgui"
# write script to file
scriptfile = open(expectfilename, 'w')
scriptfile.write(scriptcontents)
scriptfile.close()
# run script file
cmd = "expect '%s' '%s'" % (expectfilename, password)
expectoutput = execOSCmd(cmd)
# parse output
startfound = False
endfound = False
rawCaps = []
for l in expectoutput:
#print_debug(">>> %s" % l)
if not startfound:
if "filename encoding algorithms" in l and "available" in l:
startfound = True
else:
if not "." in l:
endfound = True
else:
rawCaps.append(l)
if startfound and endfound:
break
if not startfound:
rawCaps.clear()
endfound = False
# maybe encfs is in a different language, try in a different way
for l in expectoutput:
if not startfound:
if "1. Block" in l:
startfound = True
rawCaps.append(l)
else:
if not "." in l:
endfound = True
else:
rawCaps.append(l)
if startfound and endfound:
break
for l in rawCaps:
capparts = l.split(" ")
if len(capparts) > 1:
thisencoding = capparts[1]
encodings.append(thisencoding)
else:
print_debug("No encfs binary found at %s" % encfsgui_globals.g_Settings["encfspath"])
if len(encodings) > 0:
encfsgui_globals.g_Encodings = encodings
else:
print_debug("Unable to get filename encodings")
for l in expectoutput:
print_debug("%s" % l)
# clean up again
os.removedirs(tmpfolder_enc)
os.removedirs(tmpfolder_mnt)
os.remove(expectfilename)
return
def getMasterKey():
print_debug("Start %s" % inspect.stack()[0][3])
curframe = inspect.currentframe()
calframe = inspect.getouterframes(curframe, 2)
print_debug("%s() Called from: %s()" % (inspect.stack()[0][3],calframe[1][3]))
print_debug("Current length of masterkey: %d" % len(encfsgui_globals.masterkey))
if len(encfsgui_globals.masterkey) != 32:
frmpassword = CMasterKeyWindow()
frmpassword.setWindowTitle("Please enter master key")
frmpassword.show()
frmpassword.setFocus()
frmpassword.activateWindow()
frmpassword.exec_()
encfsgui_globals.masterkey = str(frmpassword.getPassword())
print_debug("New length of masterkey: %d" % len(encfsgui_globals.masterkey ))
return
def encrypt(cleartext):
print_debug("Start %s" % inspect.stack()[0][3])
curframe = inspect.currentframe()
calframe = inspect.getouterframes(curframe, 2)
print_debug("%s() Called from: %s()" % (inspect.stack()[0][3],calframe[1][3]))
ciphertext = ""
encfsgui_globals.masterkey = str(encfsgui_globals.masterkey)
#print_debug("Current length of masterkey: %d" % len(encfsgui_globals.masterkey))
obj = AES.new(encfsgui_globals.masterkey, AES.MODE_CBC, '!IVNotSoSecret!!')
while (len(cleartext) % 16 != 0):
# add spaces at the end, we can remove them later
cleartext = cleartext + " "
ciphertext=base64.b64encode(obj.encrypt(cleartext))
return ciphertext.decode()
def decrypt(ciphertext):
print_debug("Start %s" % inspect.stack()[0][3])
curframe = inspect.currentframe()
calframe = inspect.getouterframes(curframe, 2)
print_debug("%s() Called from: %s()" % (inspect.stack()[0][3],calframe[1][3]))
encfsgui_globals.masterkey = str(encfsgui_globals.masterkey)
#print_debug("Current length of masterkey: %d" % len(encfsgui_globals.masterkey))
cleartext = ""
#print_debug("Requested to decrypt '%s'" % ciphertext)
#print_debug("Base64 decoded: %s" % base64.b64decode(ciphertext))
obj = AES.new(encfsgui_globals.masterkey, AES.MODE_CBC, '!IVNotSoSecret!!')
cleartext = obj.decrypt(base64.b64decode(ciphertext))
#remove spaces from the end again
cleartext = cleartext.rstrip()
return cleartext
def makePW32(key):
print_debug("Start %s" % inspect.stack()[0][3])
pw = key[0:31]
ccode = 1
while len(pw) < 32:
pw += chr(ccode)
ccode += 1
return pw
def SavePasswordInKeyChain(volumename, password):
print_debug("Start %s" % inspect.stack()[0][3])
cmd = "sh -c \"security add-generic-password -U -a 'EncFSGUI_%s' -s 'EncFSGUI_%s' -w '%s' login.keychain\"" % (volumename, volumename, str(password))
print_debug(cmd)
setpwoutput = execOSCmd(cmd)
return
def RemovePasswordFromKeyChain(volumename):
print_debug("Start %s" % inspect.stack()[0][3])
cmd = "sh -c \"security delete-generic-password -a 'EncFSGUI_%s' -s 'EncFSGUI_%s' login.keychain\"" % (volumename, volumename)
print_debug(cmd)
setpwoutput = execOSCmd(cmd)
return