예제 #1
0
파일: GetDNSSD.py 프로젝트: woodlums/graspy
def resolve(n, q):
    """Resolve a single domain and return the RR"""
    try:
        grasp.ttprint("Resolving", n, q)
        a = dns.resolver.query(n, q)
        grasp.ttprint("Got", a)
        return a
    except:
        return []
예제 #2
0
    def run(self):
        answer = self.nobj
        shandle = self.shandle

        grasp.ttprint("listened, answer", answer.name, answer.value)
        grasp.tprint("Got message:", answer.value)
        err = False
        while not err:
            err, stuff = grasp.grecv(asa_handle, shandle, 60000)
            if not err:
                grasp.tprint("Peer said", stuff)
                tweet = input("Your message:")
                err = grasp.gsend(asa_handle, shandle, tweet)
        grasp.tprint("Send/recv error:", grasp.etext[err])
        #all errors are fatal, the session is dead
        grasp.tprint("End of session")
예제 #3
0
 def run(self):
     received_obj=self.nobj
     snonce=self.snonce    
     grasp.tprint("Got request for QUADS keys")
     if received_obj.dry:
         endit(snonce,"Dry run not supported")
     else:
         #unwrap pledge's request                            
         pledge_password = private_key.decrypt(
                      received_obj.value[0],
                      padding.OAEP(
                      mgf=padding.MGF1(algorithm=hashes.SHA256()),
                      algorithm=hashes.SHA256(),
                      label=None))
         if pledge_password != password:
             endit(snonce,"Incorrect password")
         else:
             #prepare pledge's public key
             pub_key = serialization.load_pem_public_key(
                 received_obj.value[1],
                 backend=default_backend() )
             #prepare the QUADS keys
             chunk = cbor.dumps([key, iv])
             grasp.tprint("Sending keys")
             #encrypt chunk
             received_obj.value = pub_key.encrypt(
                 chunk,
                 padding.OAEP(
                     mgf=padding.MGF1(algorithm=hashes.SHA256()),
                     algorithm=hashes.SHA256(),
                     label=None))
             grasp.ttprint("Sending",len(chunk),"bytes")
                                                       
             #send keys as negotiation step                    
             err,temp,received_obj = grasp.negotiate_step(asa_nonce, snonce, received_obj, 1000)
             grasp.ttprint("Negotiation step gave:", err, temp, received_obj)
             if not err:
                 # the other end signalled End/Accept
                 grasp.tprint("Ended transfer")                 
             else:    
                 #other end rejected or loop count exhausted
                 if err==grasp.errors.loopExhausted:
                     # we need to signal the end
                     endit(snonce, grasp.etext[err])
                 else:
                     grasp.tprint("Failed:",grasp.etext[err])
예제 #4
0
파일: Mudlark.py 프로젝트: woodlums/graspy
    def run(self):
        answer=self.nobj
        snonce=self.snonce        
        grasp.ttprint("listened, answer",answer.name, answer.value)
        grasp.tprint("Got MUD URL", answer.value,
                     "from", ipaddress.IPv6Address(snonce.id_source))
        if grasp.tname(answer.value)!="str":
            endit(snonce, "Not a string")
        elif answer.value[0:8]!="https://":
            endit(snonce, "Not https: scheme")
        #could do other sanity checks
        else:
            #sanity checks passed
            #Now the MUD manager can process the URL
            process_MUD_URL(answer.value)            

            #close the session normally (with no feedback to peer)
            err = grasp.end_negotiate(asa_nonce, snonce, True)
            if err:
                grasp.tprint("end_negotiate error:",grasp.etext[err])       
예제 #5
0
파일: Mudlark.py 프로젝트: woodlums/graspy
def check_sig(j,sig):
    """ j is the MUD file (JSON) to be validated,
        sig is the URL of the signature file,
        return True if verified, else False."""
    mfile = cwd+"/mud.mud"
    file = open(mfile, "wb")
    file.write(j)
    file.close()
    try:
        pfile = cwd+"/p7s.p7s"
        p7s = requests.get(sig).content
        file = open(pfile, "wb")
        file.write(p7s)
        file.close()
    except:
        grasp.tprint("Couldn't fetch signature file")
        return False
    cmd = ['openssl', 'cms', '-verify', '-in',
            pfile, '-inform', 'DER', '-content',
            mfile, '-binary']
    if 'CAfile' in globals():
        cmd.append('-CAfile')
        cmd.append(CAfile)
    elif 'CApath' in globals():
        cmd.append('-CApath')
        cmd.append(CApath)
    x = run(cmd)
    grasp.ttprint(x)
    try:
        os.remove(mfile)
        os.remove(pfile)
    except:
        pass
    if x.returncode != 0:
        return False
    else:
        return True
예제 #6
0
    def run(self):
        answer=self.nobj
        snonce=self.snonce
        
        answer.value, _cbor = detag(answer.value)
        if _cbor:
            grasp.tprint("CBOR value decoded")

        grasp.tprint("Got request")
        if answer.dry:
            endit(snonce,"Dry run not supported")
            return
        
        # Check format of request & extract fields
        try:
            req = answer.value.get("@rfcXXXX")
        except:
            req = None
        if not req:
            endit(snonce,"Not RFCXXXX format")
            return
        grasp.tprint(req)
        sel = req.get(cp.srv_element)
        if not sel:
            endit(snonce,"No service element")
            return     
        msg_type = sel.get(cp.msg_type)
        if msg_type != cp.describe_request:
            endit(snonce,"Not describe_request")
            return
        srv_name = sel.get(cp.service)
        if not srv_name:
            endit(snonce,"No service name")
            return
        dom_name = sel.get(cp.domain)
        if not dom_name:
            endit(snonce,"No domain name")
            return
        
        # Construct DNS name
        dns_name = "_"+srv_name+"."+dom_name
        if dns_name[-1] != ".":
            dns_name += "."

       
        #Look for PTR record first

        found_something = False
        broken = False
        a = resolve(dns_name,'PTR')
        
        for r in a:
            found_something = True
            #extract the instance name
            raw_name = str(r)
            #decode Unicode escapes
            fixed_name = fix_string(raw_name)
            #remove bogus escapes
            name = fixed_name.replace("\\","")
                            
            grasp.tprint("Got PTR name:",name)
            grasp.ttprint("Raw name:",raw_name)
            if name[-len(dns_name):] == dns_name:
                inst_name = name[0:-len(dns_name)-1]
            else:
                inst_name = name
            grasp.tprint("Instance name", inst_name)

            #start new reply element
            relement = new_relement()
            grasp.ttprint("Answer is", answer)
            relement[cp.outer][cp.sender_loop_count] = answer.loop_count
            relement[cp.outer][cp.srv_element][cp.instance] = inst_name
            relement[cp.outer][cp.srv_element][cp.service] = srv_name
            relement[cp.outer][cp.srv_element][cp.domain] = dom_name

            #look for other records
            a = resolve(fixed_name,'SRV')
            for r in a:
                grasp.ttprint("Got SRV", str(r))

                #parse SRV record to extract the fields

                priority,weight,srv_port,srv_dom = str(r).split(' ')
                grasp.ttprint("Got SRV domain", srv_dom)
                relement[cp.outer][cp.srv_element][cp.priority] = int(priority)
                relement[cp.outer][cp.srv_element][cp.weight] = int(weight)
                srv_port = int(srv_port)
                
                #look for address records & build locators
                loc_l = []
                a = resolve(srv_dom,'AAAA')
                for r in a:
                    grasp.ttprint("Got AAAA", str(r))
                    srv_addr = ipaddress.IPv6Address(r)
                    loc = [grasp.O_IPv6_LOCATOR,srv_addr.packed,17,srv_port]                    
                    loc_l.append(["Internet", loc])
                    
                a = resolve(srv_dom,'A')
                
                for r in a:
                    grasp.ttprint("Got A", str(r))
                    srv_addr = ipaddress.IPv4Address(r)
                    loc = [grasp.O_IPv4_LOCATOR,srv_addr.packed,17,srv_port]                    
                    loc_l.append(["Internet", loc])

                loc_l.append(["Internet",[grasp.O_FQDN_LOCATOR,srv_dom,17,srv_port]])

                #add locators to reply
                relement[cp.outer][cp.srv_element][cp.clocator] = loc_l
                
            a = resolve(name,'TXT')
            for r in a:
                grasp.tprint("Got TXT", r)                
                #Note that TXT records may include quotes
                try:
                    k,v = str(r).split(' ')
                    if k[0]=='"':
                        k=k[1:-1]
                    if v[0]=='"':
                        v=v[1:-1]                        
                    grasp.ttprint("kv",k,v)
                    relement[cp.outer][cp.srv_element][cp.kvps] = {k:v}
                except:
                    grasp.ttprint("Couldn't split", str(r))
                    pass

            # The relement is now complete, send it as next negotiation step

            grasp.tprint("Reply step", relement)
               
            answer.value = relement                  
            
            if _cbor:
                answer.value=cbor.dumps(answer.value)
            #send reply as negotiation step
            err,temp,answer = grasp.negotiate_step(asa_nonce, snonce, answer, 1000)
            grasp.ttprint("Negotiation step gave:", err, temp, answer)
            if (not err) and temp==None:
                grasp.tprint("Reply step succeeded")                 
            elif not err:
                answer.value, _ = detag(answer.value)
                if _:
                    grasp.tprint("CBOR value decoded")
                    
                if answer.value !="ACK":
                    grasp.tprint("Unexpected reply: loop count", answer.loop_count,
                                 "value",answer.value)
                    endit(snonce, "Unexpected reply")
                    broken = True
                    break
            else:    
                #other end rejected or loop count exhausted
                if err==grasp.errors.loopExhausted:
                    # we need to signal the end
                    endit(snonce, grasp.etext[err])
                else:
                    grasp.tprint("Failed:",grasp.etext[err])
                broken = True
                break
        #Sent all relements
        if broken:
            return
        if not found_something:
            #NXDOMAIN
            endit(snonce, "Service not found")
        else:
            err = grasp.end_negotiate(asa_nonce, snonce, True)
            if err:
                grasp.tprint("end_negotiate error:",grasp.etext[err])
예제 #7
0
    dns.resolver.default_resolver.nameservers = [ '2001:4860:4860::8888',
                                                  '2001:4860:4860::8844',
                                                  '8.8.8.8', '8.8.4.4' ]
    grasp.tprint("Couldn't resolve test domain, switched to Google nameservers")

###################################
# Set up pretty printing
###################################

grasp.init_bubble_text("GetDNSSD2")
grasp.tprint("GetDNSSD2 is listening")

###################################
# Negotiate as listener for ever
###################################

while True:
    # listen for negotiation request
    err, snonce, answer = grasp.listen_negotiate(asa_nonce, obj1)
    if err:
        grasp.tprint("listen_negotiate error:",grasp.etext[err])
        time.sleep(5) #to calm things if there's a looping error
    else:
        #got a new negotiation request; kick off a separate negotiator
        #so that multiple requests can be handled in parallel
        grasp.ttprint("Raw answer", answer.value)
        negotiator(snonce, answer).start()



예제 #8
0
파일: pfxm3.py 프로젝트: woodlums/graspy
    def run(self):
        nobj = self.nobj
        snonce = self.snonce
        try:
            nobj.value = cbor.loads(nobj.value)
            grasp.tprint("CBOR value decoded")
            _cbor = True
        except:
            _cbor = False
        req_ipv = nobj.value[ipv]
        #req_PD = nobj.value[PD]
        req_plen = nobj.value[lgth]
        if len(nobj.value) == lgth + 1:
            nobj.value.append(None)
        #grasp.tprint("Got request for IPv"+str(req_ipv)+"; PD=", req_PD, "length=", req_plen)
        grasp.tprint("Got request for IPv" + str(req_ipv) + "; length=",
                     req_plen)
        if nobj.dry:
            grasp.tprint("Dry run (not handled by this implementation)")
        result = True
        reason = None

        if len(ppool) == 0:
            endit(snonce, "Prefix pool empty")
        elif req_ipv == 6:
            if req_plen < 32 or req_plen > subnet_max:
                endit(snonce, "Prefix length out of range")
            else:
                pref = get_from_pool(req_plen)
                if not pref:
                    #other end wants too much, we try to make an offer
                    while (not pref) and (req_plen < subnet_max):
                        req_plen += 1
                        pref = get_from_pool(req_plen)
                if pref:
                    nobj.value = [6, req_plen, pref]
                    #nobj.value = [6, False, req_plen, pref]
                    grasp.tprint("Starting negotiation")
                    #we are offering the shortest prefix we can, so no
                    #negotiation loop can happen
                    grasp.tprint("Offering", prefstr(req_plen, pref))
                    if _cbor:
                        nobj.value = cbor.dumps(nobj.value)
                    err, temp, nobj = grasp.negotiate_step(
                        asa_nonce, snonce, nobj, 1000)
                    grasp.ttprint("Step gave:", err, temp, nobj)
                    if (not err) and temp == None:
                        grasp.tprint("Negotiation succeeded")
                    elif not err:
                        #we don't have enough resource, we will reject
                        insert_pool(req_plen, pref)
                        endit(snonce, "Insufficient resource")
                    else:
                        #other end rejected or loop count exhausted
                        insert_pool(req_plen, pref)
                        if err == grasp.errors.loopExhausted:
                            # we need to signal the end
                            endit(snonce, "Loop count exhausted")
                        else:
                            grasp.tprint("Failed:", grasp.etext[err])
                    #end of negotiation
                else:
                    #got nothing suitable from pool
                    endit(snonce, "No prefix available")
        elif req_ipv == 4:
            if req_plen < 16 or req_plen > 32:
                endit(snonce, "Prefix length out of range")
            else:
                pref = get4_from_pool(req_plen)
                if pref:
                    nobj.value = [4, req_plen, pref[12:]]
                    #nobj.value = [4, False, req_plen, pref[12:]]
                    grasp.tprint("Starting negotiation")
                    #we are offering the shortest prefix we can, so no
                    #negotiation loop can happen
                    grasp.tprint("Offering", pref4str(req_plen, pref[12:]))
                    if _cbor:
                        nobj.value = cbor.dumps(nobj.value)
                    err, temp, nobj = grasp.negotiate_step(
                        asa_nonce, snonce, nobj, 1000)
                    grasp.ttprint("Step gave:", err, temp, nobj)
                    if (not err) and temp == None:
                        grasp.tprint("Negotiation succeeded")
                    elif not err:
                        #we don't have enough resource, we will reject
                        insert_pool(req_plen, pref)
                        endit(snonce, "Insufficient resource")
                    else:
                        #other end rejected or loop count exhausted
                        insert_pool(req_plen, pref)
                        if err == grasp.errors.loopExhausted:
                            # we need to signal the end
                            endit(snonce, "Loop count exhausted")
                        else:
                            grasp.tprint("Failed:", grasp.etext[err])
                    #end of negotiation
                else:
                    #got nothing suitable from pool
                    endit(snonce, "No prefix available")
예제 #9
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)

    if err == grasp.errors.noReply:
        #session is available
        err = False
        while not err:
            tweet = input("Your message:")
            err = grasp.gsend(asa_nonce, snonce, tweet)
예제 #10
0
파일: GetDNSSD.py 프로젝트: woodlums/graspy
    def run(self):
        answer = self.nobj
        snonce = self.snonce

        answer.value, _cbor = detag(answer.value)
        if _cbor:
            grasp.tprint("CBOR value decoded")

        grasp.tprint("Got request for", answer.value)
        if answer.dry:
            endit(snonce, "Dry run not supported")
        else:
            reply = []
            reply_size = 0
            #Look for PTR record first

            a = resolve(answer.value, 'PTR')

            for r in a:

                #extract the name
                raw_name = str(r)
                #decode Unicode escapes
                fixed_name = fix_string(raw_name)
                #remove bogus escapes
                name = fixed_name.replace("\\", "")

                grasp.tprint("Got PTR name:", name)
                grasp.ttprint("Raw name:", raw_name)

                #remember where we are in the list
                reply_mark = len(reply)

                #add RR to reply
                reply.append('PTR ' + name)

                #look for other records
                a = resolve(fixed_name, 'SRV')
                for r in a:
                    srv_reply = []
                    grasp.ttprint("Got SRV", str(r))
                    srv_reply.append('SRV ' + str(r))

                    #parse SRV record to extract the domain

                    _, _, _, domain = str(r).split(' ')
                    grasp.ttprint("Got domain", domain)

                    #look for address records
                    a = resolve(domain, 'AAAA')
                    for r in a:
                        grasp.ttprint("Got AAAA", str(r))
                        srv_reply.append('AAAA ' + str(r))
                    a = resolve(domain, 'A')

                    for r in a:
                        grasp.ttprint("Got A", str(r))
                        srv_reply.append('A ' + str(r))

                    #add RRs to reply
                    reply.append(srv_reply)

                a = resolve(name, 'TXT')
                for r in a:
                    grasp.ttprint("Got TXT", str(r))
                    #Note that TXT records may include quotes
                    reply.append('TXT ' + str(r))

                #fragment before reaching 2000 bytes
                _l = len(cbor.dumps(reply))
                if _l > reply_size + 1900:
                    #getting big, mark to fragment before previous PTR
                    grasp.tprint("Fragmenting before", _l)
                    reply_size += (_l + 5)
                    reply.insert(reply_mark, 'MORE')

            #reply is now a (possibly empty) list of RRs
            if len(reply):
                grasp.tprint("Found", reply)
            else:
                reply = ['NXDOMAIN']
                grasp.tprint("No record in DNS")

            #grasp.tprint("Object length",sys.getsizeof(reply),"bytes")
            #creply=cbor.dumps(reply)
            #grasp.tprint("CBOR length",len(creply),"bytes")

            while len(reply):

                if 'NXDOMAIN' in reply:
                    piece = []
                    reply = []
                elif 'MORE' in reply:
                    grasp.tprint("Oversized reply fragmented")
                    mx = reply.index('MORE') + 1
                    piece = reply[:mx]
                    reply = reply[mx:]
                else:
                    piece = reply
                    reply = []

                answer.value = piece

                if _cbor:
                    answer.value = cbor.dumps(answer.value)
                #send reply as negotiation step
                err, temp, answer = grasp.negotiate_step(
                    asa_nonce, snonce, answer, 1000)
                grasp.ttprint("Negotiation step gave:", err, temp, answer)
                if (not err) and temp == None:
                    grasp.tprint("Reply step succeeded")
                elif not err:
                    answer.value, _ = detag(answer.value)
                    if _:
                        grasp.tprint("CBOR value decoded")

                    if not len(reply):
                        grasp.tprint("Unexpected reply: loop count",
                                     answer.loop_count, "value", answer.value)
                        endit(snonce, "Unexpected reply")
                else:
                    #other end rejected or loop count exhausted
                    reply = []  #to get us out of the loop
                    if err == grasp.errors.loopExhausted:
                        # we need to signal the end
                        endit(snonce, grasp.etext[err])
                    else:
                        grasp.tprint("Failed:", grasp.etext[err])
예제 #11
0
    def run(self):
        answer = self.nobj
        snonce = self.snonce

        try:
            answer.value = cbor.loads(answer.value)
            grasp.tprint("CBOR value decoded")
            _cbor = True
        except:
            _cbor = False
        grasp.ttprint("listened, answer", answer.name, answer.value)
        grasp.tprint("Got request for", answer.value[0], answer.value[1])
        if answer.dry:
            grasp.tprint("Dry run")
        result = True
        reason = None

        if answer.value[0] != "NZD":
            endit(snonce, "Invalid currency")
        elif answer.value[1] > reserves / 2:
            #other end wants too much, we need to negotiate
            proffer = int(reserves / 2)
            step = 1
            concluded = False
            grasp.tprint("Starting negotiation")
            while not concluded:
                #proffer some resource
                grasp.tprint("Offering NZD", proffer)
                answer.value[1] = proffer
                if _cbor:
                    answer.value = cbor.dumps(answer.value)
                err, temp, answer = grasp.negotiate_step(
                    asa_nonce, snonce, answer, 1000)
                grasp.ttprint("Step", step, "gave:", err, temp, answer)
                step += 1
                if (not err) and temp == None:
                    concluded = True
                    grasp.tprint("Negotiation succeeded")
                elif not err:
                    try:
                        answer.value = cbor.loads(answer.value)
                        grasp.tprint("CBOR value decoded")
                    except:
                        pass
                    grasp.tprint("Loop count", answer.loop_count, "request",
                                 answer.value[1])
                    #maybe wait (for no particular reason)
                    if grasp._prng.randint(1, 10) % 2:
                        err1 = grasp.negotiate_wait(asa_nonce, snonce, wt)
                        grasp.tprint("Tried wait:", grasp.etext[err1])
                        time.sleep(
                            10
                        )  # if wt<10000 this tests anomaly handling by the peer
                        grasp.tprint("Woke up")
                    if proffer < 0.6 * reserves:
                        proffer += 10
                        if proffer > answer.value[1]:
                            proffer = answer.value[
                                1] - 1  #always be a little mean
                    else:
                        #we don't have enough resource, we will reject
                        result = False
                        #randomly choose English or Russian error message
                        if reserves % 2:
                            reason = "Insufficient funds"
                        else:
                            reason = u"Недостаточно средств"
                        endit(snonce, reason)
                        concluded = True
                else:
                    #other end rejected or loop count exhausted
                    concluded = True
                    result = False

                    if err == grasp.errors.loopExhausted:
                        # we need to signal the end
                        endit(snonce, grasp.etext[err])
                    elif err == grasp.errors.declined and answer != "":
                        grasp.tprint("Declined:", answer)
                    else:
                        grasp.tprint("Failed:", grasp.etext[err])

                #end of negotiation loop
                pass
            #out of negotiation loop
        else:  #we can accept the initially requested value
            grasp.tprint("Request accepted")
            err = grasp.end_negotiate(asa_nonce, snonce, True)
            if err:
                grasp.tprint("end_negotiate error:", grasp.etext[err])
예제 #12
0
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
예제 #13
0
    def run(self):
        requested_obj = self.nobj
        snonce = self.snonce

        requested_obj.value, _cbor = detag(requested_obj.value)
        if _cbor:
            grasp.tprint("CBOR value decoded")

        grasp.tprint("Got request for", requested_obj.value)
        if requested_obj.dry:
            endit(snonce, "Dry run not supported")
        else:
            try:
                file = open(requested_obj.value, "rb")
            except Exception as e:
                grasp.tprint("File open error")
                endit(snonce, str(e))
                return
            chunk = True
            grasp.tprint("Starting transfer")
            while chunk:

                chunk = file.read(1024)
                grasp.ttprint("Sending", len(chunk), "bytes")
                requested_obj.value = chunk
                #bump the loop count for next chunk
                requested_obj.loop_count += 1

                if _cbor:
                    requested_obj.value = cbor.dumps(requested_obj.value)

                #send chunk as negotiation step
                err, temp, requested_obj = grasp.negotiate_step(
                    asa_nonce, snonce, requested_obj, 1000)
                grasp.ttprint("Negotiation step gave:", err, temp,
                              requested_obj)

                if (not err) and temp == None:
                    # the other end signalled End/Accept
                    grasp.tprint("Ended transfer")

                elif not err:
                    requested_obj.value, _ = detag(requested_obj.value)
                    if _:
                        grasp.ttprint("CBOR value decoded")

                    if (not len(chunk)) or (requested_obj.value != 'ACK'):
                        # we got a reply after EOF, or a bad ACK
                        grasp.tprint("Unexpected reply: loop count",
                                     requested_obj.loop_count, "value",
                                     requested_obj.value)
                        endit(snonce, "Unexpected reply")
                        break
                else:
                    #other end rejected or loop count exhausted
                    if err == grasp.errors.loopExhausted:
                        # we need to signal the end
                        endit(snonce, grasp.etext[err])
                    else:
                        grasp.tprint("Failed:", grasp.etext[err])
                    break
            file.close()
예제 #14
0
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
예제 #15
0
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
예제 #16
0
파일: AskDNSSD.py 프로젝트: woodlums/graspy
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
예제 #17
0
        else:  #we can accept the initially requested value
            grasp.tprint("Request accepted")
            err = grasp.end_negotiate(asa_nonce, snonce, True)
            if err:
                grasp.tprint("end_negotiate error:", grasp.etext[err])
        #end of a negotiating session


###################################
# Negotiate EX3 as listener for ever
###################################

obj3.value = ["NZD", 0]
grasp.tprint("Ready to negotiate EX3 as listener")
grasp.ttprint(
    "(Note: Cyrillic test case fails in a Windows console window, OK in IDLE window.)"
)

grasp.init_bubble_text("Briggs")

while True:
    #start of a negotiating session

    #create a random amount of resource and a random waiting time
    reserves = grasp._prng.randint(100, 400)
    wt = grasp._prng.randint(9000, 20000)
    grasp.tprint("Reserves: $", reserves, "Wait:", wt, "ms")

    #attempt to listen for negotiation
    err, snonce, answer = grasp.listen_negotiate(asa_nonce, obj3)
    if err:
예제 #18
0

def dump_some():
    grasp.dump_all(partial=True)
    time.sleep(5)


dump_some()

###################################
# Negotiate EX3 as initiator for ever
###################################

grasp.tprint("Ready to negotiate EX3 as requester")
grasp.ttprint(
    "(Note: Cyrillic test case fails in a Windows console window, OK in IDLE window.)"
)
failct = 0
grasp.init_bubble_text("Gray (old API)")

while True:
    #start of a negotiating session
    iwant = _prng.randint(10, 500)  # random requested value
    limit = int(0.7 * iwant)
    obj3.value = ["NZD", iwant]
    obj3.loop_count = _prng.randint(4, 20)  # random loop count

    #if not iwant%5:
    if iwant & 4:
        obj3.dry = True  # signal a dry run at random
    else:
예제 #19
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
        while not err:
            tweet = input("Your message:")
            err = grasp.gsend(asa_handle, shandle, tweet)
            if not err:
                err, reply = grasp.grecv(asa_handle, shandle, 60000)
                if not err:
                    grasp.tprint("Peer replied:", reply)
예제 #20
0
    dump_some()

###################################
# Negotiate MUDURL as initiator to send URL
###################################

grasp.init_bubble_text(asa_name)
grasp.tprint("Ready to negotiate", obj_name, "as requester")

failct = 0
while True:
    obj3.value = input("Enter sample MUD URL:")
    #########this tests an error case##########
    if obj3.value == "magic":
        obj3.value = 987654321
    grasp.ttprint("Starting discovery for", obj_name)
    #discover a peer
    if failct > 3:
        failct = 0
        grasp.tprint("Flushing 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.ttprint("Trying request for:", obj3.value)