-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlbcp.py
1616 lines (1393 loc) · 61.2 KB
/
lbcp.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
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
#!/usr/bin/env python2.7
__author__ = "Leonid Bloch"
__copyright__ = "Copyright 2014, Leonid Bloch"
__license__ = "GPLv2"
__version__ = "0.1"
__email__ = "[email protected]"
from os import walk, urandom, access, R_OK, W_OK, sep, symlink, makedirs, remove, listdir, lstat
from os.path import join, getsize, abspath, islink, realpath, isfile, exists, dirname, expanduser
from datetime import datetime, timedelta
import hashlib
import numpy as np
import fnmatch
import re
from zlib import compressobj, decompressobj
from Crypto.Cipher import AES
import struct
from boto.s3.connection import S3Connection
from boto.exception import S3ResponseError, S3CreateError
from boto.s3.key import Key
from boto.s3.connection import Location
from boto.s3.multipart import part_lister
import io
import sys
import shutil
import progressbar
import getpass
from math import ceil
import argparse
import signal
###################################################################
### Parsing the arguments
parser = argparse.ArgumentParser(description = ("Compressed, encrypted,"
" deduplicated backup to Amazon's S3"),
epilog = ("===> For options of the different actions"
" check \"%(prog)s ACTION -h\""
" (for example: \"%(prog)s backup -h\")"))
# Initiating subparsers (for different actions)
subparsers = parser.add_subparsers(dest = 'action', help = "Choose the desired action")
# Backup arguments
parser_backup = subparsers.add_parser('backup', help = "Initiate backup.")
parser_backup.add_argument('mypaths', nargs = '+', metavar = "BACKUPPATH",
help = "Paths to backup.")
parser_backup.add_argument('-e', '--exclude', dest = 'excludes', nargs = '+',
metavar = "PATTERN",
help = "Paths/file patterns to exclude from backup.")
parser_backup.add_argument('-d', '--device', metavar = "DEVICE",
help = ("Specify the device you want to backup. The device"
" might be a distinct physical device, or a different location on"
" the same device. If only one device is backed up on the physical"
" device, you need to enter this parameter only during the initial"
" backup (will be detected during consecutive backups). If this"
" parameter is neither specified nor detected, you will be"
" prompted."))
parser_backup.add_argument('-c', '--credsfile', dest = 'credsFile', default = 'default',
metavar = "PATH",
help = ("Path to the credentials file you've downloaded from"
" Amazon (.csv format: User Name, Access Key Id, Secret Access"
" Key). If you choose to encrypt this file after the first use"
" (RECOMMENDED!) you won't have to use this option on the"
" same physical device anymore. It is, however, required for"
" the initial backup of any new physical device."
" (default: <LOGPATH>/credentials.csv.enc)."))
parser_backup.add_argument('--bucket', dest = 'mybucket', metavar = "BUCKET",
help = ("The bucket for uploading. Doesn't have to exist during"
" the first backup, but has to be the same afterwards,"
" for ALL backups and devices. Should be provided only during"
" the first backup on each device (otherwise it is detected)."
" If this argument is neither specified nor detected, you will"
" be prompted to enter a value."))
parser_backup.add_argument('--oldlogbucket', dest = 'oldlogBucket', default = 'default',
metavar = "BUCKET",
help = ("The bucket for backup of old log files. Can be the same"
" as the main upload bucket, but specifying a new one might help"
" to manage the old logs better (for example, move all of the"
" old logs to Glacier. (default: <MAIN BUCKET>-oldlogs)."))
parser_backup.add_argument('--credsenc', dest = 'credsEnc', action = 'store_true',
default = 'default',
help = ("Specify that the credentials file is encrypted."
" The default behavior is \"True\" if the credentials file is"
" <LOGPATH>/credentials.csv.enc, and \"False\" otherwise."))
parser_backup.add_argument('--geolocation', dest = 'newLoc', default = 'DEFAULT',
metavar = "LOCATION",
choices = ['APNortheast', 'APSoutheast', 'APSoutheast2',
'CNNorth1', 'DEFAULT', 'EU', 'SAEast', 'USWest',
'USWest2'],
help = ("Geographic location to create a new bucket in."
" Only useful if creating a new bucket (beginning a totally"
" fresh backup, to a currently unexisting bucket)."
" Options: \"APNortheast\", \"APSoutheast\", \"APSoutheast2\","
" \"CNNorth1\", \"DEFAULT\", \"EU\", \"SAEast\", \"USWest\","
" \"USWest2\""
" (default: DEFAULT)."))
parser_backup.add_argument('--logpath', dest = 'logPath', metavar = "PATH",
default = expanduser('~') + sep + ".lbcp",
help = ("Path to the log files. Needs to be the same during the"
" entire lifetime of all the backups on the device."
" Do NOT use this option unless you have REALLY specific needs."
" (default: $HOME/.lbcp)."))
# Restore arguments
parser_restore = subparsers.add_parser('restore', help = "Initiate rstore.")
parser_restore.add_argument('restoreThis', nargs = '+', metavar = "RESTOREPATH",
help = ("Paths to restore. If restoring on a different"
" device, a full path of the restored files is required."
" Generally, it is recommended to use the full path anyway."))
parser_restore.add_argument('restorePath', metavar = "SAVEPATH",
help = "Path to which the restored files will be downloaded.")
parser_restore.add_argument('-d', '--device', metavar = "DEVICE",
help = ("Specify the device you want to restore from. The device"
" might be a distinct physical device, or a different location on"
" the same device. If only one device is backed up on the"
" physical device you're working on, and you want to restore"
" from it, you don't have to specify this parameter - it is"
" detected automatically. If this parameter is neither specified"
" nor detected, you will be prompted."))
parser_restore.add_argument('-c', '--credsfile', dest = 'credsFile', default = 'default',
metavar = "PATH",
help = ("Path to the credentials file you've downloaded from"
" Amazon (.csv format: User Name, Access Key Id, Secret Access"
" Key). If you chose to encrypt this file after the first use"
" (RECOMMENDED!) you don't have to use this option on the"
" same physical device anymore. It is, however, required if"
" restoring on a new or different physical device."
" (default: <LOGPATH>/credentials.csv.enc)."))
parser_restore.add_argument('--bucket', dest = 'mybucket', metavar = "BUCKET",
help = ("The bucket from which to restore. Should be specified"
" only if the restore is on a different or a new device"
" (it is detected automatically otherwise)."
" If this argument is neither specified nor detected, you will"
" be prompted to enter a value."))
parser_restore.add_argument('--credsenc', dest = 'credsEnc', action = 'store_true',
default = 'default',
help = ("Specify that the credentials file is encrypted."
" The default behavior is \"True\" if the credentials file is"
" <LOGPATH>/credentials.csv.enc, and \"False\" otherwise."))
parser_restore.add_argument('--logpath', dest = 'logPath', metavar = "PATH",
default = expanduser('~') + sep + ".lbcp",
help = ("Path to the log files. Needs to be the same during the"
" entire lifetime of all the backups on the device."
" Do NOT use this option unless you have REALLY specific needs."
" (default: $HOME/.lbcp)."))
# Encrypt arguments
parser_encrypt = subparsers.add_parser('encrypt',
help = "Initiate local file encryption.")
parser_encrypt.add_argument('PLAINTEXT', help = "Path of the original file.")
parser_encrypt.add_argument('ENCRYPTED', help = "Path to save the encrypted file in.")
# Decrypt arguments
parser_decrypt = subparsers.add_parser('decrypt',
help = "Initiate local file decryption.")
parser_decrypt.add_argument('ENCRYPTED', help = "Path of the encrypted file.")
parser_decrypt.add_argument('PLAINTEXT', help = "Path to save the decrypted file in.")
args = parser.parse_args()
# Getting default values of parameters, and naming them shorter
action = args.action
if action == 'backup' or action == 'restore':
credsFile = args.credsFile
mybucket = args.mybucket
device = args.device
credsEnc = args.credsEnc
logPath = args.logPath
# Use absolute log path
logPath = abspath(logPath)
if credsFile == 'default':
credsFile = logPath + sep + "credentials.csv.enc"
if credsEnc == 'default':
if credsFile == logPath + sep + "credentials.csv.enc":
credsEnc = True
else:
credsEnc = False
# Backup only
if action == 'backup':
mypaths = args.mypaths
excludes = args.excludes
oldlogBucket = args.oldlogBucket
newLoc = args.newLoc
# Restore only
elif action == 'restore':
restoreThis = args.restoreThis
restorePath = args.restorePath
oldlogBucket = '' # Dummy, for general initialization
newLoc = '' # Dummy, for general initialization
# Local encrypt/decrypt
else:
plainFile = args.PLAINTEXT
encFile = args.ENCRYPTED
###################################################################
### Global variables
# Get current time
currentTime = int(datetime.now().strftime("%Y%m%d%H%M%S"))
# Upload parameters (DON'T CHANGE!!!)
maxUploadSize = 16*1024*1024 #Must be dividable by 16, and more than 2**23
chunksize = 64*1024 #Must be dividable by 16
# Max date (DON'T CHANGE!!!)
maxDate = 99999999999999
###################################################################
### Functions
def mod_time(filename):
t = datetime.fromtimestamp(lstat(filename).st_mtime)
return int(t.strftime("%Y%m%d%H%M%S"))
def addSeconds(time, sec):
'''
Add or subtract seconds from int formatted time
'''
time = datetime.strptime(str(time), "%Y%m%d%H%M%S")
time += timedelta(seconds = sec)
return int(time.strftime("%Y%m%d%H%M%S"))
def checksum_file(f, block_size=128*512):
checksum = hashlib.md5()
with open(f, 'rb') as file_to_check:
while True:
data = file_to_check.read(block_size)
if not data:
break
checksum.update(data)
return checksum.hexdigest()
def makeSerials(rawString, byteString):
rawString = str.encode(rawString)
return hashlib.sha256(rawString + byteString).hexdigest()
def sizeof_fmt(num):
for x in [' bytes',' KB',' MB',' GB']:
if num < 1024.0:
return "%3.1f%s" % (num, x)
num /= 1024.0
return "%3.1f%s" % (num, ' TB')
def pBarInitiation(obj, initial = ''):
global widgets
widgets = [ initial,
progressbar.FileTransferSpeed(),
' ', progressbar.Bar(), ' ',
progressbar.Percentage(), ' ',
progressbar.ETA() ]
global pbar
pbar = progressbar.ProgressBar(widgets=widgets,
maxval=sys.getsizeof(obj))
def progress_callback(current, total):
try:
pbar.update(current)
except AssertionError as e:
print e
def intToDate(i):
i = str(i)
return i[:4] + '-' + i[4:6] + '-' + i[6:8] + '_' + \
i[8:10] + ':' + i[10:12] + ':' + i[12:]
def maxDateBeforeLast(listOfArrs, datesArray, lastDate):
'''
Take a list of arrays of indices, and determine which of these indices
corresponds to the latest date in a second array, that is smaller than
the last date.
Returns uniquified, sorted array of such indices.
Assumptions: all dates are greater than zero and all members of
the list of arrays are valid indices in the dates array.
'''
lst = []
for i in listOfArrs:
t = datesArray[i]
t[t > lastDate] = 0
tMax = np.amax(t)
if tMax:
lst.append(i[np.argmax(t)])
return np.unique(np.array(lst))
def fileRestore(path, checksum):
if isfile(path):
if checksum_file(path) == checksum and not islink(path):
print "Same file exists in restore path. Skipping!"
return False
else:
print "A different file with the same name exists in the restore path!"
count = 0
while True:
ns = raw_input("Overwrite? (Y/n) ")
if (ns in ['', 'Y', 'y']) or (count > 4):
print "Overwriting..."
return True
elif ns in ['N', 'n']:
print "Skipping..."
return False
count += 1
else:
return True
def getInitialPasswd(currPass = False):
count = 0
print ("Please choose your new password wisely, and make sure you"
" never forget it\nas long as you need it!!!")
pprompt = lambda: (getpass.getpass(), getpass.getpass("Retype password: "))
if currPass:
p1, p2 = currPass, getpass.getpass("Retype password: ")
else:
p1, p2 = pprompt()
while p1 != p2:
print("Passwords do not match. Please try again")
p1, p2 = pprompt()
if count >= 3:
print "Goodbye!"
sys.exit(1)
count += 1
return p1
def verifyPasswd(b, logPath, act, currPass = False):
'''
Verify or initiate password, provide string for computing serials
'''
try:
k = b.get_key("0_logs/control")
except:
print "No connection to S3. Exiting."
sys.exit(1)
if k:
randStr = k.get_contents_as_string()
salt = randStr[:24]
iv = randStr[24:40]
randStr = randStr[40:]
count = 0
while True:
if currPass and not count:
password = currPass
else:
password = getpass.getpass()
encKey = hashlib.sha256(str.encode(password) + salt).digest()
decryptor = AES.new(encKey, AES.MODE_CBC, iv)
decStr = decryptor.decrypt(randStr)
providedHash = decStr[32:]
calculatedHash = hashlib.sha256(decStr[:32]).digest()
if providedHash == calculatedHash:
break
if count >= 3:
print "Goodbye!"
sys.exit(1)
count += 1
elif listdir(logPath) or len([ f for f in b.list('0_logs')]):
print ("##############################################"
"\nERROR: control log is missing, but other logs exist!"
"\nIf you have the control log which was created during the"
"\nbackup initialization, please restore it manually"
"\n(e.g. via the web interface) to:\n"
+ b.name + "/0_logs."
"\nOtherwise, you have to delete all the contents of the bucket and"
"\nthe local log files manually, and start from scratch!"
"\nONLY RESTORES CAN BE DONE NOW!"
"\n##############################################")
if act == 'restore':
if currPass:
password = currPass
else:
password = getpass.getpass()
providedHash = b'0'
else:
sys.exit(1)
else:
print "Welcome to the new backup!"
salt = urandom(24)
randStr = urandom(32)
password = getInitialPasswd(currPass)
encKey = hashlib.sha256(str.encode(password) + salt).digest()
providedHash = hashlib.sha256(randStr).digest()
randStr = randStr + providedHash
iv = urandom(16)
encryptor = AES.new(encKey, AES.MODE_CBC, iv)
randStr = encryptor.encrypt(randStr)
randStr = salt + iv + randStr
k = Key(b)
k.key = "0_logs/control"
k.set_contents_from_string(randStr)
# Download new control log
k.get_contents_to_filename(logPath + sep + 'control')
print ("The newly created control log was saved to " + logPath + sep + "control."
"\nIt should never change as long as you keep this backup, and is very important."
"\nYou might want to put it in a safe place. It is automatically uploaded to S3,"
"\nso backing it up there is NOT needed.")
raw_input("Press any key to continue...")
return password, providedHash
def connBucket(c, b, loc, act):
'''
Connect to S3 bucket
'''
try:
bucket = c.get_bucket(b)
except S3ResponseError as e:
if act != 'backup':
print "Bucket " + b + " does not exist or is not accessible. Exiting."
sys.exit(1)
elif e.error_code == 'NoSuchBucket':
print "Bucket " + b + " does not exist. Create it?"
count = 0
while True:
cr = raw_input("(Y/n)? ")
if cr in ['', 'Y', 'y']:
try:
bucket = c.create_bucket(b, location = getattr(Location, loc))
print "Bucket " + b + " created in location \"" + loc + "\"."
break
except S3CreateError as e:
if e.error_code == 'BucketAlreadyExists':
print "Bucket name taken. Please choose another."
sys.exit(1)
else:
raise e
elif (cr in ['N', 'n']) or (count > 3):
print "Goodbye!"
sys.exit(1)
count += 1
elif e.error_code == 'AccessDenied':
print ("You do not have access to bucket " + b +
". Please choose another.")
sys.exit(1)
else:
print "No connection to S3. Exiting."
sys.exit(1)
return bucket
def getRemoteLog(remoteLogName, bucket, dev, logPath, logName, password):
try:
remoteLog = bucket.get_key(remoteLogName)
except:
print "No connection to S3. Exiting."
sys.exit(1)
logFile = logPath + sep + logName
if remoteLog:
print "Remote log for device " + dev + " found."
count = 0
while True:
dl = raw_input("Download and use it? (Y/n) ")
if dl in ['', 'Y', 'y']:
downDecUnzipCopy(remoteLogName, logPath + sep, '0', [logName],
bucket, password)
return logFile, remoteLogName
elif (dl in ['N', 'n']) or (count > 3):
print "No log file. Exiting."
sys.exit(1)
count += 1
else:
print "Remote log for device " + dev + " not found. Exiting."
sys.exit(1)
#def ifRestore(remoteLogName, bucket, dev, logPath, logName, password):
# logFile, remoteLogName = getRemoteLog(remoteLogName, bucket, dev,
# logPath, logName, password)
# if not logFile:
# print "ERROR: restore action needs log file!"
# sys.exit(1)
# else:
# return logFile, remoteLogName
def getLogFile(dev, devList, logPath, bucket, password):
logName = "lbcp_" + dev + ".log"
logFile = logPath + sep + logName
remoteLogName = "0_logs/" + logName
if isfile(logFile) or (dev not in devList):
# if logfile exists, or we are starting a new backup
return logFile, remoteLogName
else:
count = 0
while True:
getRemote = raw_input("Local log file not found, try to"
" search for remote? (Y/n) ")
if getRemote in ['', 'Y', 'y']:
return getRemoteLog(remoteLogName, bucket, dev, logPath,
logName, password)
elif (getRemote in ['N', 'n']) or (count > 3):
print "No log file. Exiting."
sys.exit(1)
count += 1
def verifyBucket(bucket, internal = False):
if (not re.match('^[a-z0-9][a-z0-9-]+[a-z0-9]$', bucket) or
len(bucket) < 3 or len(bucket) > 63):
print ("Invalid bucket name: " + bucket + "."
"\nName may contain lowercase alphanumeric characters only, and hyphens."
"\nIt must also contain between 3 and 63 characters.")
if internal:
return False
else:
sys.exit(1)
else:
return True
def verifyDevice(dev, internal = False):
if not re.match('^[a-z0-9_-]+$', dev) or len(dev) > 16:
print ("Invalid device name."
"\nDevice name may contain lowercase alphanumeric characters, hyphens"
"\nand underscores only, and must be less than 16 characters long.")
if internal:
return False
else:
sys.exit(1)
else:
return True
def listDevs(bucket, quiet = False):
devList = [ str(k.name[12:-4]) for k in bucket.list('0_logs/lbcp_')]
if not quiet:
if len(devList):
print "Existing devices in bucket " + bucket.name + ":"
count = 1
for s in devList:
print str(count) + ") " + s
count += 1
else:
print "No devices found in bucket " + bucket.name + "."
return devList
def zipEnc(archivepath, filepath, password, inMem = False):
'''
Local encryption
'''
salt = urandom(24)
encKey = hashlib.sha256(str.encode(password) + salt).digest()
iv = urandom(16)
encryptor = AES.new(encKey, AES.MODE_CBC, iv)
filesize = getsize(filepath)
queue = b''
compressor = compressobj(9)
with open(filepath, 'rb') as file:
if inMem:
archive = io.BytesIO()
else:
archive = open(archivepath, 'wb')
archive.write(struct.pack('<Q', filesize))
archive.write(salt)
archive.write(iv)
while True:
data = file.read(chunksize)
if not data:
break
data = compressor.compress(data)
queue += data
if len(queue) < chunksize:
continue
data = encryptor.encrypt(queue[:chunksize])
queue = queue[chunksize:]
archive.write(data)
queue += compressor.flush()
if queue:
queue += b'+' * (16 - len(queue) % 16)
queue = encryptor.encrypt(queue)
archive.write(queue)
if inMem:
return archive
else:
archive.close()
def decUnzip(archivepath, filepath, password, inMem = False):
'''
Local decryption
'''
with open(archivepath, 'rb') as archive:
origsize = struct.unpack('<Q', archive.read(struct.calcsize('Q')))[0]
salt = archive.read(24)
iv = archive.read(16)
encKey = hashlib.sha256(str.encode(password) + salt).digest()
decryptor = AES.new(encKey, AES.MODE_CBC, iv)
decompressor = decompressobj()
if inMem:
f = io.BytesIO()
else:
f = open(filepath, 'wb')
while True:
data = archive.read(chunksize)
if not data:
break
data = decryptor.decrypt(data)
try:
data = decompressor.decompress(data)
except:
print "Data corrupted! Are you sure the password is correct?"
if not inMem:
f.close()
remove(filepath)
sys.exit(1)
f.write(data)
data = decompressor.flush()
f.write(data)
f.truncate(origsize)
if inMem:
return f
else:
f.close()
def devGivenNotDetected(action, dev, devList, bucket, devLogFile, logPath, password):
'''
Manages log file and device log in the case that the device is
specified by the user, but not detected locally.
'''
if action == 'backup':
selfDev = True
inDevLog = np.array([dev, bucket.name]).reshape(1,2)
logFile, remoteLogName = getLogFile(dev, devList, logPath,
bucket, password)
# Write new device log
np.savetxt(devLogFile, inDevLog, fmt='%s',
delimiter=',', header='This device,Bucket')
elif action == 'restore':
selfDev = False
logName = "lbcp_" + dev + ".log"
remoteLogName = "0_logs/" + logName
logFile, remoteLogName = getRemoteLog(remoteLogName, bucket, dev,
logPath, logName, password)
return logFile, remoteLogName, selfDev
def devGivenAndDetected(action, dev, detectedDev, devList,
bucket, logPath, password):
if detectedDev == dev:
selfDev = True
logFile, remoteLogName = getLogFile(dev, devList, logPath,
bucket, password)
elif action == 'restore':
selfDev = False
logName = "lbcp_" + dev + ".log"
remoteLogName = "0_logs/" + logName
logFile, remoteLogName = getRemoteLog(remoteLogName, bucket, dev,
logPath, logName, password)
else:
print ("Specified device (" + dev + ") doesn't match detected ("
+ detectedDev + ")"
"\nand you want to upload! Please try again.")
sys.exit(1)
return logFile, remoteLogName, selfDev
def initiate(dev, action, logPath, bucket, oldlogBucket, credsFile, loc):
# Check if this physical device is backed up as a single device
localDevs = [ f[10:-4] for f in listdir(logPath)
if f.startswith('local_dev') ]
if len(localDevs) == 1 and not dev:
devLogFile = logPath + sep + "local_dev_" + localDevs[0] + ".log"
else:
try:
# Try, because dev might not be a string, but "False"
devLogFile = logPath + sep + "local_dev_" + dev + ".log"
except:
pass
try:
devLog = np.loadtxt(devLogFile, dtype = 'str', delimiter = ',')
detectedDev = devLog[0]
detectedBucket = devLog[1]
except:
detectedDev = False
detectedBucket = False
# Get correct bucket
if bucket:
verifyBucket(bucket)
if not bucket and not detectedBucket:
print "No S3 bucket specified nor detected."
count = 0
while True:
if count > 5:
print "Too many trys, goodbye!"
sys.exit(1)
count += 1
bucket = raw_input("Please specify bucket: ")
if not verifyBucket(bucket, internal = True):
continue
cont = raw_input("Got bucket: " + bucket + ". Continue? (Y/n) ")
if cont in ['', 'Y', 'y']:
break
elif cont in ['N', 'n']:
continue
elif detectedBucket and not bucket:
bucket = detectedBucket
elif bucket and detectedBucket and (bucket != detectedBucket):
if action == 'backup':
print "You can not continue existing backup to a different bucket!"
sys.exit(1)
elif action == 'restore':
print ("WARNING: You are restoring from a different bucket than this"
"\ndevice is backed up to!")
raw_input("Press any key to continue, ctrl+C to quit.")
# Get correct credentials file, and encrypt if new.
#if not access(credsFile, R_OK):
# print "Credentials file not accessible. Please specify another."
# sys.exit(1) #TODO delete this check if really unnecessary
if not credsEnc:
print "Reading initial S3 credentials file."
try:
S3creds = np.loadtxt(credsFile, dtype = 'str', delimiter = ',',
skiprows = 1, usecols = (1, 2))
except:
print "Credentials file can not be read. Exiting."
sys.exit(1)
conn = S3Connection(S3creds[0], S3creds[1])
bucket = connBucket(conn, bucket, loc, action)
password, hashStr = verifyPasswd(bucket, logPath, action)
print ("The credentials file was read, but it exists unencrypted on"
"\nyour computer. Would you like to encrypt it?")
count = 0
while True:
toEnc = raw_input("(Y/n)? ")
if toEnc in ['', 'Y', 'y']:
zipEnc(logPath + sep + "credentials.csv.enc",
credsFile, password)
print ("##############################################"
"\nCredentials file encrypted. The encrypted file is saved to:\n"
+ logPath + sep + "credentials.csv.enc"
"\n...and is the same for all devices."
"\n##############################################")
if access(credsFile, W_OK):
cnt = 0
while True:
print ("It is advised to delete the plaintext"
" file for better security."
"\n(Original can be restored by decryption, or"
" by downloading from the S3 web interface)")
toDel = raw_input("Delete plaintext credentials? (Y/n) ")
if toDel in ['', 'Y', 'y']:
remove(credsFile)
break
elif (toDel in ['N', 'n']) or (cnt > 3):
break
cnt += 1
break
elif (toEnc in ['N', 'n']) or (count > 3):
break
count += 1
# If credentials file encrypted
else:
if not isfile(credsFile):
print "Credentials file not found! Exiting."
sys.exit(1)
print "Reading S3 encrypted credentials file."
password = getpass.getpass()
try:
credsFile = decUnzip(credsFile, '', password, inMem = True)
credsFile = io.StringIO(credsFile.getvalue().decode('UTF-8'))
S3creds = np.loadtxt(credsFile, dtype = 'str', delimiter = ',',
skiprows = 1, usecols = (1, 2))
except:
print "Credentials file can not be read. Exiting."
sys.exit(1)
conn = S3Connection(S3creds[0], S3creds[1])
bucket = connBucket(conn, bucket, loc, action)
password, hashStr = verifyPasswd(bucket, logPath, action, currPass = password)
# Connect to log bacup bucket
if action == 'backup':
if oldlogBucket == 'default':
oldlogBucket = bucket.name + '-oldlogs'
count = 0
while not verifyBucket(oldlogBucket, internal = True):
count += 1
print ("Old logs' storage bucket may be the same or"
" different than the main backup bucket!")
oldlogBucket = raw_input("Please specify bucket FOR"
" STORING OLD LOGS: ")
if count > 5:
print "Too many trys, goodbye!"
sys.exit(1)
if bucket.name == oldlogBucket:
oldlogBucket = bucket
else:
oldlogBucket = connBucket(conn, oldlogBucket, loc, action)
else:
oldlogBucket = False
# Logfile and device management
if dev:
verifyDevice(dev)
devList = listDevs(bucket, quiet = True)
if detectedDev:
logFile, remoteLogName, selfDev = devGivenAndDetected(action, dev,
detectedDev,
devList, bucket,
logPath, password)
else:
logFile, remoteLogName, selfDev = devGivenNotDetected(action, dev,
devList,
bucket,
devLogFile,
logPath,
password)
elif detectedDev:
selfDev = True
devList = listDevs(bucket, quiet = True)
logFile, remoteLogName = getLogFile(detectedDev, devList, logPath,
bucket, password)
else:
print ("No device specified nor detected."
"\nPlease wait for a list of available devices...")
devList = listDevs(bucket)
# Ask to specify a device manually
count = 0
while True:
if count > 5:
print "Too many trys, goodbye!"
sys.exit(1)
count += 1
if devList:
dev = raw_input("Please specify a device (new, or "
"a number from the list above): ")
try:
if int(dev) in range(len(devList) + 1)[1:]:
dev = devList[int(dev) - 1]
except:
pass
else:
dev = raw_input("Please specify a device: ")
if not verifyDevice(dev, internal = True):
continue
cont = raw_input("Got device: " + dev + ". Continue? (Y/n) ")
if cont in ['', 'Y', 'y']:
break
elif cont in ['N', 'n']:
continue
devLogFile = logPath + sep + "local_dev_" + dev + ".log"
if dev in localDevs:
detectedBucket = np.loadtxt(devLogFile, dtype = 'str',
delimiter = ',')[1]
if bucket.name != detectedBucket:
print ("Specified bucket (" + bucket.name + ") is not the same that"
"\nthis device is backed up in (" + detectedBucket +"). Exiting.")
sys.exit(1)
selfDev = True
logFile, remoteLogName = getLogFile(dev, devList, logPath,
bucket, password)
else:
logFile, remoteLogName, selfDev = devGivenNotDetected(action, dev,
devList,
bucket,
devLogFile,
logPath,
password)
return (conn, bucket, oldlogBucket, password, hashStr,
logFile, remoteLogName, selfDev)
def zipEncUp(filepath, serial, bucket, password):
'''
Main upload
'''
try:
filesize = getsize(filepath) #check filesize independantly of list
except:
print "No such file." # Case of interrupted backup, and file's gone.
return
print "Uploading " + filepath + " (" + sizeof_fmt(filesize) + ")..."
try:
k = bucket.get_key(str(serial))
except:
print ("No connection to S3. Exiting. Please complete the "
"upload another time.")
sys.exit(1)
if k:
print "Already exists, moving on..."
return
salt = urandom(24)
encKey = hashlib.sha256(str.encode(password) + salt).digest()
iv = urandom(16)
encryptor = AES.new(encKey, AES.MODE_CBC, iv)
queue = b''
compressor = compressobj(9)
k = Key(bucket)
k.key = str(serial)
multipartCount = 1
with open(filepath, 'rb') as file:
upload = io.BytesIO()
upload.write(struct.pack('<Q', filesize))
upload.write(salt)
upload.write(iv)
while True:
data = file.read(chunksize)
if not data:
break
data = compressor.compress(data)
queue += data
if len(queue) < chunksize:
continue
data = encryptor.encrypt(queue[:chunksize])
upload.write(data)
if sys.getsizeof(upload) >= maxUploadSize:
if multipartCount == 1:
mpu = bucket.initiate_multipart_upload(k.key)
upload.seek(0)
pBarInitiation(upload, "Part: " + str(multipartCount) +
" of ~" +
str(int(ceil(float(filesize)/maxUploadSize))) +
" (" + sizeof_fmt(maxUploadSize) + ") @")
pbar.start()
mpu.upload_part_from_file(upload, multipartCount,
cb=progress_callback,
num_cb=100)
pbar.finish()
upload.seek(0)
upload.truncate()
multipartCount += 1
queue = queue[chunksize:]
queue += compressor.flush() #write everything that's left
if queue:
queue += b'+' * (16 - len(queue) % 16)
queue = encryptor.encrypt(queue)
upload.write(queue)