def get_dns_info(dom): """Obtain and return all DNS-SD records for a domain""" global obj3 global failct #start of a negotiating session obj3.value = dom obj3.loop_count = 10 #allows for some fragmentation # As a random test, use CBOR (Tag 24) format for value (should work) if not grasp._prng.randint(0, 3): _cbor = True else: _cbor = False # As a random test, request dry run (should fail) if not grasp._prng.randint(0, 7): obj3.dry = True # random error for testing purposes else: obj3.dry = False grasp.tprint("Asking for", obj3.value, "; dry run", obj3.dry, "; Tag 24", _cbor) #discover a peer if failct > 3: failct = 0 grasp.tprint("Flushing", obj3.name, "discovery") _, ll = grasp.discover(asa_nonce, obj3, 1000, flush=True) else: _, ll = grasp.discover(asa_nonce, obj3, 1000) if ll == []: grasp.tprint("Discovery failed") failct += 1 return grasp.ttprint("Discovered locator", ll[0].locator) #attempt to negotiate if _cbor: #CBORise the value obj3.value = cbor.dumps(obj3.value) reply = [] err, snonce, answer = grasp.req_negotiate(asa_nonce, obj3, ll[0], None) if err: if err == grasp.errors.declined and answer != "": _e = answer else: _e = grasp.etext[err] grasp.tprint("req_negotiate error:", _e) failct += 1 grasp.tprint("Fail count", failct) time.sleep(5) #to calm things if there's a looping error elif (not err) and snonce: grasp.ttprint("requested, session_nonce:", snonce, "answer", answer) _found_cbor = False if _cbor: answer.value, _found_cbor = detag(answer.value) grasp.ttprint("Received reply", answer.value) if _cbor != _found_cbor: #Anomaly, get me out of here grasp.tprint("CBOR anomaly 1 - missing segment?") grasp.end_negotiate(asa_nonce, snonce, False, reason="CBOR anomaly 1 - missing segment?") elif not grasp._prng.randint(0, 7): ####################################################### # As a random test of robustness, send a bogus response answer.value = "rubbish" grasp.tprint("Sending rubbish") if _cbor: #CBORise the value answer.value = cbor.dumps(answer.value) err, temp, answer = grasp.negotiate_step(asa_nonce, snonce, answer, 1000) grasp.ttprint("Reply to rubbish:", err, temp, answer) _found_cbor = False if _cbor and (not err): answer.value, _found_cbor = detag(answer.value) if (not err) and temp == None: grasp.tprint("Unexpected answer:", answer.value) elif (not err) and _cbor != _found_cbor: grasp.tprint("CBOR anomaly 2 - missing segment?") elif not err: grasp.tprint("Loop count", answer.loop_count, "unexpected answer", answer.value) err = grasp.end_negotiate(asa_nonce, snonce, False, reason="Unexpected answer") if err: grasp.tprint("end_negotiate error:", grasp.etext[err]) else: #other end rejected if err == grasp.errors.declined and answer != "": _e = answer else: _e = grasp.etext[err] grasp.tprint("Peer reject:", _e) # End of random test of robustness ####################################################### else: #Received answer looping = True while looping: grasp.ttprint("Answer is", answer.value) if 'MORE' in answer.value: #need to go again reply += answer.value[:answer.value.index('MORE')] answer.value = "ACK" grasp.tprint("Sending ACK for more") if _cbor: #CBORise the value answer.value = cbor.dumps(answer.value) err, temp, answer = grasp.negotiate_step( asa_nonce, snonce, answer, 1000) if err: grasp.tprint("negotiate_step error:", grasp.etext[err]) looping = False elif _cbor: answer.value, _found_cbor = detag(answer.value) if _cbor != _found_cbor: #anomaly, get me out of here looping = False grasp.end_negotiate( asa_nonce, snonce, False, reason="CBOR anomaly - missing segment?") grasp.tprint("CBOR anomaly 3 - missing segment?") grasp.ttprint("Reply to ACK:", err, temp, answer) else: looping = False reply += answer.value err = grasp.end_negotiate(asa_nonce, snonce, True) if not err: if len(reply): grasp.tprint("Query succeeded", reply) else: grasp.tprint("Empty result") else: grasp.tprint("end_negotiate error:", grasp.etext[err]) else: #immediate end, strange grasp.tprint("Unexpected reply", answer.value) #end of a negotiating session time.sleep(5) #to keep things calm... return
exit() grasp.init_bubble_text(name) grasp.tprint("Ready to negotiate EX3 as client") failct = 0 while True: #start of a negotiating session obj3.value = "Start" #discover a peer if failct > 3: failct = 0 grasp.tprint("Flushing EX3 discovery") _, ll = grasp.discover(asa_handle, obj3, 1000, flush = True) else: _, ll = grasp.discover(asa_handle, obj3, 1000) if ll==[]: grasp.tprint("Discovery failed") failct += 1 continue grasp.ttprint("Discovered locator", ll[0].locator) #attempt to negotiate grasp.tprint("Session starting") err, shandle, answer = grasp.req_negotiate(asa_handle, obj3, ll[0], None, noloop=True) if err == grasp.errors.noReply: #session is available err = False
exit() grasp.init_bubble_text(name) grasp.tprint("Ready to negotiate EX3 as client") failct = 0 while True: #start of a negotiating session obj3.value = "Start" #discover a peer if failct > 3: failct = 0 grasp.tprint("Flushing EX3 discovery") _, ll = grasp.discover(asa_nonce, obj3, 1000, flush=True) else: _, ll = grasp.discover(asa_nonce, obj3, 1000) if ll == []: grasp.tprint("Discovery failed") failct += 1 continue grasp.ttprint("Discovered locator", ll[0].locator) #attempt to negotiate grasp.tprint("Session starting") err, snonce, answer = grasp.req_negotiate(asa_nonce, obj3, ll[0], None, noloop=True)
next_peer = 0 # for cycling through peers while True: #IPv6 shortfall = need - sum_pool() if shortfall > 0: #find the next power of 2 above shortfall #and add 1 for luck if shortfall < 1: want_p = subnet_length - 1 else: want_p = subnet_length - 2 - int(math.log(shortfall, 2)) grasp.tprint("IPv6 prefix pool is low, will ask for /" + str(want_p)) want_obj.value = [6, want_p, None] #want_obj.value = [6, False, want_p, None] #find a negotiation peer err, ll = grasp.discover(asa_nonce, want_obj, 1000, flush=True) if err: grasp.tprint("Discovery error:", grasp.etext[err]) elif ll == []: grasp.tprint("No peer discovered") good_peer = None else: #pick a peer if len(ll) == 1: #only one choice peer = ll[0] grasp.tprint("Trying the only peer") elif good_peer in ll: #good one is still available peer = good_peer grasp.tprint("Trying previous peer")
def run(self): global cheat_nonce iwant = grasp._prng.randint(10, 500) grasp.tprint("Asking for $", iwant) err, asa_nonce2 = grasp.register_asa("Neg2") #assume it worked obj = grasp.objective("EX2") obj.neg = True #obj.loop_count = 2 #for testing purposes while cheat_nonce == None: time.sleep( 1) #we should exit after neg1 has registered the objective asa_nonce = cheat_nonce #now we can pretend to own the objective grasp.tprint("Got nonce", asa_nonce) err, ll = grasp.discover(asa_nonce, obj, 5000) if ll == []: grasp.tprint("Discovery failed: exit") return grasp.tprint("Discovered locator", ll[0].locator) #attempt to negotiate obj.value = ["NZD", iwant] if not iwant % 7: obj.value = ["USD", iwant] # for testing purposes err, snonce, answer = grasp.req_negotiate(asa_nonce, obj, ll[0], None) if err: if err == grasp.errors.declined and answer != "": _t = answer else: _t = grasp.etext[err] grasp.tprint("req_negotiate error:", _t) elif (not err) and snonce: grasp.tprint("requested, session_nonce:", snonce, "answer", answer) if answer.value[1] < 0.75 * iwant: answer.value[1] = int(0.75 * iwant) err, temp, answer2 = grasp.negotiate_step( asa_nonce, snonce, answer, 1000) grasp.tprint("Step1 gave:", err, temp, answer2) if (not err) and (not temp): grasp.tprint("Negotiation succeeded", answer.value) elif not err: #not acceptable, try one more time answer2.value[1] = int(0.6 * iwant) #at random, throw an invalid format of message if not iwant % 3: grasp.tprint("Trying badmess") grasp._make_badmess = True err, temp, answer3 = grasp.negotiate_step( asa_nonce, snonce, answer2, 1000) grasp.tprint("Step2 gave:", err, temp, answer3) if (not err) and (not temp): grasp.tprint("Negotiation succeeded", answer3.value) elif (not err): #not acceptable err = grasp.end_negotiate(asa_nonce, snonce, False, reason="You are mean!") if err: grasp.tprint("end_negotiate error:", grasp.etext[err]) else: #other end rejected grasp.tprint("Peer reject:", answer3) else: #other end rejected grasp.tprint("Peer reject:", answer2) else: #acceptable answer err = grasp.end_negotiate(asa_nonce, snonce, True) if not err: grasp.tprint("Negotiation succeeded", answer.value) else: grasp.tprint("end_negotiate error:", grasp.etext[err]) else: #acceptable answer first time grasp.tprint("Negotiation succeeded", answer.value) grasp.tprint("Exit")
def run(self): time.sleep(1) # avoid printing glitch grasp.tprint( "WARNING: you can't run this test suite more than once without restarting the Python context; it leaves GRASP data structures dirty!\n" ) grasp.skip_dialogue(testing=True, selfing=True, diagnosing=True) time.sleep(1) # just to avoid mixed up print output #################################### # Test code: register ASA/objective# #################################### test_obj = grasp.objective("EX1") test_obj.loop_count = 2 test_obj.synch = True err, test_nonce = grasp.register_asa("ASA-1") if not err: err = grasp.register_obj(test_nonce, test_obj, ttl=10000) if not err: grasp.tprint("ASA-1 and EX1 Registered OK") #################################### # Test code: discover EX1 # #################################### err, test_ll = grasp.discover(test_nonce, test_obj, 10000) if len(test_ll) > 0: grasp.tprint("EX1 discovery result", test_ll[0].locator) else: grasp.tprint("No EX1 discovery response") #################################### # Test code: register and discover # # Boot ASA/objective # #################################### err, boot_nonce = grasp.register_asa("Boot") if err: #we've got a problem... raise RuntimeError("Can't register Boot as ASA") boot_obj = grasp.objective("Boot") boot_obj.loop_count = 2 boot_obj.synch = True err = grasp.register_obj(boot_nonce, boot_obj, discoverable=True) if err: #we've got a different problem... raise RuntimeError("Can't register Boot objective") for i in range(3): #test discovery 3 times, including artificial Divert grasp.tprint("Test ASA: grasp.test_divert", grasp.test_divert) err, boot_ll = grasp.discover(boot_nonce, boot_obj, 5000) if len(boot_ll) > 0: grasp.tprint("Boot discovery result", boot_ll[0].locator) grasp.test_divert = True else: grasp.tprint("No Boot discovery response") time.sleep(5) grasp.test_divert = False #################################### # Test code: send Flood messages #################################### obj1 = grasp.objective("Money") obj1.synch = True obj1.loop_count = 2 err = grasp.register_obj(test_nonce, obj1) obj1.value = [100, "NZD"] obj2 = grasp.objective("Bling") obj2.synch = True obj2.loop_count = 2 err = grasp.register_obj(test_nonce, obj2) obj2.value = ["Diamonds", "Rubies"] err = grasp.register_obj(test_nonce, obj2) if err: grasp.tprint(grasp.etext[err]) obj3 = grasp.objective("Intent.PrefixManager") obj3.synch = True obj3.loop_count = 2 err = grasp.register_obj(test_nonce, obj3) #obj3.value = '{"autonomic_intent":[{"model_version": "1.0"},{"intent_type": "Network management"},{"autonomic_domain": "Customer_X_intranet"},{"intent_name": "Prefix management"},{"intent_version": 73},{"Timestamp": "20150606 00:00:00"},{"Lifetime": "Permanent"},{"signature":"XXXXXXXXXXXXXXXXXXX"},{"content":[{"role": [{"role_name": "RSG"},{"role_characteristic":[{"prefix_length":"34"}]}]},{"role": [{"role_name": "ASG"},{"role_characteristic":[{"prefix_length": "44"}]}]},{"role": [{"role_name": "CSG"},{"role_characteristic":[{"prefix_length": "56"}]}]}]}]}' #obj3.value = '{"autonomic_intent dummy text"}' #obj3.value = bytes.fromhex('48deadbeefdeadbeef') #dummy CBOR obj3.value = cbor.dumps(["Some", "embedded", "CBOR", [1, 2, 3]]) grasp.flood(test_nonce, 0, grasp.tagged_objective(obj1, None), grasp.tagged_objective(obj2, None), grasp.tagged_objective(obj3, None)) ################################### # Test code: Listen Synchronize as from Boot ASA ################################### boot_obj.value = [1, "two", 3] boot_obj.synch = True err = grasp.listen_synchronize(boot_nonce, boot_obj) grasp.tprint("Listen synch", grasp.etext[err]) grasp.tprint(grasp._obj_registry[1].objective.name, "value", grasp._obj_registry[1].objective.value) ################################### # Test code: call Synchronize as from EX1 ################################### time.sleep(5) err, result = grasp.synchronize(test_nonce, obj2, None, 5000) if not err: grasp.tprint("Flooded synch obj2", result.value) else: grasp.tprint("Synch fail obj2", grasp.etext[err]) err, result = grasp.synchronize(test_nonce, obj3, None, 5000) if not err: grasp.tprint("Flooded synch obj3", result.value) else: grasp.tprint("Synch fail obj3", grasp.etext[err]) #this should fail as test_obj was neither flooded or listened for. err, result = grasp.synchronize(test_nonce, test_obj, None, 5000) if not err: grasp.tprint("Synch test_obj (should fail)", result.value) else: grasp.tprint("Synch fail test_obj (should fail)", grasp.etext[err]) boot2_obj = grasp.objective("Boot") boot2_obj.synch = True err, result = grasp.synchronize(test_nonce, boot2_obj, None, 5000) if not err: grasp.tprint("Synch boot2_obj", result.name, result.value) else: grasp.tprint("Synch fail boot2_obj", grasp.etext[err]) ################################### # Test code: print obj_registry # and flood cache ################################### grasp.tprint("Objective registry contents:") for x in grasp._obj_registry: o = x.objective grasp.tprint(o.name, "ASA:", x.asa_id, "Listen:", x.listening, "Neg:", o.neg, "Synch:", o.synch, "Count:", o.loop_count, "Value:", o.value) grasp.tprint("Flood cache contents:") for x in grasp._flood_cache: grasp.tprint(x.objective.name, "count:", x.objective.loop_count, "value:", x.objective.value, "source:", x.source) time.sleep(5) ################################### # Test code: check flood cache for Tag 24 case ################################### flobj = grasp.objective("Intent.PrefixManager") flobj.synch = True err, tobs = grasp.get_flood(test_nonce, flobj) if not err: for x in tobs: try: grasp.tprint("Flooded CBOR", x.objective.name, cbor.loads(x.objective.value)) except: grasp.tprint("Flooded raw", x.objective.name, x.objective.value) ################################### # Test code: deregister and then # attempt synch ################################### err = grasp.deregister_obj(boot_nonce, boot_obj) if not err: grasp.tprint("Deregistered Boot", ) else: grasp.tprint("Deregister failure", grasp.etext[err]) err, result = grasp.synchronize(test_nonce, boot2_obj, None, 5000) if not err: grasp.tprint("Synch boot2_obj (should fail)", result.name, result.value) else: grasp.tprint("Synch fail boot2_obj (should fail)", grasp.etext[err]) ################################### # Test code: start in-host negotiate test ################################### cheat_nonce = None Neg1().start() time.sleep(10) Neg2().start() ##################################### # Test code: # test deregistering an ASA, # and exit the thread ##################################### grasp.deregister_asa(test_nonce, "ASA-1") grasp.tprint("Exiting ASA test thread")
def get_dns_info(service, dom): """Obtain and return all DNS-SD records for a service and domain""" global obj3 global failct #start of a negotiating session obj3.loop_count = 20 #allows for some fragmentation obj3.dry = False #dry run not allowed req_elem = new_relement() req_elem[cp.outer][cp.sender_loop_count] = obj3.loop_count req_elem[cp.outer][cp.srv_element][cp.service] = service req_elem[cp.outer][cp.srv_element][cp.domain] = dom obj3.value = req_elem # As a random test, use CBOR (Tag 24) format for value (should work) if not grasp._prng.randint(0, 3): _cbor = True else: _cbor = False grasp.tprint("Asking for", obj3.value, "; Tag 24", _cbor) #discover a peer if failct > 3: failct = 0 grasp.tprint("Flushing", obj3.name, "discovery") _, ll = grasp.discover(asa_nonce, obj3, 1000, flush=True) else: _, ll = grasp.discover(asa_nonce, obj3, 1000) if ll == []: grasp.tprint("Discovery failed") failct += 1 return grasp.ttprint("Discovered locator", ll[0].locator) #attempt to negotiate if _cbor: #CBORise the value obj3.value = cbor.dumps(obj3.value) reply = [] err, snonce, answer = grasp.req_negotiate(asa_nonce, obj3, ll[0], None) if err: if err == grasp.errors.declined and answer != "": _e = answer else: _e = grasp.etext[err] grasp.tprint("req_negotiate error:", _e) failct += 1 grasp.tprint("Fail count", failct) time.sleep(5) #to calm things if there's a looping error elif (not err) and snonce: grasp.ttprint("requested, session_nonce:", snonce, "answer", answer) _found_cbor = False if _cbor: answer.value, _found_cbor = detag(answer.value) grasp.tprint("First reply:", prettify(answer.value)) if _cbor != _found_cbor: #Anomaly, get me out of here grasp.tprint("CBOR anomaly 1 - missing segment?") grasp.end_negotiate(asa_nonce, snonce, False, reason="CBOR anomaly 1 - missing segment?") else: #Received first answer looping = True while looping: #need to go again answer.value = "ACK" grasp.tprint("Sending ACK for more") answer.loop_count += 2 #allow an extra round trip if _cbor: #CBORise the value answer.value = cbor.dumps(answer.value) err, temp, answer = grasp.negotiate_step( asa_nonce, snonce, answer, 5000) if err: grasp.tprint("negotiate_step error:", grasp.etext[err]) looping = False elif not temp: #end of replies looping = False else: if _cbor: answer.value, _found_cbor = detag(answer.value) if _cbor != _found_cbor: #anomaly, get me out of here looping = False grasp.end_negotiate( asa_nonce, snonce, False, reason="CBOR anomaly 2 - missing segment?") grasp.tprint("CBOR anomaly 2 - missing segment?") return grasp.tprint("Next reply:", prettify(answer.value)) grasp.tprint("End of replies") else: #immediate end, strange grasp.tprint("Unexpected reply", answer.value) #end of a negotiating session time.sleep(5) #to keep things calm... return
def get_file(fn): """Get a single file""" global requested_obj global failct global directory #start of a negotiating session requested_obj.value = fn requested_obj.loop_count = 10 #allows for some fragmentation #prepare file path for result try: #strip C:/brian/docs for xfer from Windows to Linux _, fpath = fn.split("C:/brian/docs/") except: fpath = directory + fn grasp.tprint("Asking for", requested_obj.value) #discover a peer if failct > 3: failct = 0 grasp.tprint("Flushing", requested_obj.name, "discovery") _, ll = grasp.discover(asa_nonce, requested_obj, 1000, flush=True) else: _, ll = grasp.discover(asa_nonce, requested_obj, 1000) if ll == []: grasp.tprint("Discovery failed") failct += 1 return grasp.ttprint("Discovered locator", ll[0].locator) #attempt to negotiate reply = b'' err, snonce, received_obj = grasp.req_negotiate(asa_nonce, requested_obj, ll[0], 5000) if err: if err == grasp.errors.declined and received_obj != "": _e = received_obj else: _e = grasp.etext[err] grasp.tprint("req_negotiate error:", _e) failct += 1 grasp.tprint("Fail count", failct) elif (not err) and snonce: grasp.ttprint("requested, session_nonce:", snonce, "received_obj", received_obj) grasp.ttprint("Received reply", received_obj.value) looping = True first = True while looping: grasp.ttprint("received_obj is", received_obj.value) if first and (received_obj.value == b''): grasp.tprint("File not found") looping = False elif received_obj.value == b'': #got the last block looping = False file.close() err = grasp.end_negotiate(asa_nonce, snonce, True) if not err: grasp.tprint("Transfer succeeded") else: grasp.tprint("end_negotiate error:", grasp.etext[err]) elif len(received_obj.value): if first: file = open(fpath, "wb") grasp.tprint("Starting transfer") #write a block and go again file.write(received_obj.value) received_obj.value = "ACK" received_obj.loop_count += 1 grasp.ttprint("Sending ACK for more") err, temp, received_obj = grasp.negotiate_step( asa_nonce, snonce, received_obj, 1000) if err: if err == grasp.errors.declined and received_obj != "": _e = received_obj else: _e = grasp.etext[err] grasp.tprint("negotiate_step error:", _e) looping = False grasp.ttprint("Reply to ACK:", err, temp, received_obj) first = False else: #immediate end, strange grasp.tprint("Unexpected reply", received_obj.value) #end of a negotiating session time.sleep(5) #to keep things calm... return
def get_file(): """Get key file""" global keys_obj global failct global private_key #look for quadski err, results = grasp.get_flood(asa_nonce, flood_obj) if not err: # results contains all the unexpired tagged objectives # but really there should only be one... if results == []: grasp.tprint("Found no value for",flood_obj.name) time.sleep(10) #pause for something to change... return else: grasp.tprint("Found value for",flood_obj.name) # recover quadski's public key quadski_pub_key = serialization.load_pem_public_key( results[0].objective.value, backend=default_backend() ) else: grasp.tprint("get_flood failed", grasp.etext[err]) return #not this time #set up objective value ciphertext = quadski_pub_key.encrypt( password, padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) keys_obj.value = [ciphertext,pem] #start of negotiating session grasp.tprint("Asking for keys") #discover a peer if failct > 3: failct = 0 grasp.tprint("Flushing", keys_obj.name, "discovery") _, ll = grasp.discover(asa_nonce, keys_obj, 1000, flush = True) else: _, ll = grasp.discover(asa_nonce, keys_obj, 1000) if ll==[]: grasp.tprint("Discovery failed") failct += 1 return grasp.ttprint("Discovered locator", ll[0].locator) #attempt to negotiate err, snonce, received_obj = grasp.req_negotiate(asa_nonce, keys_obj, ll[0], 5000) if err: if err==grasp.errors.declined and received_obj!="": _e = received_obj else: _e = grasp.etext[err] grasp.tprint("Negotiation error:", _e) failct += 1 grasp.tprint("Fail count", failct) if _e == "Incorrect password": get_pass() return elif (not err) and snonce: grasp.ttprint("requested, session_nonce:",snonce,"received_obj",received_obj) grasp.ttprint("Received raw reply",received_obj.value) grasp.ttprint("received_obj is", received_obj.value) if received_obj.value == b'': grasp.tprint("Keys not found") else: grasp.ttprint("Starting transfer") #decrypt block plaintext = private_key.decrypt( received_obj.value, padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) keys = cbor.loads(plaintext) key = keys[0] iv = keys[1] file = open(r"quadsk.py","w") file.write("key="+str(key)+"\n") file.write("iv="+str(iv)+"\n") file.close() grasp.tprint("quadsk.py saved OK") err = grasp.end_negotiate(asa_nonce, snonce, True) if err: grasp.tprint("end_negotiate error:",grasp.etext[err]) else: #immediate end, strange grasp.tprint("Unexpected reply", received_obj.value) #end of a negotiating session time.sleep(10) #pause for something to change... return