-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathgrasp.py
4881 lines (4289 loc) · 180 KB
/
grasp.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
"""########################################################
########################################################
#
# Generic Autonomic Signaling Protocol (GRASP)
#
# GRASP engine and experimental API
#
# Module name is 'grasp'
#
# This is a prototype/demo implementation of GRASP. It was
# developed using Python 3.4 and above.
#
# It is based on RFC8990. The API is not fully compatible
# with RFC8991; for that, use the module graspi.py, which
# imports this module.
#
# This code is not guaranteed or validated in any way and is
# both incomplete and probably wrong. It makes no claim
# to be production-quality code. Its main purpose is to
# help validate the protocol specification.
#
# Because it's demonstration code written in an
# interpreted language, performance is slow.
#
# SECURITY WARNINGS:
# - assumes ACP up on all interfaces (or none)
# - does not watch for interface up/down changes
# - no support for wrapping TCP in TLS
# - it is strongly recommended to use the built-in QUADS security
# unless a truly secure ACP is available
#
# LIMITATIONS:
# - only coded for IPv6, no IPv4 support
# - survival of address changes and CPU sleep/wakeup is patchy
# - FQDN and URI locators incompletely supported
# - no code for handling rapid mode negotiation
# - relay code is lazy (no rate control)
# - workarounds for defects in Python socket module and
# Windows socket peculiarities. Not tested on Android.
#
# Released under the BSD "Revised" License as follows:
#
# Copyright (C) 2015-2023 Brian E. Carpenter.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with
# or without modification, are permitted provided that the
# following conditions are met:
#
# 1. Redistributions of source code must retain the above
# copyright notice, this list of conditions and the following
# disclaimer.
#
# 2. Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials
# provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of
# its contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
# AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
# THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
########################################################
########################################################"""
_version = "RFC8990-BC-20230226"
##########################################################
# The following change log records significant changes,
# not small bug fixes, in older versions.
# Version 05 added proto/port to discovery responses
# 1. Update constants for revised CDDL
# 2. Add fields to discovered locator (class asa_locator) and objective
# registry (class _registered_objective)
# 3. Add option code and fields in response messages
# 4. Update generation and parsing of response messages accordingly
# 5. Change from a global TCP listener to a per-objective TCP listener
# 6. Change register_objective to obtain a TCP port and socket and
# launch its own listener
# 7. Make this listener exit if the objective is deregistered (but only
# if new requests come in, otherwise it sleeps harmlessly for ever)
# 20160601 Added discovery cache timeout, and detection of address changes
# 20160605 Added partial recovery after system sleep
# 20160619 Fixed to allow reentrant calls to listen_neg (and listen_syn)
# Version 06 added no protocol changes
# Version 07 added ttl & locator to flood cache entries, and ttl to discovery response
# 20161003 added bubble output option with tkinter
# Version 08 added partial support of M_INVALID
# Version 09 added the F_NEG_DRY flag, modified M_FLOOD format
# 20170122 added Flag24 handling to API
# 20170124 changed error returns to integers (incompatible change to API)
# 20170221 changed session nonce to store packed locator insted of IPv6Address
# 20170224 improved flag bit handling
# 20170429 port 7017 assigned
# 20170518 added interactive choice of test mode (instead of countdown)
# 20170528 fixed several bugs in discovery relaying
# Version 13 improved calculation of discovery timeouts
# 20170604 added initialisation deferral
# Version 15 should conform to RFC-to-be
# 20170721 multicast addresses ff02::13 and 224.0.0.119 assigned
# 20170819 improved handling for long messages
# 20170824 added skip_dialogue() to API
# 20170929 added send_invalid() to API
# 20171003 added inbound message checking option, fixed bug in M_FLOOD format
# 20171013 replaced inbound checking by full parsing, and use parsed
# messages wherever possible
# 20171023 updated _ass_message() to use 'option' class,
# added multiple locators to M_RESPONSE and O_DIVERT,
# added rapid mode objective to M_RESPONSE
# updated register_obj() and synchronize() APIs accordingly
# 20190126 restructure to put IP address/interface discovery
# in the ACP module. There are now no operating system
# dependencies in the grasp.py module (although some
# may be hidden in imported Python modules).
# 20190206 added socket timeouts when sending discovery responses
# or request messages, since there should always be a listener
# 20190410 improved flood() to allow all locator types
# (based on patch from Robin Jaeger)
# 20190724 added exception handler to _mchandler to increase robustness
# 20190912 inserted diagnostics for _mchandler hang
# 20190913 fixed lock bug in _mchandler for expired discovery
# 20190925 commented out diagnostics for _mchandler hang
# 20191017 added QUADS crypto
# 20191025 made all threads daemonic to force proper exit
# 20191102 improved password entry code
# 20191113 added gsend() and grecv()
# 20200408 fixed historic bug in flood()
# 20200913 improved interaction between acp.status() and security checks
# 20200920 added DULL flag and behaviour
# 20210105 started API upgrade to draft-ietf-anima-grasp-api-10
# (aka API RFC)
# - tweaked default objective.value to None
# - renamed nonces as handles in API
# - fixed a printing bug
# 20210106 - added overlap parameter to register_obj
# 20210109 - added minimum_TTL parameter to discover
# - documented remaining deviations from API RFC
# 20210110 - renamed snonce as shandle throughout
# - cleaned up naming of some globals, classes and functions
# to tidy up the 'help' results
# 20210111 - cleaned up help texts
# - did all remaining s/nonce/handle/
# - made flood() RFC-compatible
# 20210112 - cosmetic improvements
# 20210115 - added partial option to dump_all()
# 20210118 - tweak to allow "No key" bypass
# 20210205 - graceful behaviour if import cryptography fails
# 20210306 - store interface index with flooded objective
# 20210309 - allow for objectives with F_DISC = 0
# 20210722 - corrected Tag 24 handling
# 20210820 - prefer cbor2 over cbor (more error handling)
# - allow receiving long unicast messages
# - separate max message size settings
#
# 20210826 - fixed off-by-one in loop count check
#
# 20210918 - fixed bug in flood expiry for floods with no locator
#
# 20210919 - added experimental _figger ASA (self-configuration ASA)
#
# 20210920 - added "ask" options to skip_dialogue(), removed "quadsing" parameter
#
# 20211010 - fixed dependency on CBOR library tag handling
# - tuned startup dialogue defaults
#
# 20211014 - fixed Linux-only bug in CBORTag usage
#
# 20211015 - cosmetic improvement in cbor vs cbor2 usage
#
# 20220316 - fixed grievous bug in O_DIVERT format and other related bugs
# - added duplicate detection when storing locator in discovery cache
#
# 20220429 - ignore cache entries discovered on same interface
#
# 20230224 - parser bug if objective contains no value
#
# 20230226 - missing initialisation (for corner case)
#
##########################################################
####################################
# #
# Python version check #
# #
####################################
import sys
if sys.version_info[0] < 3 or \
(sys.version_info[0] == 3 and sys.version_info[1]) < 4:
raise RuntimeError("Must use Python 3.4 or later")
# Each ASA starts with "import graspi" for the RFC8991 API,
# or "import grasp" for the old API.
# List of main classes and functions included in the grasp.py API:
def init(self):
__all__ = ['objective', 'asa_locator', 'tagged_objective',
'register_asa', 'deregister_asa', 'register_obj',
'deregister_obj', 'discover',
'req_negotiate', 'negotiate_step', 'negotiate_wait',
'end_negotiate', 'listen_negotiate', 'stop_negotiate',
'synchronize', 'listen_synchronize', 'stop_synchronize',
'flood', 'get_flood', 'expire_flood']
####################################
# #
# Imports #
# #
####################################
import time
import errno
import threading
import queue
import socket
import struct
import ipaddress
import ssl
import random
import binascii
import copy
import traceback
### for bubbles
try:
import tkinter as tk
from tkinter import font
except:
print("Could not import tkinter. No pretty printing.")
time.sleep(10)
###
try:
import cbor2 as cbor
from cbor2 import CBORTag
except:
print("Could not import cbor2. Will try to import cbor instead.")
time.sleep(5)
try:
import cbor
from cbor import Tag as CBORTag
except:
print("Could not import cbor. Please do 'pip3 install cbor2' and try again.")
time.sleep(10)
exit()
try:
import acp
except:
print("Could not import acp. Please copy acp.py to the current directory and try again.")
time.sleep(10)
exit()
#imports for QUADS
import os
import getpass
_cryptography = False
try:
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
_cryptography = True
except:
pass
#check for latest ACP
try:
acp.new2019()
except:
print("Please update acp.py to the 2019 version and try again.")
time.sleep(10)
exit()
#work-around for Python system error
try:
socket.IPPROTO_IPV6
except:
socket.IPPROTO_IPV6 = 41
#########################################
# A very handy function...
#########################################
def tname(x):
"""-> name of type of x"""
return type(x).__name__
####################################
# #
# Data types and global data #
# #
####################################
####################################
# ASA registry #
####################################
class _asa_instance:
"""Internal use only"""
def __init__(self, handle, name):
self.handle = handle #the ASA's handle
self.name = name #the ASA's name string
# _asa_registry - list of _asa_instance
# _asa_lock - lock for _asa_registry
####################################
# Objectives & registry #
####################################
class objective:
"""
A GRASP objective:
.name String
.neg True if objective supports negotiation
.dry True if objective supportd dry-run negotiation
.synch True if objective supports synchronization
.loop_count Limit on negotiation steps etc.
.value A valid Python object
"""
def __init__(self, name):
self.name = name #Unique name, string
self.discoverable = True #Set False if unwanted (unusual!)
self.neg = False #Set True if objective supports negotiation
self.dry = False #Set True if objective also supports dry-run negotiation
self.synch = False #Set True if objective supports synch
self.loop_count = GRASP_DEF_LOOPCT #Default starting value
self.value = None #Place holder; format undefined
def _oclone(obj):
"""Internal use only"""
###################################################
# Clones an objective for local use
# If you don't use this, you may unintenionally
# modify the caller's objective
# Just do obj=_oclone(obj)
###################################################
cobj=objective(obj.name)
cobj.neg=obj.neg
cobj.dry=obj.dry
cobj.synch=obj.synch
cobj.loop_count=obj.loop_count
cobj.value=obj.value
return cobj
class _registered_objective:
"""Internal use only"""
def __init__(self, objective, asa_handle):
self.objective = objective
self.asa_id = [asa_handle]
self.overlap_OK = False
self.protocol = socket.IPPROTO_TCP #default
self.locators = [] #list of explicit locators, if any
self.port = 0
self.discoverable = False # not discoverable until first listening
self.local = False # link-local iff True
self.rapid = False # support rapid mode iff True
self.ttl = _discCacheDefTimeOut # discovery cache timeout in milliseconds
self.listening = 0 # counts active listeners
self.listen_q = None
# _obj_registry - list of _registered_objective
# _obj_lock - lock for _obj_registry
####################################
# Discovery cache #
####################################
class _discovered_objective:
"""Internal use only"""
def __init__(self, objective, asa_locators):
self.objective = objective
self.asa_locators = asa_locators #list of asa_locator
self.received = None #objective received in M_RESPONSE
class asa_locator:
"""
Locator for a discovered peer ASA, also used for flooded objectives.
Values:
.locator The actual locator
.protocol Transport protocol number
.port Port number
.ifi Interface identifier via which this was discovered
.expire int(time.monotonic()) value when this entry expires (0=never)
Booleans:
.diverted
.is_ipaddress
.is_fqdn
.is_uri
"""
def __init__(self, locator, ifi, diverted):
self.locator = locator
self.ifi = ifi # Remember which interface this came from
self.diverted = diverted # True iff it was in a Divert option
#Defaults
self.protocol = socket.IPPROTO_TCP
self.port = GRASP_LISTEN_PORT
self.expire = 0
#One of the following must be set when the object is created
#Addresses to be stored in Python ipaddress class
self.is_ipaddress = False
self.is_fqdn = False
self.is_uri = False
# _discovery_cache - list of _discovered_objective
# _disc_lock - lock for _discovery_cache
####################################
# Session ID cache #
####################################
class _session_instance:
"""Internal use only"""
def __init__(self, id_value, id_active, id_source):
self.id_value = id_value #Integer
self.id_active = id_active #True if active
self.id_source = id_source #Source locator of ID if needed (packed)
self.id_dq = None #Queue if discovering
self.id_sock = None #Socket if negotiating
self.id_relayed = False #True if has been relayed
class _session_handle:
"""Internal use only"""
def __init__(self, id_value, id_source):
self.id_value = id_value #Integer
self.id_source = id_source #Source locator of ID if non-local (packed)
# _session_id_cache - list of _session_instance
# _sess_lock - lock for _session_id_cache
# Session_ID cache contains
# - all currently active Session_IDs
# - foreign source address if any
# - status for each one (in use or inactive)
# - as memory permits, all previously seen Session_IDs (status inactive) to avoid reuse
####################################
# Flood cache #
####################################
class tagged_objective:
"""
An objective tagged with its source asa_locator:
.objective the objective
.source an asa_locator (including expiry time) or None
"""
def __init__(self, objective, source):
self.objective = objective
self.source = source # an asa_locator (including expiry time)
# _flood_cache - list of tagged_objective
# _flood_lock - lock for _flood_cache
# Flood cache contains flooded objectives with their values and tagged
# with their source address
####################################
# Classes for message parsing #
####################################
class _flooded_objective:
"""
An objective embedded in a flood:
.obj the objective
.loco its locator option, or None
"""
def __init__(self, obj, loco):
self.obj = obj #an objective
self.loco = loco #associated locator option
class _message:
"""
A GRASP message:
.mtype message type, integer
.id_value session ID, integer
.id_source source address (packed)
.ttl ttl or waiting time (ms)
.options list of embedded option
.obj embedded objective
.flood_list list of _flooded_objective
.content arbitrary content
"""
def __init__(self, mtype):
self.mtype = mtype #message type, integer
self.id_value = 0 #session ID, integer
self.id_source = _unspec_address.packed #source address
self.ttl = 0 #ttl or waiting time, integer
self.options = [] #list of options
self.obj = None #embedded objective
self.flood_list = None #list of _flooded_objective
self.content = None #arbitrary content
class _option:
"""
A GRASP option:
.otype option type, integer
.embedded embedded option if any
.locator if locator option: packed address or string
.protocol if locator option: protocol #
.port if locator option: port #
.reason if decline option: reason string
"""
def __init__(self, otype):
self.otype = otype #option type, integer
self.embedded = [] #list of embedded options (if any)
self.locator = None #if locator option: packed address
#or string
self.protocol = 0 #if locator option: protocol #
self.port = 0 #if locator option: port #
self.reason = None #if decline option: reason string
####################################
# Other global variables #
# #
# Reminder: any of these that get #
# assigned inside any function or #
# thread must be declared 'global' #
# inside that function #
####################################
_grasp_initialised = False #true after GRASP core has been initialised
_skip_dialogue = False #true if ASA calls grasp.skip_dialogue
# _tls_required #true if neither ACP nor QUADS is secure
# _crypto #true if QUADS is secure
# _secure #true if either ACP or TLS or QUADS is secure
# _rapid_supported #true if rapid mode allowed
# _mcq #FIFO for incoming multicasts
# _drq #FIFO for pending discovery responses
# _my_address #this node's preferred global address
# _my_link_local #this node's preferred link local address
# _session_locator #address used to disambiguate session ids (if initiator field used)
# _ll_zone_ids #list of [IPv6 Zone (interface) index,LL address]
# _said_no_route #flag used by watcher to limit printing
# _mcssocks #list of multicast sending sockets
# _relay_needed #True if multiple interfaces require Discovery/Flood relaying
# _mc_restart #True if system wakeup detected - multicast listeners must restart
# _i_sent_it #session ID of most recent discovery multicast, used in a hack
# _multi_asas #flag used by ASA loader
# test_mode #True iff module is running in test mode
# _listen_self #True iff listening to own LL multicasts for testing
# _test_divert #True to force a divert message from discovery
# _mess_check #True to trigger message check diagnostics
# _make_invalid #True to throw a test M_INVALID
# _make_badmess #True to throw a malformed message
# _dobubbles #True to enable bubble printing
####################################
# GRASP protocol constants #
####################################
# Note: there is no reasonable way to define constants in Python.
# These objects could all be overwritten by programming errors.
M_NOOP = 0
M_DISCOVERY = 1
M_RESPONSE = 2
M_REQ_NEG = 3
M_REQ_SYN = 4
M_NEGOTIATE = 5
M_END = 6
M_WAIT = 7
M_SYNCH = 8
M_FLOOD = 9
M_INVALID = 99
O_DIVERT = 100
O_ACCEPT = 101
O_DECLINE = 102
O_IPv6_LOCATOR = 103
O_IPv4_LOCATOR = 104
O_FQDN_LOCATOR = 105
O_URI_LOCATOR = 106
F_DISC = 0 # valid for discovery
F_NEG = 1 # valid for negotiation
F_SYNCH = 2 # valid for synchronization
F_NEG_DRY = 3 # negotiation is dry-run
ALL_GRASP_NEIGHBORS_6 = ipaddress.IPv6Address('ff02::13') # LL multicast
ALL_GRASP_NEIGHBORS_4 = ipaddress.IPv4Address('224.0.0.119') # LL multicast
GRASP_LISTEN_PORT = 7017 # IANA port number
GRASP_DEF_TIMEOUT = 60000 # milliseconds
GRASP_DEF_LOOPCT = 6
GRASP_DEF_MAX_SIZE = 2048 # max message size
_multicast_size = GRASP_DEF_MAX_SIZE
_unicast_size = GRASP_DEF_MAX_SIZE
_unspec_address = ipaddress.IPv6Address('::') # Used in special cases
# to indicate link local
####################################
# Support for flag bits #
####################################
def _bit(b):
"""Return integer with bit b on"""
return 2**b
B_DISC = _bit(F_DISC)
B_NEG = _bit(F_NEG)
B_SYNCH = _bit(F_SYNCH)
B_DRY = _bit(F_NEG_DRY)
def _flagword(obj):
"""Create the flags word for an objective"""
_f = 0
if obj.discoverable:
_f = B_DISC
if obj.neg:
_f |= B_NEG
if obj.synch:
_f |= B_SYNCH
if obj.dry:
_f |= B_DRY
return _f
def _flags(flagword):
"""Internal use only"""
#return Boolean flags for an objective
return bool(flagword&B_NEG), bool(flagword&B_SYNCH), \
bool(flagword&B_DRY)
####################################
# GRASP engine internal constants #
####################################
_asaRegistryLimit = 100
_sessionCacheLimit = _asaRegistryLimit + 1000
_objRegistryLimit = 200
_discCacheLimit = 500
_discCacheDefTimeOut = 10*GRASP_DEF_TIMEOUT # milliseconds
_floodCacheLimit = 100
_discQlimit = 10
_listenQlimit = 5
_multQlimit = 100
_minRelayGap = 500 # milliseconds (unused, intended for relay throttling)
_discTimeoutUnit = 100 # milliseconds (discovery timeout per hop)
####################################
# List offsets for raw message #
# contents (for poor man's parsing)#
# #
# These constants are used only in #
# the various _parse_ functions, #
# _relay() and _ass_message() #
####################################
_Op_Opt = 0 #option code in an option
_Op_Con = 1 #first specific item in an option
_Op_Proto = 2 #protocol number in a locator option
_Op_Port = 3 #port number in a locator option
_Pl_Msg = 0 #message type in a message payload
_Pl_Ses = 1 #session ID in a message payload
_Pl_Ini = 2 #initiator in a message payload
_Pl_Con = 2 #first specific item in a normal message payload
_Pl_TTL = _Pl_Ini+1 #TTL in response or flood payload
_Pl_Rloc = _Pl_TTL+1 #locator option in response payload
_Pl_Robj = _Pl_Rloc+1 #objective in response payload
_Pl_FCon = _Pl_TTL+1 #list of [locator,objective] in flood payload
_Pl_Dobj = _Pl_Ini+1 #objective in discovery payload
_Fo_Fobj = 0 #objective in tagged objective in flood
_Fo_Floc = 1 #locator in tagged objective in flood
_Ob_Nam = 0 #name in an objective
_Ob_Flg = 1 #flags in an objective
_Ob_LCt = 2 #loop count in an objective
_Ob_Val = 3 #value object in an objective
####################################
# Error codes and English-language #
# error texts #
####################################
class _error_codes:
"""names for the error codes"""
def __init__(self):
self.ok = 0
self.declined = 1 #"Declined"
self.noReply = 2 #"No reply"
self.unspec = 3 #"Unspecified error"
self.ASAfull = 4 #"ASA registry full"
self.dupASA = 5 #"Duplicate ASA name"
self.noASA = 6 #"ASA not registered"
self.notYourASA = 7 #"ASA registered but not by you"
self.notBoth = 8 #"Objective cannot support both negotiation and synchronization"
self.notDry = 9 #"Dry-run allowed only with negotiation"
self.notOverlap = 10 #"Overlap not supported by this implementation"
self.objFull = 11 #"Objective registry full"
self.objReg = 12 #"Objective already registered"
self.notYourObj = 13 #"Objective not registered by this ASA"
self.notObj = 14 #"Objective not found"
self.notNeg = 15 #"Objective not negotiable"
self.noSecurity = 16 #"No security"
self.noDiscReply = 17 #"No reply to discovery"
self.sockErrNegRq = 18 #"Socket error sending negotiation request"
self.noSession = 19 #"No session"
self.noSocket = 20 #"No socket"
self.loopExhausted = 21 #"Loop count exhausted"
self.sockErrNegStep = 22 #"Socket error sending negotiation step"
self.noPeer = 23 #"Negotiation peer not listening"
self.CBORfail = 24 #"CBOR decode failure"
self.invalidNeg = 25 #"Invalid Negotiate message"
self.invalidEnd = 26 #"Invalid end message"
self.noNegReply = 27 #"No reply to negotiation step"
self.noValidStep = 28 #"No valid reply to negotiation step"
self.sockErrWait = 29 #"Socket error sending wait message"
self.sockErrEnd = 30 #"Socket error sending end message"
self.IDclash = 31 #"Incoming request Session ID clash"
self.notSynch = 32 #"Not a synchronization objective"
self.notFloodDisc = 33 #"Not flooded and no reply to discovery"
self.sockErrSynRq = 34 #"Socket error sending synch request"
self.noListener = 35 #"Synchronization peer not listening"
self.noSynchReply = 36 #"No reply to synchronization request"
self.noValidSynch = 37 #"No valid reply to synchronization request"
self.invalidLoc = 38 #"Invalid locator"
self.sockErr = 39 #"Socket error sending gmessage"
errors = _error_codes()
etext = ["OK",
"Declined",
"No reply",
"Unspecified error",
"ASA registry full",
"Duplicate ASA name",
"ASA not registered",
"ASA registered but not by you",
"Objective cannot support both negotiation and synchronization",
"Dry-run allowed only with negotiation",
"Overlap not supported by this implementation",
"Objective registry full",
"Objective already registered",
"Objective not registered by this ASA",
"Objective not found",
"Objective not negotiable",
"No security",
"No reply to discovery",
"Socket error sending negotiation request",
"No session",
"No socket",
"Loop count exhausted",
"Socket error sending negotiation step",
"Negotiation peer not listening",
"CBOR decode failure",
"Invalid Negotiate message",
"Invalid end message",
"No reply to negotiation step",
"No valid reply to negotiation step",
"Socket error sending wait message",
"Socket error sending end message",
"Incoming request Session ID clash",
"Not a synchronization objective",
"Not flooded and no reply to discovery",
"Socket error sending synch request",
"Synchronization peer not listening",
"No reply to synchronization request",
"No valid reply to synchronization request",
"Invalid locator"
"Socket error sending gmessage"
]
#############################################
# #
# QUick And Dirty Secrecy for GRASP (QUADS) #
# #
#############################################
#Global variables for QUADS
_qsalt = b'\xf4tRj.t\xac\xce\xe1\x89\xf1\xfb\xc1\xc3L\xeb'
_crypto = False
_key = 0
_iv = 0
_cipher = None
def _ini_crypt(key=None, iv=None):
"""Internal use only; gets passsword and enables crypto"""
global _crypto, _key, _iv, _qsalt, _cipher, _cryptography
if not _cryptography:
tprint("Could not import cryptography: GRASP is insecure.")
return
elif not key:
password = None
confirm = 1
print("Please enter the keying password for the domain.")
while password != confirm:
password = bytes(getpass.getpass(), 'utf-8')
confirm = bytes(getpass.getpass("Confirm:" ), 'utf-8')
if password != confirm:
print("Mismatch, try again.")
if password == b'':
print("Encryption off: GRASP is insecure.")
return
else:
print("Password accepted")
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=_qsalt,
iterations=100000,
backend=default_backend()
)
_key = kdf.derive(password)
_skip = _key[0]%10
_iv = _key[_skip:_skip+16]
elif key == "No key":
tprint("No encryption key: GRASP is insecure.")
return
else:
#use configured keys
_key = key
_iv = iv
#print("Keys: ", _key, _iv)
backend = default_backend()
_cipher = Cipher(algorithms.AES(_key), modes.CBC(_iv), backend=backend)
_crypto = True
return
def _encrypt_msg(raw):
"""Returns encrypted bytes"""
global _cipher, _crypto
if not _crypto:
return raw
padder = padding.PKCS7(128).padder()
encryptor = _cipher.encryptor()
msg = padder.update(raw) + padder.finalize()
return encryptor.update(msg) + encryptor.finalize()
def _decrypt_msg(crypt):
"""Returns decrypted bytes"""
global _cipher, _crypto
if not _crypto:
return crypt
decryptor = _cipher.decryptor()
unpadder = padding.PKCS7(128).unpadder()
return unpadder.update(decryptor.update(crypt)) + unpadder.finalize()
####################################
# #
# Registration functions #
# #
####################################
####################################
#
# Tell GRASP to skip initial dialogue
#
####################################
def skip_dialogue(testing=False, selfing=False, diagnosing=True,
quadsing=True, be_dull=False):
"""
####################################################################
# skip_dialogue(testing=False, selfing=False, diagnosing=True,
# be_dull=False)
#
# A utility function that tells GRASP to skip some or all of its
# initial dialogue. Each parameter may be True, False or the string "ask".
# Default is:
# not test mode
# not listening to own multicasts
# printing message syntax diagnostics
# and not DULL
#
# Must be called before register_asa()
#
# No return value
#
# The quadsing parameter is obsolete (defined for compatibility)
####################################################################
"""
global _skip_dialogue, test_mode, _listen_self, _mess_check, _grasp_initialised, DULL, _be_dull
if _grasp_initialised:
return
_skip_dialogue = True
test_mode = testing
_listen_self = selfing
_mess_check = diagnosing
_be_dull = be_dull #too early to set the actual DULL flag
def register_asa(asa_name):
"""
####################################################################
# register_asa(asa_name)
#
# Tells the GRASP engine that a new ASA is starting up.
# Also triggers GRASP initialisation if needed.
#
# return zero, asa_handle if successful
# return errorcode, None if failure
#
# Note - the ASA must store the asa_handle (an opaque Python object)
# and use it in every subsequent GRASP call.
####################################################################
"""
if not _grasp_initialised:
_initialise_grasp()
_asa_lock.acquire()
if len(_asa_registry) >= _asaRegistryLimit:
# no free space, fail
_asa_lock.release()
return errors.ASAfull, None
elif ([clash for clash in _asa_registry if clash.name == asa_name]):
# duplicate, fail
_asa_lock.release()