forked from id175196/cs262
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStrongBox.py
More file actions
executable file
·2394 lines (1915 loc) · 96.4 KB
/
Copy pathStrongBox.py
File metadata and controls
executable file
·2394 lines (1915 loc) · 96.4 KB
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
"""
The StrongBox encrypted P2P backup program. Run `./StrongBox.py -h` for details on how to execute.
"""
import socket
import ssl
import os
import cPickle # Supposed to be orders of magnitude faster than `pickle`, but with some limitations limitations on (esoteric) subclassing of `Pickler`/`Unpickler`.
import hashlib
import random
import shutil
import struct
import inspect
import json
import httplib
import copy
from urllib2 import urlopen
from collections import namedtuple
import threading
import Queue
import sys
import traceback
import time
import Crypto.Signature.PKCS1_v1_5, Crypto.Hash, Crypto.Cipher.AES, Crypto.PublicKey.RSA, Crypto.Random
import base64
import DirectoryMerkleTree
import subprocess
import argparse
import watchdog.observers as wd_observers
import watchdog.events as wd_events
VERSION= '0.1'
STORE_DIR = 'store'
REMOTE_STORE_BACKUPS_DIR = '.remote_store_backups'
CONFIG_DIR = '.config'
KEY_SUBDIR = 'keys'
OWN_KEYS_SUBDIR = 'own'
PEER_KEYS_SUBDIR = 'peer'
STORE_KEYS_SUBDIR = 'store'
# Named tuples have (immutable) class-like semantics for accessing fields, but are straightforward to pickle/unpickle.
# The following types are for important data whose contents and format should be relatively stable at this point.
PeerData = namedtuple('PeerData', 'network_address, store_revisions')
StoreData = namedtuple('StoreData', 'revision_data, peers')
RevisionData = namedtuple('RevisionData', 'revision_number, store_hash, signature')
Metadata = namedtuple('Metadata', 'peer_id, peer_dict, store_id, store_dict, encryption_key, aes_iv, merkle_tree')
# Necessary constants for messaging
PROTOCOL_VERSION = 1
INT_PACK_SIZE = struct.calcsize('!I')
INVALID_REVISION = None #RevisionData(revision_number=0, store_hash=None, signature=None)
class ManualDisconnectException(Exception):
"""
An exception for indicating manual disconnections which should not be treated as errors.
"""
pass
# TODO: Find a better place to put this ('utils.py'?)
class DirectoryModificationHandler(wd_events.FileSystemEventHandler):
def __init__(self, dir_modified_flag):
super(DirectoryModificationHandler, self).__init__()
self.dir_modified_flag = dir_modified_flag
def on_any_event(self, file_system_event):
# TODO: Evntually might want to record the changes to facilitate
# faster, partial Merkle tree regeneration.
self.dir_modified_flag.set()
class Peer:
"""
The central component of StrongBox. A peer is the entity that tracks changes to
the user's store and synchronizes backups with other peers.
"""
#########################
# Primary functionality #
#########################
# These are the goods, implemented at a higher level than the lower methods.
def __init__(self,
store_dir=None,
debug_verbosity=0,
root_directory=None,
debug_preamble=None,
_metadata=None,
lock=None,
shutdown_signaled=None,
store_modified_flag=None,
private_key_contents=None,
aes_key=None
):
"""Initialize a `Peer` object."""
# Set default or overridden attribute values.
self.store_dir= os.path.join(os.getcwd(), STORE_DIR) if (store_dir == None) else store_dir
self.debug_verbosity= debug_verbosity
self.root_directory = os.getcwd() if (root_directory == None) else root_directory
self.debug_preamble = debug_preamble
self._metadata = _metadata
self.lock = threading.RLock() if (lock == None) else lock
self.shutdown_signaled = threading.Event() if (shutdown_signaled == None) else shutdown_signaled
self.store_modified_flag= threading.Event() if (store_modified_flag == None) else store_modified_flag
# self.thread_exceptions = Queue.Queue()
self.initialize_directory_structure()
self.initialize_keys(private_key_contents)
self.load_metadata_file(aes_key)
def run(self, client_sleep_time=5):
"""Start operating as a both a peer client and peer server in synchronized threads."""
# Do preliminary updates before coming online
self.update_network_address()
self.check_store(force=True)
# Start observing the store for changes.
store_modification_handler = DirectoryModificationHandler(self.store_modified_flag)
store_observer = wd_observers.Observer()
store_observer.schedule(store_modification_handler, self.store_dir, recursive=True)
store_observer.start()
peer_server_thread = threading.Thread(target=self.run_peer_server, args=())
peer_server_thread.start()
peer_client_thread = threading.Thread(target=self.run_peer_client, args=())
peer_client_thread.start()
try:
time.sleep(2**30) # Just over 34 years.
except (KeyboardInterrupt, SystemExit):
self.shutdown_signaled.set()
self.debug_print( (1, '\nSHUTDOWN SIGNALED.\nWaiting for peer client and peer server threads to finish.\n') )
store_observer.stop()
t_i = time.time()
peer_client_thread.join(18)
peer_server_thread.join(20-(time.time()-t_i))
if peer_client_thread.is_alive() or peer_server_thread.is_alive():
self.debug_print( (0, 'Shutdown taking too long, forcibly quitting.') )
if peer_client_thread.is_alive():
peer_client_thread._Thread__stop()
if peer_server_thread.is_alive():
peer_server_thread._Thread__stop()
store_observer.join()
# Retrieve any exceptions from the peer server and client threads.
# try:
# while True:
# etype, value, tb = self.thread_exceptions.get(block=False)
# print 'Exception in thread.'
# traceback.print_exception(etype, value, tb)
# except Queue.Empty:
# pass
if self.debug_verbosity == 0:
print # Print an empty new line for the terminal to come back to.
def run_peer_client(self, sleep_time=1, socket_timeout=1):
"""
The peer client thread periodically reaches out to other peers to enact synchronizations.
"""
# TODO: Figure out why running this function as a thread causes the following modules to be sometimes set to `None`
import socket
try:
self.debug_print( (1, 'Peer client mode running.'))
while not self.shutdown_signaled.is_set():
# Find a peer with which to connect to and initiate a session.
server_peer_id = self.select_sync_peer()
if server_peer_id and self.lock.acquire(blocking=False):
try:
self.debug_print( [(1, 'Attempting to connect to peer server.'),
(1, 'network_address = {}'.format(self.peer_dict[server_peer_id].network_address)),
(2, 'server_peer_id = {}'.format([server_peer_id]))] )
# # FIXME: There's got to be something more sensible than this crap shoot... Maybe use queues.
# if not self.lock.acquire(blocking=False):
# time.sleep(socket_timeout)
# if not self.lock.acquire(blocking=False):
# raise socket.timeout()
# With lock in hand, check if there have been local changes to our store.
self.check_store()
skt_ssl = self.connect_to_peer(server_peer_id, socket_timeout)
try:
self.debug_print( (1, 'Successfully connected to peer server. Initiating peer client session.') )
self.peer_client_session(skt_ssl)
except socket.error:
self.debug_print( (1, 'Disconnected from peer server due to socket error.') )
except ManualDisconnectException:
self.debug_print( (2, 'The peer client session did not complete in a successful sync.') )
finally:
try:
skt_ssl.settimeout(.1)
skt_ssl.shutdown(socket.SHUT_RDWR)
skt_ssl.close()
except socket.error:
self.debug_print( (2, 'Socket already closed by peer server.') )
self.debug_print( (1, 'Disconnected from peer server.') )
except (socket.timeout, socket.error):
self.debug_print( (2, 'Could not connect to peer server.') )
finally:
try:
# FIXME: Quick hack to ensure the recursive lock is fully released. Need to identify how multiple acquisition might occur.
while True:
self.lock.release()
# FIXME: Not sure how we could get to the above line without having acquired the lock first...
except RuntimeError:
pass
# Sleep a while before iterating the loop again.
self.debug_print( (1, 'Peer client mode going to sleep.') )
time.sleep(sleep_time)
self.debug_print( (1, 'Peer client mode waking up.') )
self.update_network_address()
except:
import sys, traceback
print 'Exception in peer client thread.'
etype, value, tb = sys.exc_info()
traceback.print_exception(etype, value, tb)
def run_peer_server(self, socket_timeout=10):
"""
The peer server thread listens for and services connections from other peers.
"""
# TODO: Figure out why running this function as a thread causes the following modules to be set to `None`
import socket
try:
self.debug_print( (1, 'Peer server mode running.'))
skt_listener = self.create_listening_socket(timeout=socket_timeout)
while not self.shutdown_signaled.is_set():
self.debug_print( (1, 'Waiting for a peer client to connect.') )
try:
skt_raw, (peer_address, _) = skt_listener.accept()
# FIXME: There's got to be something more sensible than this crap shoot... Maybe use queues.
if not self.lock.acquire(blocking=False):
raise socket.timeout()
self.debug_print( (1, 'Connected to a peer client from \'{}\'. Initiating peer server session.'.format(peer_address)))
skt_ssl = ssl.wrap_socket(skt_raw, server_side=True, keyfile=self.private_key_file, certfile=self.x509_cert_file, ssl_version=ssl.PROTOCOL_SSLv3)
try:
self.peer_server_session(skt_ssl, peer_address)
except socket.error:
self.debug_print( (1, 'Disconnected from peer client due to socket error.') )
except ManualDisconnectException:
self.debug_print( (2, 'The peer server session did not complete in a successful sync.') )
finally:
try:
skt_ssl.settimeout(.1)
skt_ssl.shutdown(socket.SHUT_RDWR)
skt_ssl.close()
except socket.error:
self.debug_print( (3, 'Socket already closed by peer client.') )
self.debug_print( (1, 'Disconnected from peer client.') )
except (socket.timeout, socket.error):
pass
finally:
try:
# FIXME: Quick hack to ensure the recursive lock is fully released. Need to identify how multiple acquisition might occur.
while True:
self.lock.release()
# FIXME: Not sure how we could get to the above line without having acquired the lock first...
except RuntimeError:
pass
# Close the listening socket
skt_listener.shutdown(socket.SHUT_RDWR)
skt_listener.close()
except:
import sys, traceback
print 'Exception in peer server thread.'
etype, value, tb = sys.exc_info()
traceback.print_exception(etype, value, tb)
def peer_server_session(self, skt_ssl, peer_address):
"""
The activities undertaken once a peer client has connected.
"""
self.debug_print( (2, 'Waiting for peer client\'s handshake message.'))
pickled_payload = self.receive_expected_message(skt_ssl, 'handshake_msg')
(client_peer_id, client_peer_dict) = self.unpickle('handshake_msg', pickled_payload)
self.debug_print( [(1, 'Handshake message received from peer client.'),
(2, 'client_peer_id = {}'.format([client_peer_id])),
(3, 'client_peer_dict = {}'.format([client_peer_dict]))] )
self.debug_print( (1, 'Attempting to learn from peer client\'s reports about itself.'))
self.record_peer_data(client_peer_id, client_peer_dict[client_peer_id])
# If the peer client is of interest, handshake back.
if client_peer_id in self.peer_dict.keys():
self.debug_print( (1, 'Sending handshake message to peer client.'))
self.send_handshake_msg(skt_ssl)
# Otherwise, disconnect.
else:
self.debug_print( (1, 'No stores in common with peer client. Disconnecting.'))
self.send_disconnect_req(skt_ssl, 'No stores in common.')
raise ManualDisconnectException()
self.debug_print( (1, 'Store match!') )
# FIXME: For known client peers, will want to verify the public key provided to the SSL.
# TODO: Should only ask for peer's public key when it's unknown (?)
# Receive and record the peer client's public key file.
self.debug_print( (2, 'Waiting for peer client\'s public key.'))
pickled_payload = self.receive_expected_message(skt_ssl, 'public_key_msg')
public_key_file_contents = self.unpickle('public_key_msg', pickled_payload)
# If the peer client is of interest to us and we don't have their public key, record it.
if (client_peer_id in self.peer_dict.keys()) \
and (not os.path.isfile(self.get_peer_key_path(client_peer_id))):
self.debug_print( [(1, 'Recording public key for new peer.'),
(4, 'public_key_file_contents = {}'.format([public_key_file_contents]))] )
with open(self.get_peer_key_path(client_peer_id), 'w') as f:
f.write(public_key_file_contents)
# Otherwise, check the supplied key against what we have on record.
# FIXME: We should really be getting this from the SSL socket.
elif (client_peer_id in self.peer_dict.keys()) \
and (self.get_peer_key(client_peer_id) != Crypto.PublicKey.RSA.importKey(public_key_file_contents)):
self.debug_print( (1, 'Public key supplied by peer client does not match what we have on record. Disconnecting.') )
self.send_disconnect_req(skt_ssl, 'Public key failed verification.')
raise ManualDisconnectException()
self.debug_print( (1, 'Parsing useful gossip from peer client.'))
self.learn_peer_gossip(client_peer_id, client_peer_dict)
# Get the peer client's sync request.
self.debug_print( (2, 'Waiting for peer client\'s sync request.') )
pickled_payload = self.receive_expected_message(skt_ssl, 'sync_req')
sync_store_id = self.unpickle('sync_req', pickled_payload)
self.debug_print( [(1, 'Peer client sync request received.'),
(2, 'sync_store_id = {}'.format([sync_store_id]))] )
# Figure out what type of sync we'll be conducting.
sync_type = self.determine_sync_type(client_peer_id, sync_store_id)
# Sync
self.debug_print( (1, 'Executing sync of type \'{}\' with peer client.'.format(sync_type)) )
self.do_sync(skt_ssl, sync_type, client_peer_id, sync_store_id)
self.debug_print( (1, 'Successfully completed sync with peer client.'))
# Session over, send the peer client a disconnect request.
self.debug_print( (1, 'Peer server session complete. Disconnecting.'))
self.send_disconnect_req(skt_ssl, 'Session complete.')
def peer_client_session(self, skt_ssl):
"""
The activities undertaken once connected to a peer server.
"""
# Initiate handshake with the peer server, providing pertinent metadata about ourselves and gossip.
self.debug_print( (1, 'Sending handshake message to peer server.'))
self.send_handshake_msg(skt_ssl)
self.debug_print( (2, 'Waiting for peer server\'s handshake message.'))
pickled_payload = self.receive_expected_message(skt_ssl, 'handshake_msg')
(server_peer_id, server_peer_dict) = self.unpickle('handshake_msg', pickled_payload)
self.debug_print( [(1, 'Handshake message received from peer server.'),
(2, 'server_peer_id = {}'.format([server_peer_id])),
(3, 'server_peer_dict = {}'.format([server_peer_dict]))] )
# The peer server's knowledge of itself is at least as up to date as ours, so trust what it says.
self.record_peer_data(server_peer_id, server_peer_dict[server_peer_id])
self.debug_print( (1, 'Parsing useful gossip from peer server.'))
self.learn_peer_gossip(server_peer_id, server_peer_dict)
# FIXME
# Always send public key file to server
self.debug_print( (1, 'Sending public key to peer server'))
self.send_public_key_msg(skt_ssl)
# Select a store to sync with the peer server.
sync_store_id = self.select_sync_store(server_peer_id)
# Quit the session if we couldn't find a store to sync.
if not sync_store_id:
self.debug_print( (1, 'No valid mutual stores to sync or check. Disconnecting.') )
self.send_disconnect_req(skt_ssl, 'No valid mutual stores to sync or check.')
raise ManualDisconnectException()
# Initiate a sync.
self.debug_print( [(1, 'Requesting sync with peer server.'),
(2, 'sync_store_id = {}'.format([sync_store_id]))] )
self.send_sync_req(skt_ssl, sync_store_id)
# Figure out what type of sync we'll be conducting.
sync_type = self.determine_sync_type(server_peer_id, sync_store_id)
# Sync
self.debug_print( (1, 'Executing sync of type \'{}\' with peer server.'.format(sync_type)))
self.do_sync(skt_ssl, sync_type, server_peer_id, sync_store_id)
self.debug_print( (1, 'Successfully completed sync with peer server.') )
self.debug_print( (1, 'Session complete.') )
self.debug_print( (2, 'Waiting for peer server\'s disconnect request.'))
pickled_payload = self.receive_expected_message(skt_ssl, 'disconnect_req')
disconnect_message = self.unpickle('disconnect_req', pickled_payload)
self.debug_print( [(1, 'Peer requested disconnect reporting the following:'),
(1, disconnect_message)] )
def do_sync(self, skt, sync_type, peer_id, store_id):
"""
Initiate a "receive", "send", or "check" sync.
"""
if sync_type == 'receive':
self.sync_receive(skt, peer_id, store_id)
elif sync_type == 'send':
self.sync_send(skt, peer_id, store_id)
elif sync_type == 'check':
self.sync_check(skt, peer_id, store_id)
else:
# TODO: Raise a meaningful exception.
raise Exception()
####################
# Class attributes #
####################
# FIXME: Beware the unsafety if accessing mutable fields from multiple threads.
listening_port = 51338 # TODO: Magic number. Ideally would want listening listening_port number to be configurable per peer.
##########################
# Initialization methods #
##########################
def generate_initial_metadata(self, aes_key):
"""
Generate a peer's important configuration metadata upon first execution.
"""
# TODO: Just do full initialization here (i.e. including revision and tree data).
self.debug_print( (0, 'Creating initial configuration for peer.') )
# Since we're doing initialization, make sure the store is empty for the first revision.
store_contents = os.listdir(self.store_dir)
if store_contents:
raise EnvironmentError('Store directory \'%(store_dir)s\' must be empty prior to initial configuration.'
% self.__dict__)
peer_id = self.generate_peer_id()
store_id = self.compute_store_id()
network_address = self.get_public_network_address( )
merkle_tree = DirectoryMerkleTree.make_dmt(self.store_dir, encrypter=self)
# Prepare and sign the initial revision data.
revision_number = 1
store_hash = merkle_tree.dmt_hash
pickled_payload = cPickle.dumps( (revision_number, store_hash) )
signature = self.sign(pickled_payload)
own_revision_data = RevisionData(revision_number=revision_number, store_hash=store_hash, signature=signature)
initial_peers = set([peer_id])
if not aes_key:
aes_key = Crypto.Random.new().read(Crypto.Cipher.AES.key_size[-1])
# FIXME: Remove
aes_iv = Crypto.Random.new().read(Crypto.Cipher.AES.block_size)
peer_dict = {peer_id: PeerData(network_address, {store_id: own_revision_data})}
store_dict = {store_id: StoreData(own_revision_data, initial_peers)}
# Load the initial values into a `Metadata` object.
metadata = Metadata(peer_id, peer_dict, store_id, store_dict, aes_key, aes_iv, merkle_tree)
return metadata
def generate_peer_id(self):
"""
Generate a quasi-unique ID for this peer using a hash (SHA-256, which
currently has no known collisions) of the owner's public key "salted" with
32 random bits.
"""
cipher = hashlib.sha256(self.public_key.exportKey())
cipher.update(Crypto.Random.new().read(4))
peer_id = cipher.digest()
self.debug_print( (2, 'Generated new peer ID: {}'.format([peer_id])) )
return peer_id
def compute_store_id(self, public_key=None):
"""
Store IDs are meant to uniquely identify a store/user. They are essentially
the RSA public key, but we use use their SHA-256 hash to "flatten" them to
a shorter, predictable length.
"""
# Default to using own public key.
if not public_key:
public_key = self.public_key
store_id = hashlib.sha256(public_key.exportKey()).digest()
self.debug_print( (2, 'Generated new store ID: {}'.format([store_id])) )
return store_id
#######################
# Config file methods #
#######################
def initialize_directory_structure(self):
"""
Generate the directories for storing configuration data and the backups of
other peers' stores.
"""
if not os.path.exists(self.store_dir):
os.makedirs(self.store_dir)
self.config_dir = os.path.join(self.root_directory, CONFIG_DIR)
self.key_dir = os.path.join(self.config_dir, KEY_SUBDIR)
self.own_keys_dir = os.path.join(self.key_dir, OWN_KEYS_SUBDIR)
if not os.path.exists(self.own_keys_dir):
os.makedirs(self.own_keys_dir)
self.peer_keys_dir = os.path.join(self.key_dir, PEER_KEYS_SUBDIR)
if not os.path.exists(self.peer_keys_dir):
os.makedirs(self.peer_keys_dir)
self.store_keys_dir = os.path.join(self.key_dir, STORE_KEYS_SUBDIR)
if not os.path.exists(self.store_keys_dir):
os.makedirs(self.store_keys_dir)
self.remote_store_backups_dir = os.path.join(self.root_directory, REMOTE_STORE_BACKUPS_DIR)
if not os.path.exists(self.remote_store_backups_dir):
os.makedirs(self.remote_store_backups_dir)
def initialize_keys(self, private_key_contents):
"""
Import, load, or generate the private and public keys for the user and their store.
"""
self.private_key_file = os.path.join(self.own_keys_dir, 'private_key.pem')
if private_key_contents:
with open(self.private_key_file, 'w') as f:
f.write(private_key_contents)
self.private_key = Crypto.PublicKey.RSA.importKey(private_key_contents)
elif os.path.isfile(self.private_key_file):
with open(self.private_key_file, 'r') as f:
self.private_key = Crypto.PublicKey.RSA.importKey(f.read())
else:
self.private_key = Crypto.PublicKey.RSA.generate(4096)
with open(self.private_key_file, 'w') as f:
f.write(self.private_key.exportKey())
# TODO: Don't believe we ever actually use the public key file.
self.public_key_file = os.path.join(self.own_keys_dir, 'public_key.pem')
if os.path.isfile(self.public_key_file):
with open(self.public_key_file, 'r') as f:
self.public_key = Crypto.PublicKey.RSA.importKey(f.read())
else:
self.public_key = self.private_key.publickey()
with open(self.public_key_file, 'w') as f:
f.write(self.public_key.exportKey())
self.x509_cert_file = os.path.join(self.own_keys_dir, 'x509.pem')
if not os.path.isfile(self.x509_cert_file):
# Use OpenSSL's CLI to generate an X.509 from the existing RSA private key
# Adapted from http://stackoverflow.com/a/12921889 and http://stackoverflow.com/a/12921889
subprocess.check_call('openssl req -new -batch -x509 -nodes -days 3650 -key ' +
self.private_key_file +
' -out ' + self.x509_cert_file,
shell=True)
# TODO: De-uglify
def load_metadata_file(self, aes_key):
"""
Load important configuration metadata that must be persisted to storage.
"""
# Create a null metadata object to update against
self._metadata = Metadata(None, None, None, None, None, None, None)
self.metadata_file = os.path.join(self.config_dir, 'metadata_file.pickle')
self.backup_metadata_file = self.metadata_file + '.bak'
try:
# Load the metadata file
if os.path.isfile(self.metadata_file):
self.debug_print( (2,'Metadata file found, loading.') )
with open(self.metadata_file, 'r') as f:
metadata = cPickle.load(f)
else:
raise Exception()
except:
try:
self.debug_print( (2,'Metadata file not found. Attempting to load backup.') )
# Load the backup file
if os.path.isfile(self.backup_metadata_file):
self.debug_print( (2,'Backup metadata file found, loading.') )
with open(self.backup_metadata_file, 'r') as f:
metadata = cPickle.load(f)
shutil.copyfile(self.backup_metadata_file, self.metadata_file)
else:
raise Exception()
except:
self.debug_print( (2,'Backup metadata file not found. Generating new file.') )
metadata = self.generate_initial_metadata(aes_key)
# Immediately write out to non-volatile storage since `update_metadata()` expects a pre-existing file to be made the backup.
with open(self.metadata_file, 'w') as f:
cPickle.dump(metadata, f)
# Bring the new values into effect.
self.update_metadata(metadata)
def get_peer_key_path(self, peer_id):
"""
Convenience function to compute the location of a peer's recorded public key file.
"""
if peer_id == self.peer_id:
key_path = self.public_key_file
else:
peer_filename = self.compute_safe_filename(peer_id)
key_path = os.path.join(self.peer_keys_dir, peer_filename+'.pem')
return key_path
def get_peer_key(self, peer_id):
"""
Convenience function to load a peer's public key.
"""
if peer_id == self.peer_id:
return self.public_key
with open(self.get_peer_key_path(peer_id), 'r') as f:
public_key = Crypto.PublicKey.RSA.importKey(f.read())
return public_key
def _get_store_key_path(self, store_id):
"""
Convenience function to compute the location of a store's recorded public key file.
"""
if store_id == self.store_id:
key_path = self.public_key_file
else:
store_filename = self.compute_safe_filename(store_id)
key_path = os.path.join(self.store_keys_dir, store_filename+'.pem')
return key_path
def get_store_key(self, store_id):
"""
Convenience function to load a store's public key .
"""
if store_id == self.store_id:
return self.public_key
with open(self._get_store_key_path(store_id), 'r') as f:
public_key = Crypto.PublicKey.RSA.importKey(f.read())
return public_key
def _get_store_path(self, store_id):
"""
Unsafe reference to a store's absolute path meant for internal use only.
"""
if store_id == self.store_id:
return self.store_dir
store_dirname = self.compute_safe_filename(store_id)
return os.path.join(self.remote_store_backups_dir, store_dirname)
def compute_safe_filename(self, input_string):
"""
Take any string of characters (e.g. the result of a SHA hash) and reversibly
convert it to a valid filename.
"""
return base64.urlsafe_b64encode(input_string)
######################
# Metadata accessors #
######################
@property
def peer_id(self):
"""A quasi-unique identifier for this particular peer."""
return self.metadata.peer_id
@property
def peer_dict(self):
"""
A mapping from the IDs of other peers who serve as backups to this peer to
important metadata such as their IP address and what revisions they had for
stores of interest upon last contact.
"""
return self.metadata.peer_dict
@property
def store_id(self):
"""A quasi-unique identifier for this peer's store."""
return self.metadata.store_id
@property
def store_dict(self):
"""
A mapping from store IDs to important metadata such as this peer's current
revision for the store and the IDs of peers known to be associated with the
store.
"""
return self.metadata.store_dict
@property
def merkle_tree(self):
"""
A `DirectoryMerkleTree` object containing the current state of the user's store.
"""
return self.metadata.merkle_tree
@property
def encryption_key(self):
"""
The AES key used for encrypting a user's store data before transmission.
"""
return self.metadata.encryption_key
# FIXME: Remove.
@property
def aes_iv(self):
return self.metadata.aes_iv
@property
def metadata(self):
"""
Important metadata about peers and stores. Access is controlled to ensure
that all changes are backed up to primary storage.
"""
return self._metadata
@property
def network_address(self):
"""
The current network address of this peer.
"""
return self.peer_dict[self.peer_id].network_address
def get_revision_data(self, peer_id, store_id):
"""
A convenience function for retrieving a given peer's revision data for a
given store.
"""
revision_data = self.peer_dict[peer_id].store_revisions[store_id]
return revision_data
###################################
# Configuration metadata mutators #
###################################
def update_metadata(self, metadata, lock_acquired=False):
"""
All updates to a peer's stored metadata occur through this function so
we can ensure that changes are backed up to primary storage before coming
into effect.
"""
# Only update if necessary.
if metadata == self.metadata:
self.debug_print( (2, 'No new metadata. Update skipped.') )
return
# Accumulate and squawk out reports of changes.
print_tuples = [(2, 'Updating metadata configuration.')]
if metadata.peer_id != self.peer_id:
print_tuples.append( (2, 'peer_id = {}'.format([metadata.peer_id])) )
if metadata.peer_dict != self.peer_dict:
print_tuples.append( (2, '`peer_dict` updated') )
print_tuples.append( (3, 'peer_dict = {}'.format(metadata.peer_dict)) )
if metadata.store_id != self.store_id:
print_tuples.append( (2, 'store_id = {}'.format([metadata.store_id])) )
if metadata.store_dict != self.store_dict:
print_tuples.append( (2, '`store_dict` updated') )
print_tuples.append( (3, 'store_dict = {}'.format(metadata.store_dict)) )
if metadata.encryption_key != self.encryption_key:
print_tuples.append( (2, '`encryption_key` updated') )
print_tuples.append( (4, '!!!! SOOOoo INSECURE !!!!') )
print_tuples.append( (4, 'encryption_key = {}'.format([metadata.encryption_key])) )
if metadata.aes_iv != self.aes_iv:
print_tuples.append( (2, '`aes_iv` updated') )
print_tuples.append( (4, '!!!! SOOOoo INSECURE !!!!') )
print_tuples.append( (4, 'aes_iv = {}'.format([metadata.aes_iv])) )
if metadata.merkle_tree != self.merkle_tree:
print_tuples.append( (2, '`merkle_tree` updated') )
print_tuples.append( (4, 'merkle_tree:') )
self.debug_print( print_tuples )
if (metadata.merkle_tree != self.merkle_tree) and (self.debug_verbosity >= 4):
DirectoryMerkleTree.print_tree(self.merkle_tree)
# Copy the previous metadata file to the backup location.
shutil.copyfile(self.metadata_file, self.backup_metadata_file)
# Write the new metadata to primary storage.
with open(self.metadata_file, 'w') as f:
cPickle.dump(metadata, f)
# Refer to the new metadata now that it's been stored to disk
self._metadata = metadata
def record_peer_data(self, peer_id, peer_data, lock_acquired=False):
"""
Update the recorded metadata for an individual peer.
"""
peer_mutual_stores = set(peer_data.store_revisions.keys()).intersection(set(self.store_dict.keys()))
# TODO: Verify that this check is always redundant and remove (or remove duplicate implementation in `learn...`
# Only want to track peers that are associated with at least one store we're concerned with.
if not peer_mutual_stores:
return
# Only want new data.
if (peer_id in self.peer_dict.keys()) and (peer_data == self.peer_dict[peer_id]):
return
# Create copies data for staging changes.
peer_dict = copy.deepcopy(self.peer_dict)
store_dict = copy.deepcopy(self.store_dict)
# Prepare an empty record if the peer wasn't already known.
if not (peer_id in self.peer_dict.keys()):
network_address = None
store_revisions = dict()
# Otherwise, work from existing knowledge of the peer.
else:
network_address = peer_dict[peer_id].network_address
store_revisions = peer_dict[peer_id].store_revisions
# Record the peer's associations with only the stores we care about.
for mutual_store_id in peer_mutual_stores:
# Verify the reported revision data before recording.
if self.verify_revision_data(mutual_store_id, peer_data.store_revisions[mutual_store_id]):
store_revisions[mutual_store_id] = peer_data.store_revisions[mutual_store_id]
else:
store_revisions[mutual_store_id] = INVALID_REVISION
# Simultaneously ensure the store's association with the peer to maintain the bidirectional mapping.
store_dict[mutual_store_id].peers.add(peer_id)
# TODO: Remove (?)
# Again, peers are unaware of their own IP addresses, so only take valid changes thereof
if peer_data.network_address:
network_address = peer_data.network_address
# Enact the update.
peer_dict[peer_id] = PeerData(network_address, store_revisions)
metadata = Metadata(self.peer_id, peer_dict, self.store_id, store_dict, self.encryption_key, self.aes_iv, self.merkle_tree)
self.update_metadata(metadata, True)
def learn_peer_gossip(self, gossip_peer_id, gossip_peer_dict, lock=False):
"""
Update our knowledge of peers based on gossip from another peer.
"""
# Limit our considerations to mutual peers (not including ourself and the peer we're communicating with).
mutual_peers = set(gossip_peer_dict.keys()).intersection(set(self.peer_dict.keys())).difference(set([self.peer_id, gossip_peer_id]))
# if not mutual_peers:
# return
our_stores = set(self.store_dict.keys())
for peer_id in mutual_peers:
# Only update if information about received about a peer is newer than our
# records. Currently, the ways of detecting this are somewhat indirect.
# TODO: Without signing `PeerData` objects, malicious peers
# can manipulate the state of another peer. (Should there be versioning too?)
gossip_peer_stores = set(gossip_peer_dict[peer_id].store_revisions.keys())
recorded_peer_stores = set(self.peer_dict[peer_id].store_revisions.keys())
peer_mutual_stores = gossip_peer_stores.intersection(our_stores)
# See if the gossip indicates the peer is newly associated with a store we also have.
if peer_mutual_stores.difference(recorded_peer_stores):
self.record_peer_data(peer_id, gossip_peer_dict[peer_id], True)
break
# Otherwise, see if the gossip reports the peer to be more current with any mutual
# store than we knew about.
gossip_mutual_store_revisions = {store_id: gossip_peer_dict[peer_id].store_revisions[store_id] for store_id in peer_mutual_stores} # Python 2.7+
recorded_mutual_store_revisions = {store_id: self.peer_dict[peer_id].store_revisions[store_id] for store_id in peer_mutual_stores} # Python 2.7+
if any( self.gt_revision_data(store_id, gossip_mutual_store_revisions[store_id], recorded_mutual_store_revisions[store_id]) \
for store_id in peer_mutual_stores):
self.record_peer_data(peer_id, gossip_peer_dict[peer_id], True)
break
# Learn new peers associated with our stores of interest.
unknown_peers = set(gossip_peer_dict.keys()).difference(set(self.peer_dict.keys()))
for peer_id in unknown_peers:
gossip_peer_stores = set(gossip_peer_dict[peer_id].store_revisions.keys())
if set(gossip_peer_stores).intersection(our_stores):
self.record_peer_data(peer_id, gossip_peer_dict[peer_id], True)
def get_public_network_address(self):
# TODO: Figure out a fallback for this
network_address = None
while not network_address:
try:
network_address = json.load(urlopen('http://httpbin.org/ip'))['origin']
except httplib.BadStatusLine:
pass
return network_address
def update_network_address(self, lock=False):
"""Update this peer's already existing IP address data."""
# Create staging copy of data to be changed
peer_dict = copy.deepcopy(self.peer_dict)
# Get and store the IP address
# FIXME: Would like to sign this data (probably the whole `PeerData` object).
network_address = self.get_public_network_address()
peer_data = PeerData(network_address, peer_dict[self.peer_id].store_revisions)
peer_dict[self.peer_id] = peer_data
# Enact the change.
metadata = Metadata(self.peer_id, peer_dict, self.store_id, self.store_dict, self.encryption_key, self.aes_iv, self.merkle_tree)
self.update_metadata(metadata, True)
def update_peer_revision(self, peer_id, store_id, invalid=False, lock=None):
"""
After sending a peer synchronization data and verifying their store contents,
update our recording of their revision for the store in question to match
ours.
"""
# If the peer had a more recent revision than us, no need to update.
our_revision = self.get_revision_data(self.peer_id, store_id)
their_revision = self.get_revision_data(peer_id, store_id)
if self.gt_revision_data(store_id, their_revision, our_revision):
return
# Create a copy of the pertinent data in which to stage our changes.
peer_store_revisions = copy.deepcopy(self.peer_dict[peer_id].store_revisions)
if not invalid:
# Set the peer's revision for the store to match ours.
self.debug_print( (1, 'Syncing peer verified store revision {}.'.format(our_revision.revision_number)) )
peer_store_revisions[store_id] = our_revision
else:
# Record the peer's revision for the store as `None`
peer_store_revisions[store_id] = INVALID_REVISION
# Enact the changes
peer_data = PeerData(self.peer_dict[peer_id].network_address, peer_store_revisions)
self.record_peer_data(peer_id, peer_data, True)
def update_store_revision(self, store_id, revision_data, lock=None):
"""
Increment the revision number and recalculate the corresponding hash and
revision signature for the current state of the user's store.
"""
# Create a copy of the pertinent data in which to stage our changes.
store_dict = copy.deepcopy(self.store_dict)
store_dict[store_id] = StoreData(revision_data=revision_data, peers=store_dict[store_id].peers.union(set([self.peer_id])))
# Also modify our own entry in the peer dictionary so we can gossip to other peers about the new revision.
network_address = self.peer_dict[self.peer_id].network_address