-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtarzan.py
1698 lines (1376 loc) · 57.6 KB
/
tarzan.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 python
#
# Support functions for tarzan.
__author__ = 'Sean Reifschneider <[email protected]>'
__version__ = 'X.XX'
__copyright__ = (
'Copyright (C) 2013, 2014, 2015 Sean Reifschneider, RealGo, Inc.')
__license__ = 'GPLv2'
import os
import sys
from Crypto import __version__ as Crypto_version
from Crypto import Random
from Crypto.Hash import SHA512, HMAC
from Crypto.Cipher import AES
from Crypto.Protocol.KDF import PBKDF2
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
import struct
import zlib
import json
import bsddb
import uuid
import argparse
import ConfigParser
import collections
import logging
import logging.handlers
try:
from distutils.version import LooseVersion
except ImportError:
print (
'WARNING: Unable to check Crypto library version. '
'Install distutils.')
else:
if LooseVersion(Crypto_version) < LooseVersion('2.6.1'):
print (
'WARNING: Python Crypto should be 2.6.1 or higher.'
' CVE-2013-1445')
import tarfp
rsa_key_length = 3072
aes_key_length = 16 # RSA of 3072 matches AES of 128
default_blocks_size = 30000
default_brick_size_max = 30 * 1000 * 1000
# loggers
debug = logging.getLogger(__name__ + '.debug')
debug.addHandler(logging.NullHandler())
log = logging.getLogger(__name__)
log.addHandler(logging.NullHandler())
verbose = logging.getLogger(__name__ + '.verbose')
verbose.addHandler(logging.NullHandler())
class InvalidTarzanInputError(Exception):
'''General error with encrypted input.
'''
pass
# for python3 compatibility, even though tarzan isn't
if hasattr(__builtins__, 'FileExistsError'):
FileExistsError = __builtins__.FileExistsError
else:
class FileExistsError(IOError):
pass
def hashkey_to_hex(s):
len_length = struct.calcsize('!L')
return '{0}:{1}'.format(
''.join(['{0:0>2x}'.format(ord(x)) for x in s[:-len_length]]),
struct.unpack('!L', s[-len_length:])[0])
def short_hashkey_to_hex(s):
s = hashkey_to_hex(s)
return '{0}..{1}'.format(s[:9], s[119:])
def make_seq_filename(sequence_id):
'''Convert the sequence ID into a directory+file-name.
The returned value is a directory joined to a file, name using
`os.path.join()`. The top level directory will have around 1296 entries
in it, and files under it start off with a 1-byte filename, expanding
to 2 when `sequence_id` is more than 1296, and 3 when`sequence_id`
is more than 46656, etc...
:param sequence_id: The numeric sequence identifier of the brick.
:type sequence_id: int
'''
keyspace = '0123456789abcdefghijklmnopqrstuvwxyz'
top_level_count = len(keyspace) ** 2
def get_key(keyspace, n):
nl = len(keyspace)
first_loop = True
s = ''
while n or first_loop:
s = keyspace[n % nl] + s
n = int(n / nl)
first_loop = False
return s
top_level_name = get_key(keyspace, sequence_id % top_level_count)
filename = get_key(keyspace, int(sequence_id / top_level_count))
return os.path.join(top_level_name, filename)
BrickFileInfo = collections.namedtuple(
'BrickFileInfo', ['directory', 'brick', 'toc'])
class SequentialIV:
'''An IV that can be incremented sequentially.
This is used in the Tarzan tar headers to prevent re-use of the IV for
each file, but allow encrypting each file data-block separately.
'''
def __init__(self):
self.base_iv = Random.new().read(16)
self.sequence = 0
def get_next_iv(self):
next_value = struct.unpack('!Q', self.base_iv[-8:])[0] + self.sequence
if next_value >= 1 << 64:
next_value -= 1 << 64
self.sequence += 1
return self.base_iv[:-8] + struct.pack('!Q', next_value)
class BlockStorageDirectory:
'''A block storage class that writes blocks to a directory.
NOTE: This is not multi-process or multi-thread safe currently.
'''
def __init__(
self, path, password,
blocks_size=default_blocks_size,
brick_size_max=default_brick_size_max):
'''Create a block storage instance.
:param path: Directory of block storage.
:type path: str
:param password: Encryption key.
:type password: str
:param blocks_size: Size of blocks in the storage. Partial blocks
may be smaller. Defaults to `default_blocks_size.
:type blocks_size: int
:param brick_size_max: Size of the block storage files
("bricks"). The bricks will be split when they exceed this
size. Defaults to `default_brick_size_max`.
:type brick_size_max: int
'''
self.path = path
self.aes_key = PBKDF2(password, '', 32)
self.blocks_map = None
self.blocks_size = blocks_size
self.brick_size_max = brick_size_max
self._reset_brick()
if not os.path.exists(path):
os.mkdir(path)
self.next_brick = 0
self.uuid = str(uuid.uuid1())
if len(self.uuid) != 36:
raise ValueError(
'Expected 36 bytes of UUID, got %d' % len(self.uuid))
self.save()
else:
self.load()
self._open_blocks_map()
def _reset_brick(self):
'''Internal: Resets objects related to the blocks file.
'''
self.brick_file = None
self.toc_file = None
self.brick_size = None
def save(self):
'''Save the block storage status.
This should be called regularly when the status of the block
storage changes (new bricks created).
'''
filename = os.path.join(self.path, 'info')
tmp_filename = filename + '.tmp'
with open(tmp_filename, 'w') as fp:
json.dump(
{
'format_version': 1,
'next_brick': self.next_brick,
'uuid': self.uuid,
}, fp)
os.rename(tmp_filename, filename)
if self.brick_file:
self.brick_file.flush()
if self.toc_file:
self.toc_file.flush()
if self.blocks_map:
self.blocks_map.sync()
def load(self):
'''Load block storage information from disc.
This loads the status from the block storage files and makes it
ready for use.
'''
filename = os.path.join(self.path, 'info')
with open(filename, 'r') as fp:
data = json.load(fp)
if data['format_version'] != 1:
raise ValueError(
'Unsupported format "%s"' % data['format_version'])
self.format_version = data['format_version']
self.uuid = data['uuid']
self.next_brick = data['next_brick']
self._open_blocks_map()
def _open_blocks_map(self):
'''INTERNAL: Open the blocks map file.'''
if self.blocks_map is None:
filename = os.path.join(self.path, 'blocks_map')
self.blocks_map = bsddb.hashopen(filename, 'c')
def have_active_brick(self):
'''Do we have an active brick?
:returns: boolean -- Returns `True` if there is a brick open for
writing.
'''
return self.brick_file is not None
def gen_hashkey(self, block, hmac_digest):
'''Generate the hashkey for the specified block.
A hashkey is the unique identifier for a block. It consists of the
64-byte binary SHA512 of the block data, followed by 4 bytes
representing the block size, encoded in network format.
:param block: The block to hash.
:type block: str
:param hmac_digest: HMAC digest to mix into hash.
:type hmac_digest: str
:returns: str -- The hashkey associated with this block data.
'''
hash = SHA512.new()
hash.update(block)
hash.update(hmac_digest)
return hash.digest() + struct.pack('!L', len(block))
hashkey_length = 64 + struct.calcsize('!L')
def get_brick_file(self, sequence_id):
'''Format the paths of brick components.
Given a sequene, this returns a namedtuple that identifies the brick
with these attributes (in tuple order):
- directory -- The location of the directory the brick is in.
- brick -- Full path of the brick file.
- toc -- Full path of the TOC file.
:param sequence_id: The numeric sequence identifier of the brick.
:type sequence_id: int
:returns: :py:class:`BrickFileInfo` -- Namedtuple of brick paths.
'''
brick_info = os.path.split(make_seq_filename(sequence_id))
brick_directory = os.path.join(self.path, 'b-' + brick_info[0])
if not os.path.exists(brick_directory):
os.mkdir(brick_directory)
brick_filename = os.path.join(
brick_directory, 'dt_d-%s-%s' % brick_info)
toc_filename = os.path.join(
brick_directory, 'dt_t-%s-%s' % brick_info)
return BrickFileInfo(brick_directory, brick_filename, toc_filename)
def encode_block(self, block, hashkey, hmac):
'''Given a block, encode it in the block-file format.
This takes a block, potentially compresses it, encrypts it, and
creates a block header for storage in the brick.
Header format:
block magic number ("dt1z" for compressed+AWS or "dt1n" for
just AES)
payload length (4 bytes encoded network-format)
decoded length (4 bytes encoded network-format)
hashkey (64 bytes SHA512 hash of block and HMAC,
4 bytes raw length)
hmac (64 bytes SHA512 data signature)
crypto IV: 16 random bytes
Payload format:
block: Encrypted and possibly encoded
:param block: The block of data.
:type block: str
:param hashkey: The hashkey of the data block.
:type hashkey: str
:returns: (str,str) -- A tuple of the block header and payload data.
'''
decoded_length = len(block)
block_magic = 'dt1n'
compressed_block = zlib.compress(block)
if len(compressed_block) < len(block):
block = compressed_block
block_magic = 'dt1z'
crypto_iv = Random.new().read(16)
crypto = AES.new(self.aes_key, AES.MODE_CBC, crypto_iv)
padding_remainder = len(block) % 16
if padding_remainder != 0:
block += Random.new().read(16 - padding_remainder)
block = crypto.encrypt(block)
header = (
block_magic + struct.pack('!L', len(block)) +
struct.pack('!L', decoded_length) + hashkey
+ hmac + crypto_iv)
return header, block
def new_brick(self):
'''Get a new brick for writing to.
This closes the existing brick, if any, and opens a new one for
writing to.
'''
self.close_brick()
self.current_brick = self.next_brick
self.next_brick += 1
self.save()
brick_info = self.get_brick_file(self.current_brick)
self.brick_file = open(brick_info.brick, 'a')
self.toc_file = open(brick_info.toc, 'a')
self.brick_size = 0
debug.error(
'Opening new brick: %s', os.path.basename(brick_info.brick))
def close_brick(self):
'''Close a brick and finalize it.
Called when done with writing blocks to a brick.
'''
self.save()
if self.brick_file:
debug.warning('Finalizing brick')
self.brick_file.close()
if self.toc_file:
self.toc_file.close()
self._reset_brick()
def store_block(self, block, hashkey=None, hmac_digest=None):
'''Store the given block in the current brick.
If the block has already been stored to the BlockStorage, it is not
written again.
:param block: The data to store in the brick.
:type block: str
:param hashkey: (None) If specified, the hashkey for the block.
If not specified, the hashkey is generated internally.
:type hashkey: str
:param hmac_digest: (None) If specified, the hmac_digest for the block.
If not specified, the hashkey is generated internally.
:type hmac_digest: str
'''
if hmac_digest is None:
mac512 = HMAC.new(self.aes_key, digestmod=SHA512)
mac512.update(block)
hmac_digest = mac512.digest()
if hashkey is None:
hashkey = self.gen_hashkey(block, hmac_digest)
header, payload = self.encode_block(block, hashkey, hmac_digest)
if hashkey in self.blocks_map:
debug.error(
'Duplicate block found: %s', short_hashkey_to_hex(hashkey))
return
if not self.have_active_brick() or (
self.brick_size and self.brick_size > self.brick_size_max):
self.new_brick()
self.blocks_map[hashkey] = '%d,%d' % (
self.current_brick, self.brick_size)
debug.warning('Storing block {0} to {1} at {2}'.format(
short_hashkey_to_hex(hashkey), self.current_brick,
self.brick_file.tell()))
self.toc_file.write(hashkey + struct.pack('!L', self.brick_size))
self.brick_file.write(header)
debug.info('Header: %s', repr(header))
self.brick_file.write(payload)
debug.info('Payload: %s', repr(payload[:32]))
self.brick_size += len(header) + len(payload)
def retrieve_block(self, hashkey):
'''Grab a block from storage.
:param hashkey: (None) If specified, the hashkey for the block.
:type hashkey: str
:returns: str -- Block payload.
'''
location = self.blocks_map[hashkey]
brick_id, offset = map(int, location.split(','))
brick_info = self.get_brick_file(brick_id)
with open(brick_info.brick, 'rb') as fp:
debug.warning('Retrieving block {0} from {1} offset {2}'.format(
short_hashkey_to_hex(hashkey), brick_id, offset))
fp.seek(offset)
header = fp.read(4 + 4 + 4 + 68 + 64 + 16)
debug.info('Header: %s', repr(header))
header_magic = header[:4]
header_payload_length = struct.unpack('!L', header[4:8])[0]
header_decoded_length = struct.unpack('!L', header[8:12])[0]
header_hashkey = header[12:80]
header_hmac = header[80:144]
header_crypto_iv = header[144:]
if header_magic not in ['dt1z', 'dt1n']:
raise ValueError('Invalid hashkey in read block')
if hashkey != header_hashkey:
raise ValueError('Hash key in block does not match expected.')
payload = fp.read(header_payload_length)
debug.info('Payload: %s', repr(payload[:32]))
payload = decode_payload(
payload, self.aes_key,
header_crypto_iv, header_hmac, header_magic,
header_decoded_length)
return payload
class BlockStorageDirectoryNoBrick:
'''A block storage class that writes blocks to a directory.
This version does not store files in bricks, it uses the block
hash to just write individual files. This is largely for testing
of an S3 back-end.
NOTE: This is not multi-process or multi-thread safe currently.
'''
def __init__(
self, path, password,
blocks_size=default_blocks_size,
brick_size_max=default_brick_size_max):
'''Create a block storage instance.
:param path: Directory of block storage.
:type path: str
:param password: Encryption key.
:type password: str
:param blocks_size: Size of blocks in the storage. Partial blocks
may be smaller. Defaults to `default_blocks_size.
:type blocks_size: int
:param brick_size_max: Size of the block storage files
("bricks"). The bricks will be split when they exceed this
size. Defaults to `default_brick_size_max`.
:type brick_size_max: int
'''
self.path = path
self.aes_key = PBKDF2(password, '', 32)
self.blocks_map = None
self.blocks_size = blocks_size
self.brick_size_max = brick_size_max
self._reset_brick()
if not os.path.exists(path):
os.mkdir(path)
self.next_brick = 0
self.uuid = str(uuid.uuid1())
if len(self.uuid) != 36:
raise ValueError(
'Expected 36 bytes of UUID, got %d' % len(self.uuid))
self.save()
else:
self.load()
self._open_blocks_map()
def _reset_brick(self):
'''Internal: Resets objects related to the blocks file.
'''
self.brick_file = None
self.toc_file = None
self.brick_size = None
def save(self):
'''Save the block storage status.
This should be called regularly when the status of the block
storage changes (new bricks created).
'''
filename = os.path.join(self.path, 'info')
tmp_filename = filename + '.tmp'
with open(tmp_filename, 'w') as fp:
json.dump(
{
'format_version': 1,
'next_brick': self.next_brick,
'uuid': self.uuid,
}, fp)
os.rename(tmp_filename, filename)
if self.brick_file:
self.brick_file.flush()
if self.toc_file:
self.toc_file.flush()
if self.blocks_map:
self.blocks_map.sync()
def load(self):
'''Load block storage information from disc.
This loads the status from the block storage files and makes it
ready for use.
'''
filename = os.path.join(self.path, 'info')
with open(filename, 'r') as fp:
data = json.load(fp)
if data['format_version'] != 1:
raise ValueError(
'Unsupported format "%s"' % data['format_version'])
self.format_version = data['format_version']
self.uuid = data['uuid']
self.next_brick = data['next_brick']
self._open_blocks_map()
def _open_blocks_map(self):
'''INTERNAL: Open the blocks map file.'''
if self.blocks_map is None:
filename = os.path.join(self.path, 'blocks_map')
self.blocks_map = bsddb.hashopen(filename, 'c')
def have_active_brick(self):
'''Do we have an active brick?
:returns: boolean -- Returns `True` if there is a brick open for
writing.
'''
return self.brick_file is not None
def gen_hashkey(self, block, hmac_digest):
'''Generate the hashkey for the specified block.
A hashkey is the unique identifier for a block. It consists of the
64-byte binary SHA512 of the block data, followed by 4 bytes
representing the block size, encoded in network format.
:param block: The block to hash.
:type block: str
:param hmac_digest: HMAC digest to mix into hash.
:type hmac_digest: str
:returns: str -- The hashkey associated with this block data.
'''
hash = SHA512.new()
hash.update(block)
hash.update(hmac_digest)
return hash.digest() + struct.pack('!L', len(block))
hashkey_length = 64 + struct.calcsize('!L')
def get_brick_file(self, sequence_id):
'''Format the paths of brick components.
Given a sequene, this returns a namedtuple that identifies the brick
with these attributes (in tuple order):
- directory -- The location of the directory the brick is in.
- brick -- Full path of the brick file.
- toc -- Full path of the TOC file.
:param sequence_id: The numeric sequence identifier of the brick.
:type sequence_id: int
:returns: :py:class:`BrickFileInfo` -- Namedtuple of brick paths.
'''
brick_info = os.path.split(make_seq_filename(sequence_id))
brick_directory = os.path.join(self.path, 'b-' + brick_info[0])
if not os.path.exists(brick_directory):
os.mkdir(brick_directory)
brick_filename = os.path.join(
brick_directory, 'dt_d-%s-%s' % brick_info)
toc_filename = os.path.join(
brick_directory, 'dt_t-%s-%s' % brick_info)
return BrickFileInfo(brick_directory, brick_filename, toc_filename)
def encode_block(self, block, hashkey, hmac):
'''Given a block, encode it in the block-file format.
This takes a block, potentially compresses it, encrypts it, and
creates a block header for storage in the brick.
Header format:
block magic number ("dt1z" for compressed+AWS or "dt1n" for
just AES)
payload length (4 bytes encoded network-format)
decoded length (4 bytes encoded network-format)
hashkey (64 bytes SHA512 hash of block and HMAC,
4 bytes raw length)
hmac (64 bytes SHA512 data signature)
crypto IV: 16 random bytes
Payload format:
block: Encrypted and possibly encoded
:param block: The block of data.
:type block: str
:param hashkey: The hashkey of the data block.
:type hashkey: str
:returns: (str,str) -- A tuple of the block header and payload data.
'''
decoded_length = len(block)
block_magic = 'dt1n'
compressed_block = zlib.compress(block)
if len(compressed_block) < len(block):
block = compressed_block
block_magic = 'dt1z'
crypto_iv = Random.new().read(16)
crypto = AES.new(self.aes_key, AES.MODE_CBC, crypto_iv)
padding_remainder = len(block) % 16
if padding_remainder != 0:
block += Random.new().read(16 - padding_remainder)
block = crypto.encrypt(block)
header = (
block_magic + struct.pack('!L', len(block)) +
struct.pack('!L', decoded_length) + hashkey
+ hmac + crypto_iv)
return header, block
def new_brick(self):
'''Get a new brick for writing to.
This closes the existing brick, if any, and opens a new one for
writing to.
'''
self.close_brick()
self.current_brick = self.next_brick
self.next_brick += 1
self.save()
brick_info = self.get_brick_file(self.current_brick)
self.brick_file = open(brick_info.brick, 'a')
self.toc_file = open(brick_info.toc, 'a')
self.brick_size = 0
debug.error(
'Opening new brick: %s', os.path.basename(brick_info.brick))
def close_brick(self):
'''Close a brick and finalize it.
Called when done with writing blocks to a brick.
'''
self.save()
if self.brick_file:
debug.warning('Finalizing brick')
self.brick_file.close()
if self.toc_file:
self.toc_file.close()
self._reset_brick()
def store_block(self, block, hashkey=None, hmac_digest=None):
'''Store the given block in the current brick.
If the block has already been stored to the BlockStorage, it is not
written again.
:param block: The data to store in the brick.
:type block: str
:param hashkey: (None) If specified, the hashkey for the block.
If not specified, the hashkey is generated internally.
:type hashkey: str
:param hmac_digest: (None) If specified, the hmac_digest for the block.
If not specified, the hashkey is generated internally.
:type hmac_digest: str
'''
if hmac_digest is None:
mac512 = HMAC.new(self.aes_key, digestmod=SHA512)
mac512.update(block)
hmac_digest = mac512.digest()
if hashkey is None:
hashkey = self.gen_hashkey(block, hmac_digest)
header, payload = self.encode_block(block, hashkey, hmac_digest)
if hashkey in self.blocks_map:
debug.error(
'Duplicate block found: %s', short_hashkey_to_hex(hashkey))
return
if not self.have_active_brick() or (
self.brick_size and self.brick_size > self.brick_size_max):
self.new_brick()
self.blocks_map[hashkey] = '%d,%d' % (
self.current_brick, self.brick_size)
debug.warning('Storing block {0} to {1} at {2}'.format(
short_hashkey_to_hex(hashkey), self.current_brick,
self.brick_file.tell()))
self.toc_file.write(hashkey + struct.pack('!L', self.brick_size))
self.brick_file.write(header)
debug.info('Header: %s', repr(header))
self.brick_file.write(payload)
debug.info('Payload: %s', repr(payload[:32]))
self.brick_size += len(header) + len(payload)
def retrieve_block(self, hashkey):
'''Grab a block from storage.
:param hashkey: (None) If specified, the hashkey for the block.
:type hashkey: str
:returns: str -- Block payload.
'''
location = self.blocks_map[hashkey]
brick_id, offset = map(int, location.split(','))
brick_info = self.get_brick_file(brick_id)
with open(brick_info.brick, 'rb') as fp:
debug.warning('Retrieving block {0} from {1} offset {2}'.format(
short_hashkey_to_hex(hashkey), brick_id, offset))
fp.seek(offset)
header = fp.read(4 + 4 + 4 + 68 + 64 + 16)
debug.info('Header: %s', repr(header))
header_magic = header[:4]
header_payload_length = struct.unpack('!L', header[4:8])[0]
header_decoded_length = struct.unpack('!L', header[8:12])[0]
header_hashkey = header[12:80]
header_hmac = header[80:144]
header_crypto_iv = header[144:]
if header_magic not in ['dt1z', 'dt1n']:
raise ValueError('Invalid hashkey in read block')
if hashkey != header_hashkey:
raise ValueError('Hash key in block does not match expected.')
payload = fp.read(header_payload_length)
debug.info('Payload: %s', repr(payload[:32]))
payload = decode_payload(
payload, self.aes_key,
header_crypto_iv, header_hmac, header_magic,
header_decoded_length)
return payload
class EncryptIndexClass:
'''Encrypt the tar-format index output.
This acts like a file and takes the tar-format index file and encrypts
it with HMAC message digests and a sequential series of IVs
(initialized to be random).
'''
def __init__(self, fp, blockstore):
'''
:param fp: The file to write encrypted output to.
:type fp: file
:param blockstore: The output blockstore (provides the aes_key
and UUID).
:type blockstore: BlockStore
'''
self.fp = fp
self.blockstore = blockstore
self.block = ''
self.split_size = 102400
self.bytes_written = 0
self.sequential_iv = SequentialIV()
fp.write(self.format_index_header())
def format_index_header(self):
'''Format a Tarzan index header.
Header format:
block magic number ("dti1").
uuid (36 bytes identifying the BlockStorage)
base_iv (16 random bytes)
:returns: str -- Tarzan index header
'''
debug.warning(
'Formatting index header: uuid: "%s", base_iv: "%s"',
self.blockstore.uuid, repr(self.sequential_iv.base_iv))
return bytes(
'dti1' + self.blockstore.uuid) + self.sequential_iv.base_iv
def format_payload_header(
self, compressed, crypto_iv, block_hmac, length, decoded_length):
'''Format a header for each block of payload.
:param compressed: If true, the block is compressed.
:type compressed: boolean
:param crypto_iv: The IV for this block.
:type crypto_iv: str
:param block_hmac: The HMAC of the plaintext block.
:type block_hmac: str
:param length: Length of the compressed block.
:type length: int
:param decoded_length: Length of the original data block.
:type decoded_length: int
:returns: str -- The block header.
'''
magic = 'dtbz' if compressed else 'dtb1'
debug.warning(
'Format payload header: magic: "%s", length: %d, '
'crypto_iv: "%s" block_hmac: "%s"',
magic, length, repr(crypto_iv), repr(block_hmac))
return (
magic + crypto_iv + block_hmac + struct.pack('!L', length)
+ struct.pack('!L', decoded_length))
def flush(self):
'''Flush the current buffered data.
Takes the current buffer and writes it out as a tarzan block.
The block length is rounded to 16 bytes (required by AES),
it is compressed (if that reduces the block) and encrypted,
and the result is written out. In the event of being called
without a full remainder block, it is considered to be the last
block and a short block with trailing NUL padding is written.
:returns: str -- The block header.
'''
debug.info('EncryptIndexClass.flush()')
is_last_block = False if len(self.block) >= 16 else True
if is_last_block:
block_to_write = self.block
self.block = None
else:
remainder = len(self.block) % 16
block_to_write = self.block[:len(self.block) - remainder]
self.block = self.block[len(self.block) - remainder:]
decoded_length = len(block_to_write)
decoded_length = len(block_to_write)
compressed = False
hmac_digest = '\0' * 64
crypto_iv = self.sequential_iv.get_next_iv()
mac512 = HMAC.new(self.blockstore.aes_key, digestmod=SHA512)
mac512.update(block_to_write)
hmac_digest = mac512.digest()
compressed_block = zlib.compress(block_to_write)
if len(compressed_block) < len(block_to_write):
block_to_write = compressed_block
compressed = True
block_to_write += '\0' * (16 - (len(block_to_write) % 16))
crypto = AES.new(self.blockstore.aes_key, AES.MODE_CBC, crypto_iv)
block_to_write = crypto.encrypt(block_to_write)
header = self.format_payload_header(
compressed, crypto_iv, hmac_digest, len(block_to_write),
decoded_length)
self.fp.write(header)
self.fp.write(block_to_write)
self.fp.flush()
def beginning_of_file(self):
'''Notify us that a new file header is starting.
This is so that we can nicely split the encryption blocks on the
output. If the output buffer is larger than `split_size`, the buffer
is flushed.
'''
debug.info('EncryptIndexClass.beginning_of_file()')
if len(self.block) >= self.split_size:
self.flush()
def write(self, data):
'''Write a block of data.
This data is written to an internal buffer, so that it can be
collected into and blocked for output encryption, MACing, and
compression.
:param data: Data to be written.
:type data: str
:returns: str -- The block header.
'''
debug.info('EncryptIndexClass.write(length=%d)', len(data))
self.bytes_written += len(data)
if len(self.block) >= 2 * self.split_size:
self.flush()
self.block += data
def close(self):
'''Finalize the output.
All buffered data is written, and a closing block is written. This
object is no longer usable after this.
'''
debug.info('EncryptIndexClass.close()')
trailing_padding = 10240 - (self.bytes_written % 10240)
if trailing_padding == 0:
trailing_padding = 10240
self.write('\0' * trailing_padding)
if len(self.block) < 16:
self.flush()
self.flush()
crypto_iv = self.sequential_iv.get_next_iv()
mac512 = HMAC.new(self.blockstore.aes_key, digestmod=SHA512)
hmac_digest = mac512.digest()
header = self.format_payload_header(
False, crypto_iv, hmac_digest, 0, 0)
self.fp.write(header)
self.fp.close()
self.fp = None
class DecryptIndexClass:
'''Decrypt the tarzan format file.
This acts like a file and reads the tarzan-format encrypted index file
and decrypts it.
'''
def __init__(self, fp, blockstore):
'''
:param fp: The file to read encrypted tarzan index from.
:type fp: file
:param blockstore: The output blockstore (provides the aes_key
and UUID).
:type blockstore: BlockStore
'''
self.fp = fp
self.blockstore = blockstore
self.buffer = ''
self.eof = False
self.read_index_header()
def read(self, length):
'''Read data from the encrypted stream.
:param length: Number of bytes of input to read.
:type length: int
:returns: str -- Data that was read.
'''
debug.info(
'DecryptIndexClass.read(length=%d), existing buffer: %d',
length, len(self.buffer))
while length > len(self.buffer) and not self.eof:
self.read_next_payload()
data = self.buffer[:length]
self.buffer = self.buffer[length:]
return data
def read_index_header(self):
'''Read the index header at the beginning of the tarzan file.
See :py:func:`EncryptIndexClass::format_index_header` for the
layout.'''
data = self.fp.read(4 + 36 + 16)
if data[:4] != 'dti1':
raise ValueError('Invalid header, did not find "dti1"')
self.uuid = data[4:40]
self.base_iv = data[40:56]