-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbcsim.py
2019 lines (1619 loc) · 68.9 KB
/
bcsim.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 python3
""" Blockchain simulator
Simulates a permissioned blockchain with known participants.
This program implements a permissioned blockchain system among four participating machines,
Machine m0 is the blockchain administrator
Machine m1 is an agent
Machine m2 is an agent
Machine m4 is an agent
Agents are machines that monitor digital assets to which they have read access.
The agents record the results of their monitoring actions onto the blockchain.
The assets to monitor are specified in config files unique to each agent.
Each agent reads its asset specification from two config files, performs
the specified actions on each asset, and creates a new block with the results.
Various types (classes) of assets are defined with properties and methods
appropriate for each type of asset.
This simulator is executed on the command-line and it needs executable permission.
Functionality is divided into three sub-commands,
./bcsim.py newbc
./bcsim.py admin
./bcsim.py agent
newbc: creates a new blockchain with block 0, the genesis block
admin: allows the user (administrator) to administer the system
agent: functions that agents use to monitor assets and create new blocks
The admin and agent commands have further optional and non-optional arguments.
The admin command is used both during the simulation (to synchronise the blockchain
among participants) and, after simulation termination, for blockchain analysis.
The simulation is started by first creating and synchronising a new blockchain.
Next, all machines are activated by means of cronjob files on each machine.
The cronjobs implement a defined time-based round-robin schedule which specifies
when each agent machine performs its monitoring actions and creates a new block.
The schedule also specifies when the admin machine, m0, synchronises the blockchain.
On its turn, each agent will execute the agent sub-command which reads its asset
specification and executes the associated monitoring actions on those assets.
The agent then writes the results onto a new block on the blockchain.
The simulation involves the use of another program, perturb.py, to perform
perturbations on the monitored assets. This is executed by the cronjobs.
Copyright 2022 Ari Hämäläinen
"""
import re
import os
import csv
import time
import pickle
import shutil
import hashlib
import argparse
import ipaddress
from nacl import signing
from random import choice
from getpass import getuser
from secrets import randbits
from socket import gethostname
from ipaddress import ip_address
from io import BytesIO, BufferedWriter
from base64 import b64encode, b64decode
from pickle import dumps, dump, loads, load
from subprocess import run, CalledProcessError
from time import time, ctime, localtime, strftime
SUPPLIERS = {'m1', 'm2', 'm4'}
LOGFILE = 'log_m0'
AUTHORIDGENESIS = 'm0'
SIGNINGKEYFILEGENESIS = 'signing_key_file_m0'
SIGNINGKEYFILEPREFIX = 'signing_key_file_'
VERIFYKEYFILEPREFIX = 'verify_key_file_'
BLOCKCHAINFILE = 'blockchain_pickle'
COMMANDTYPES = {'CmdGeneric', 'CmdPing', 'CmdNmap', 'CmdNetstat', 'CmdLast', 'CmdUfwBlock', 'CmdSshd'}
COMMANDTYPESLASTBLOCK = {'CmdLast', 'CmdUfwBlock', 'CmdSshd'} # knowledge of a previous block required
ASSETTYPES = {'Directory', 'FileHashOnly', 'FileWhole', 'FileWholeRemote'}
ASSETTYPESLASTBLOCK = {'Directory', 'FileWhole', 'FileWholeRemote'} # knowledge of a previous block required
class GenericDescriptor:
""" Generic descriptor for class attributes
Defines the private naming scheme for class attributes.
"""
def __set_name__(self, owner, attributename):
self.public_name = attributename
self.private_name = f'_{attributename}'
def __get__(self, obj, objtype=None):
value = getattr(obj, self.private_name)
return value
def __set__(self, obj, value):
setattr(obj, self.private_name, value)
class FileSystemAssetError(Exception):
pass
class DirectoryError(Exception):
pass
class FileHashOnlyError(Exception):
pass
class FileWholeError(Exception):
pass
class readassetlistError(Exception):
pass
class readcommandlistError(Exception):
pass
class AssetTypeError(Exception):
pass
class CommandTypeError(Exception):
pass
class filehashError(Exception):
pass
class dirlistingError(Exception):
pass
class cmdnmapError(Exception):
pass
class cmdnetstatError(Exception):
pass
class cmdgenericError(Exception):
pass
class verifyError(Exception):
pass
class computeblocksigError(Exception):
pass
class genesisError(Exception):
pass
class makenextblockError(Exception):
pass
class addnewblockError(Exception):
pass
class verifypreviousblockhashError(Exception):
pass
class cmdlastError(Exception):
pass
class cmdufwblockError(Exception):
pass
class cmdsshdError(Exception):
pass
class summarizeblockError(Exception):
pass
class checkintegrityError(Exception):
pass
class blockdataError(Exception):
pass
class serializeError(Exception):
pass
class dirassetError(Exception):
pass
class fileassetError(Exception):
pass
class filewholeassetError(Exception):
pass
class commandassetError(Exception):
pass
class fileassethistError(Exception):
pass
class dirassethistError(Exception):
pass
class cmdhistError(Exception):
pass
class FileWholeRemoteError(Exception):
pass
class filewholeremoteError(Exception):
pass
class comparehashesError(Exception):
pass
class blocksbyauthorError(Exception):
pass
class enumerateassetsError(Exception):
pass
class assethashchangesError(Exception):
pass
class dirdiffError(Exception):
pass
class hashchangesError(Exception):
pass
class extractallfilehashes(Exception):
pass
class FileSystemAsset:
''' Base class for assets that are stored in a filesystem
e.g. files or directories on disk and accessible by path.
This class acts as a base class for other subclasses,
providing common attributes to the child classes.
'''
assetid = GenericDescriptor()
assettype = GenericDescriptor()
assetpath = GenericDescriptor()
def __init__(self, assetid=None, assettype=None, assetpath=None):
self.assetid = assetid
self.assettype = assettype
self.assetpath = assetpath
if not os.path.exists(self.assetpath):
raise FileSystemAssetError(f'Invalid assetpath "{self.assetpath}"')
def __repr__(self):
return f'{self.__class__.__name__}({self.assetid}, {self.assetpath})'
class Directory(FileSystemAsset):
''' FileSystemAssets that are directories
'''
dirlisting = GenericDescriptor()
filesindir = GenericDescriptor()
dirhashes = GenericDescriptor()
dirhash = GenericDescriptor()
def __init__(self, lastblock=None, **kwds):
super().__init__(**kwds)
if not os.path.isdir(self.assetpath):
raise DirectoryError(f'{self.assetpath} not a directory')
#
# we need to compute dirhash and compare against last block by author
# to see if dirhash has changed. If it has we continue as normal
# populating the instance attributes. If dirhash has not changed
# filesindir and dirhashes are set to None, and just the unchanged
# dirhash is recorded
self.f_dirlisting()
files, hashlist, directoryhash = self.f_dirhash()
self.dirhash = directoryhash
try:
# This authorid has not written a prior block, OR
# assetid not present in lastblock, OR
# this assetid's .hash attribute has changed from value in lastblock
if (lastblock is None or \
self.assetid not in lastblock.data.assets or \
self.hashchanged(lastblock)):
self.filesindir = files
self.dirhashes = hashlist
else:
self.filesindir = None
self.dirhashes = None
except:
raise DirectoryError(f'Error accessing last block by this authorid')
def hashchanged(self, lastblock):
''' Check if filehash has changed from last block
'''
if not lastblock.genesisblock:
previousdirhash = lastblock.data.assets[self.assetid].dirhash
return not self.dirhash == previousdirhash
def f_dirlisting(self):
""" Get output of ls -la for the directory asset
This is a record of file metadata (mode, mtime etc).
This attribute is always populated because currently
we do not record file metadata any other way.
"""
command = []
command.append('ls')
command.append('-la')
command.append('--time-style=long-iso')
command.append(f'{self.assetpath}')
try:
cp = run(command, check=True, capture_output=True, text=True)
self.dirlisting = cp.stdout
except CalledProcessError:
raise dirlistingError(f'Unable to execute ls on {self.assetpath}')
return None
def f_filesindir(self):
''' Computes list of all files in directory
'''
files = []
for direntry in os.scandir(self.assetpath):
if direntry.is_file():
files.append(direntry.path)
return files
def f_dirhashes(self):
''' Computes list of (hash, path) for each file in directory
'''
hashlist = []
files = self.f_filesindir()
for path in files:
hashlist.append((filehash(path), path))
return files, hashlist
def f_dirhash(self):
''' Compute hash over all the files in a directory
Computes a single hash on a concatenation of each file's hash.
'''
s = ''
files, hashlist = self.f_dirhashes()
for hash, path in hashlist:
s += hash
directoryhash = hashlib.sha3_224(bytes.fromhex(s)).hexdigest()
return files, hashlist, directoryhash
class FileHashOnly(FileSystemAsset):
''' Files for which we only want the hash
All monitored file assets have hash recorded
'''
hash = GenericDescriptor()
def __init__(self, **kwds):
super().__init__(**kwds)
if not os.path.isfile(self.assetpath):
raise FileHashOnlyError(f'{self.assetpath} not a file')
self.f_hash()
def f_hash(self):
self.hash = filehash(self.assetpath)
return None
class FileWhole(FileHashOnly):
''' Files for which we record content if hash has changed
This class is an example of an asset type whose instantiation
depends on knowledge of the last block written by author.
If file hash has changed since lastblock record file contents
using f_filecontent(), otherwise record just the hash. This class is not
intended for files that change regularly like logfiles. Those files should
be recorded differently eg tail.
'''
filecontent = GenericDescriptor()
def __init__(self, lastblock=None, **kwds):
super().__init__(**kwds)
# This authorid has not written a last block, OR
# assetid not present in last block, OR
# this assetid's .hash attribute has changed from value in last block
try:
if (lastblock is None or \
self.assetid not in lastblock.data.assets or \
self.hashchanged(lastblock)):
self.f_filecontent()
else:
self.filecontent = None
except:
raise FileWholeError(f'Error accessing last block by this authorid')
def hashchanged(self, lastblock):
''' Check if filehash has changed from last block
'''
if not lastblock.genesisblock:
previousfilehash = lastblock.data.assets[self.assetid].hash
return not self.hash == previousfilehash
def f_filecontent(self):
try:
with open(self.assetpath, 'r') as f:
self.filecontent = f.read()
except:
raise FileWholeError(f'Unable to read file content of {self.assetpath}')
return None
class FileWholeRemote(FileHashOnly):
''' Remote files for which we record content if hash has changed
Remote file is copied to a local temp file used as target path
for this class.
'''
filecontent = GenericDescriptor()
command = GenericDescriptor()
def __init__(self, lastblock=None, **kwds):
self.f_remotefile()
super().__init__(**kwds)
# This authorid has not written a last block, OR
# assetid not present in last block, OR
# this assetid's .hash attribute has changed from value in last block
try:
if (lastblock is None or \
self.assetid not in lastblock.data.assets or \
self.hashchanged(lastblock)):
self.f_filecontent()
else:
self.filecontent = None
except:
raise FileWholeRemoteError(f'Error accessing last block by this authorid')
def hashchanged(self, lastblock):
''' Check if filehash has changed from last block
'''
if not lastblock.genesisblock:
previousfilehash = lastblock.data.assets[self.assetid].hash
return not self.hash == previousfilehash
def f_remotefile(self):
''' Retrieve remote file and store locally
'''
self.command = []
self.command.append('scp')
self.command.append('-q')
self.command.append('m4:/etc/hosts')
self.command.append('aws_hosts.temp')
kwds = {}
kwds['check'] = True
kwds['capture_output'] = True
kwds['text'] = True
try:
cp = run(self.command, **kwds)
cmdoutput = cp.stdout
returncode = cp.returncode
except CalledProcessError:
raise FileWholeRemoteError(f'scp execution failed on m4')
return None
def f_filecontent(self):
try:
with open(self.assetpath, 'r') as f:
self.filecontent = f.read()
except:
raise FileWholeRemoteError(f'Unable to read file {self.assetpath}')
return None
class Command:
''' Executable commands to monitor assets
Properties:
commandid: unique id from commandlist
host: host on which command is executed
user: user account on host used to execute command
starttime: start time of execution
endtime: time command returned
returncode: return code from executed process
output: stdout of command
'''
cmdid = GenericDescriptor()
cmdtype = GenericDescriptor()
command = GenericDescriptor()
starttime = GenericDescriptor()
endtime = GenericDescriptor()
returncode = GenericDescriptor()
cmdoutput = GenericDescriptor()
def __init__(self, cmdid=None, cmdtype=None, command=None):
self.cmdid = cmdid
self.cmdtype = cmdtype
self.command = command
self.host = gethostname()
self.user = getuser()
self.starttime = None
self.endtime = None
self.returncode = None
self.cmdoutput = None
# also used by subclasses
def __repr__(self):
return f'{self.__class__.__name__}({self.cmdid}, {self.command})'
class CmdGeneric(Command):
''' Execute user-specified command and capture output
This command is not tailored by previous invocation
'''
def __init__(self, **kwds):
super().__init__(**kwds)
self.f_generic()
def f_generic(self):
kwds = {}
kwds['shell'] = True
kwds['executable'] = '/bin/bash'
kwds['check'] = True
kwds['capture_output'] = True
kwds['text'] = True
try:
cp = run(self.command, **kwds)
self.cmdoutput = cp.stdout
self.returncode = cp.returncode
except CalledProcessError:
raise cmdgenericError(f'Unable to execute generic command on {self.host}')
return None
class CmdNetstat(Command):
''' Execute netstat command and capture output
This command is not tailored by previous invocation
'''
def __init__(self, **kwds):
super().__init__(**kwds)
self.f_netstat()
def f_netstat(self):
self.command = []
self.command.append('netstat')
self.command.append('-tupan')
kwds = {}
kwds['check'] = True
kwds['capture_output'] = True
kwds['text'] = True
try:
cp = run(self.command, **kwds)
self.cmdoutput = cp.stdout
self.returncode = cp.returncode
except CalledProcessError:
raise cmdnetstatError(f'Unable to execute netstat on {self.host}')
return None
class CmdNmap(Command):
''' Execute nmap command against target machine
'''
def __init__(self, **kwds):
super().__init__(**kwds)
self.f_nmap()
def f_nmap(self):
self.command = []
self.command.append('nmap')
self.command.append('-Pn')
self.command.append('-n')
self.command.append('-sS')
self.command.append('--top-ports')
self.command.append(f'{choice(range(2, 150))}')
self.command.append('--open')
self.command.append('10.10.3.2')
kwds = {}
kwds['check'] = True
kwds['capture_output'] = True
kwds['text'] = True
try:
cp = run(self.command, **kwds)
self.cmdoutput = cp.stdout
self.returncode = cp.returncode
except CalledProcessError:
raise cmdnmapError(f'Unable to execute nmap on {self.host}')
return None
class CmdPing(Command):
''' container for ping command and output processing functions
'''
def __init__(self, **kwds):
super().__init__(**kwds)
class CmdLast(Command):
''' Execute last command and capture output
Records logins to this machine since author's last block.
Command parameters are tailored by previous invocation
'''
def __init__(self, lastblock=None, **kwds):
super().__init__(**kwds)
self.command = []
self.command.append('last')
self.command.append('--ip')
try:
# authorid has not written a last block, OR cmdid not present in last block
if lastblock is None or self.cmdid not in lastblock.data.commands:
self.f_last()
else:
self.command.append('--since')
self.command.append(f'{strftime("%Y%m%d%H%M%S", localtime(lastblock.unixtime))}')
self.f_last()
except:
raise cmdlastError(f'Error accessing last block by this authorid')
def f_last(self):
kwds = {}
kwds['check'] = True
kwds['capture_output'] = True
kwds['text'] = True
try:
cp = run(self.command, **kwds)
self.cmdoutput = cp.stdout
self.returncode = cp.returncode
except CalledProcessError:
raise cmdlastError(f'Unable to execute cmdlast on {self.host}')
return None
class CmdUfwBlock(Command):
''' Execute journalctl command to capture UFW BLOCK events
Extracts specified records from journal since last block by author was written.
This class is an example where we don't catch subprocess.CalledProcessError
'''
def __init__(self, lastblock=None, **kwds):
super().__init__(**kwds)
self.command = []
self.command.append('journalctl')
self.command.append('-o')
self.command.append('short-unix')
self.command.append('--no-pager')
self.command.append('-n')
self.command.append('100000')
self.command.append('--quiet')
self.command.append('-g')
self.command.append('ufw block')
try:
# authorid has not written a last block, OR cmdid not present in last block
if lastblock is None or self.cmdid not in lastblock.data.commands:
self.f_journalctl()
else:
self.command.append('--since')
self.command.append(f'@{lastblock.unixtime}')
self.f_journalctl()
except:
raise cmdufwblockError(f'Error accessing last block by this authorid')
def f_journalctl(self):
''' Executes the constructed journalctl command
Does not raise CalledProcessError for non-zero exit code.
We expect a non-zero exit code of 1 if there are no new
specified journal entries. We catch any non-zero exit
codes other than 1.
'''
def filteroutput(output):
''' Filter journalctl command output as specified herein
'''
filteredoutput = ''
po = re.compile(r'''
(\d+\.\d+)
\s.+
\[UFW(\sBLOCK)\]
.+
(\sSRC=\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})
(\sDST=\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})
.+
(\sPROTO=\w+\sSPT=\d+\sDPT=\d+.+)
\n
''', flags=re.VERBOSE)
for m in re.finditer(po, output):
filteredoutput += ''.join(m.groups()) + '\n'
return filteredoutput
kwds = {}
kwds['check'] = False # set True for testing
kwds['capture_output'] = True
kwds['text'] = True
cp = run(self.command, **kwds)
self.returncode = cp.returncode
self.cmdoutput = filteroutput(cp.stdout)
# self.cmdoutput = cp.stdout
if self.returncode not in {0, 1}:
print(f'journalctl returncode = {self.returncode}')
raise cmdufwblockError(f'Unable to execute cmdjournalctl on {self.host}')
return None
class CmdSshd(Command):
''' Execute journalctl command to capture unauthorized ssh connnection attempts
Extracts specified records from journal since last block by author was written.
This class is an example where we don't catch subprocess.CalledProcessError
'''
def __init__(self, lastblock=None, **kwds):
super().__init__(**kwds)
self.command = []
self.command.append('journalctl')
self.command.append('-o')
self.command.append('short-unix')
self.command.append('--no-pager')
self.command.append('-n')
self.command.append('1000')
self.command.append('--quiet')
self.command.append('_SYSTEMD_UNIT=ssh.service')
try:
# authorid has not written a last block, OR cmdid not present in last block
if lastblock is None or self.cmdid not in lastblock.data.commands:
self.f_journalctl()
else:
self.command.append('--since')
self.command.append(f'@{lastblock.unixtime}')
self.f_journalctl()
except:
raise cmdsshdError(f'Error accessing last block by this authorid')
def f_journalctl(self):
''' Executes the constructed journalctl command
Does not raise CalledProcessError for non-zero exit code.
We expect a non-zero exit code of 1 if there are no new
specified journal entries. We catch any non-zero exit
codes other than 1.
'''
def filteroutput(output):
''' Filter journalctl output as specified herein
'''
filteredoutput = ''
po = re.compile(r'''
(\d+\.\d+\s)
\S+
\s
(sshd.+:\s)
(Invalid.+|error.+|Unable.+|Disconnecting.+)
\n
''', flags=re.VERBOSE)
for m in re.finditer(po, output):
filteredoutput += ''.join(m.groups()) + '\n'
return filteredoutput
kwds = {}
kwds['check'] = False # set True for testing
kwds['capture_output'] = True
kwds['text'] = True
cp = run(self.command, **kwds)
self.returncode = cp.returncode
self.cmdoutput = filteroutput(cp.stdout)
if self.returncode not in {0, 1}:
print(f'journalctl returncode = {self.returncode}')
raise cmdsshdError(f'Unable to execute cmdjournalctl on {self.host}')
return None
class BlockData:
''' class for block data
This class defines properties & methods of the data portion of a block.
This class is implements two dictionaries, assets and commands,
which hold the data of a block.
Instances of this class become the value of block.data,
a property of a block instance, Block()
blockdatainstance = BlockData()
blockinstance = Block()
blockinstance.data = blockdatainstance
'''
assets = GenericDescriptor()
commands = GenericDescriptor()
def __init__(self, assetlist=[], commandlist=[]):
''' Instantiate and populate with assets and commands
Called from main()
Input:
Asset instances parsed from assetlist csv file
Command instances parsed from commandlist csv file
Output:
A single blockdata instance for use in construction of a block
'''
self.assets = {}
self.commands = {}
for asset in assetlist:
self.appendasset(asset)
for command in commandlist:
self.appendcommand(command)
def __repr__(self):
return f'{self.__class__.__name__}({len(self.assets)} assets, {len(self.commands)} commands)'
def appendasset(self, asset):
''' Adds an asset instance to blockdata.assets dict
assetid is used as dictionary key
'''
self.assets[asset.assetid] = asset
return None
def appendcommand(self, command):
''' Adds a command instance to blockdata.commands dict
cmdid is used as dictionary key
'''
self.commands[command.cmdid] = command
return None
class Block:
''' class for block
This class defines the properties and methods of a block.
Instances of this class are blocks, stored in a property of blockchain
blockinstance = Block()
blockchain.blocks.append(blockinstance)
'''
blocknumber = GenericDescriptor()
authorid = GenericDescriptor()
previousblockhash = GenericDescriptor()
genesisblock = GenericDescriptor()
unixtime = GenericDescriptor()
datetime = GenericDescriptor()
tz = GenericDescriptor()
tzoffset = GenericDescriptor()
nonce = GenericDescriptor()
data = GenericDescriptor()
comment = GenericDescriptor()
sig = GenericDescriptor()
def __init__(self):
''' Construct a skeleton block instance
'''
self.blocknumber = None
self.authorid = None
self.previousblockhash = None
self.genesisblock = False
self.unixtime = None
self.datetime = None
self.tz = None
self.tzoffset = None
self.nonce = None
self.data = None
self.comment = None
self.sig = None
def __repr__(self):
return f'{self.__class__.__name__}({self.blocknumber}, {self.authorid})'
def computeblocksig(self, skfile=None):
''' Compute signature over a populated block using author's signing_key
Called from BlockChain.makenextblock(). This function is a method of
Block() because it depends on an incomplete block i.e. a block that is
in the process of being constructed, whereas the methods of
BlockChain() mainly act upon existing blocks in the blockchain.
All block properties, except block.sig, are serialized into a BytesIO
object and the sig is computed on its value.
Inputs:
Path to a file containing the private signing key as bytes.
Output:
A base64 encoded signature
'''
if skfile is None:
raise computeblocksigError(f'No block signing key specified')
try:
bytes_to_sign = self.bytestosign()
except:
raise computeblocksigError('No bytes to sign')
try:
with open(skfile, 'rb') as f:
skbytes = f.read()
sk = signing.SigningKey(skbytes)
except:
raise computeblocksigError(f'Unable to open signing key file {skfile}')
try:
signed = sk.sign(bytes_to_sign)
signature = signed.signature
except:
raise computeblocksigError('Error creating signature')
return b64encode(signature)
def bytestosign(self):
''' Serialize block attributes for signing and verifying operations
Constructs a bytes object over which a signature will be computed or verified.
Concatenates pickles of all block attribute values except self.sig
Output:
Returns a serialized bytes object of concatenated pickles
'''
signlist = [self.blocknumber,
self.authorid,
self.previousblockhash,
self.genesisblock,
self.unixtime,
self.datetime,
self.tz,
self.tzoffset,
self.nonce,
self.data,
self.comment]
return serialize(signlist)
class BlockChain:
''' class for blockchain
This class defines the properties and methods of the blockchain.
Only one instance of this class exists.
This sole instance contains the entire blockchain.
This instance object is saved as a pickle file.
bc = BlockChain()
bc.blocks.append(block)
'''
blocks = GenericDescriptor()
blockcount = GenericDescriptor() # length of blockchain
totaldatasize = GenericDescriptor()
head = GenericDescriptor() # last block number
def __init__(self):
''' only called to instantiate a new blockchain
'''
self.blocks = []
self.blockcount = 0
self.totaldatasize = None
self.head = None
self.addnewblock(self.genesis())
def __repr__(self):
return f'{self.__class__.__name__}({self.blockcount} blocks, head = {self.head})'
def genesis(self):
''' constructs the genesis block
Called by __init__ when instantiating a new blockchain
Output:
The signed genesis block
'''
try:
genesisblock = Block()
genesisblock.blocknumber = 0
genesisblock.authorid = AUTHORIDGENESIS
genesisblock.previousblockhash = 0
genesisblock.genesisblock = True
genesisblock.nonce = randbits(64)
genesisblock.data = BlockData() # could be None
genesisblock.unixtime = time()
genesisblock.datetime = ctime(genesisblock.unixtime)
genesisblock.tz = localtime(genesisblock.unixtime).tm_zone
genesisblock.tzoffset = strftime('%z', localtime(genesisblock.unixtime))
genesisblock.comment = f'Genesis block created by admin on {genesisblock.datetime}'
genesisblock.sig = genesisblock.computeblocksig(skfile=SIGNINGKEYFILEGENESIS)
except:
raise genesisError('Error making genesis block')
return genesisblock
def makenextblock(self, block=None, authorid=None):
''' Constructs the next block to be added to blockchain
Assigns values to block properties. Signing the block is performed by
assiging the computed signature to block.sig. This completes the
creation of a block, which can then be added to blockchain.
Called from main()
Input:
A block instance for which only .data attribute has been set in main()
The authorid identifying the author and signer of this block
Output: