def receiveMessage(self, message, sig, proof): #Note: message is an XMLRPC binary data wrapper self.messagesPassed += 1 mhash = hash(message.data) if mhash in self.messagesSet: return None if not check(proof, base64.b64encode(message.data).decode('utf-8')): print("Invalid proof of work") print(proof) return None signature = None self.messagesSet.add(mhash) if self.cipher is not None: # No reason to try to snoop without a secret try: #Only recipient can decode data decryptedMessage = self.cipher.decrypt(message.data) print('Received Message from ' + self.checkSender(decryptedMessage, sig) + ': ' + decryptedMessage.decode('utf-8')) #Get binary data from XMLRPC wrapper, decrypt it, and decode it from UTF-8 from # time.sleep(random.randrange(0, 5)) #Stop, traffic analysis time digest = SHA256.new() digest.update(decryptedMessage) signature = self.signer.sign(digest) except ValueError: pass #We end up here when trying to decrypt with a non-matching key neighbourResults = self.pool.map(self.forwardMessage, [(peer, message, sig, proof) for peer in self.neighbourSet]) for result in neighbourResults: if result is not None: return result return signature
def kReceiveMessage(self, message, nonce, ttl, sig, proof): #Note: message is an XMLRPC binary data wrapper self.messagesPassed += 1 if ttl < 0: return None if not check(proof, base64.b64encode(message.data).decode('utf-8')): print("Invalid proof of work") print(proof) return None if self.cipher is not None: # No reason to try to snoop without a secret try: #Only recipient can decode data decryptedMessage = self.cipher.decrypt(message.data) mhash = hash(message.data) if not (mhash in self.messagesDict): #We might end up here a lot ttl = 64 #default self.messagesDict[mhash] = ttl unnoncedMessage = unnonceMsg(decryptedMessage, nonce) print('Received Message from ' + self.checkSender(decryptedMessage, sig) + ': ' + unnoncedMessage.decode('utf-8')) #Get binary data from XMLRPC wrapper, decrypt it, and decode it from UTF-8 from time.sleep(random.randrange(0, 5)) #Stop, traffic analysis time digest = SHA256.new() digest.update(decryptedMessage) signature = self.signer.sign(digest) for i in range(16): self.kAck(xmlrpc.client.Binary(signature), ttl) self.messagesDict[mhash] = ttl*2 except ValueError: pass #We end up here when trying to decrypt with a non-matching key forwardThread = threading.Thread(target=self.safeForwardKWalker, args=(message, nonce, ttl-1, sig, proof)) forwardThread.start()
def verify(self, stamp=None, bits=10): if self.redeemed: return False HCC = hashcash.check(stamp, resource=self.challenge, check_expiration=hashcash.DAYS * 3, bits=bits) if HCC is True: self.redeemed = True self.save() return True return False
def upload_file(): if request.method == 'POST' and 'firmware' in request.files: if 'r' not in session or 'pow' not in request.form or not check( request.form['pow'], bits=28, resource=session['r']): return '<h1>too lazy,buddy,too lazy</h1>' session.pop('r') filename = firmware.save(request.files['firmware'], name='rom.upg') print(filename) cmd = 'su upguser -c "/bin/upg ' + os.getcwd( ) + '/tmp_rom/' + filename + ' ' + b64encode(os.urandom(8)) + '"' print(cmd) os.system(cmd) return '<h1>Upgrading, there won\'t be any notice when we are done</h1>' return '<h1>Something is missing</h1>'
def do_pow(bits, sock): resource = "".join(random.choice(string.ascii_lowercase) for i in range(8)) sock.sendall( "Please use the following command to solve the Proof of Work: hashcash -mb{} {}\n" .format(bits, resource)) sys.stdout.flush() stamp = readline(sock).strip() if not stamp.startswith("1:"): sock.sendall("only hashcash v1 supported") return False if not check(stamp, resource=resource, bits=bits): sock.sendall("invalid") return False return True
def main(r): resource = "".join(random.choice(string.ascii_lowercase) for i in range(8)) r.sendall( "Please use the following command to solve the Proof of Work: hashcash -mb{} {}\n" .format(HARDNESS, resource)) stamp = get_input(r, "PoW: ") if not stamp.startswith("1:"): r.sendall("Only hashcash v1 supported\n") return if not check(stamp, resource=resource, bits=HARDNESS): r.sendall("Invalid PoW\n") return image = get_input( r, "Image name to run (shared with '" + DOCKERUSERNAME + "' on registry.gitlab.com)\n") mydb = mysql.connector.connect(host=DBHOST, user=DBUSERNAME, passwd=DBPASSWORD, database="apparmor") allowed_chars = "1234567890qwertyuiopasdfghjklzxcvbnm/" def check_name(name): for ch in name: if ch not in allowed_chars: return "" return name if check_name(image) == "": r.sendall("Image name contains not allowed characters\n") return add = mydb.cursor() add.execute('insert into images VALUES (NULL,0,"' + image + '","");') mydb.commit() r.sendall("Image added to the queue\n")
def handle(self): resource = os.urandom(8).encode("hex") self.request.send(resource) self.request.send("\n") token = self.recvline() if (not check(token, resource=resource, bits=28)) and (not token.startswith(magic)): self.request.send("BAD\n") self.request.close() return self.request.send("Welcome to the world's premier search engine\n") self.request.send( "Enter a URL and a search string, and we'll recursively\n") self.request.send("search that page for your given string!\n") self.request.send( "(eg: https://en.wikipedia.org/wiki/Main_Page Bacon)\n\n") pid = os.fork() if (pid < 0): self.request.send("something super bad happened\n") self.request.close() return if pid: self.request.close() return # reparent to init if os.fork(): os._exit(0) os.setsid() signal.alarm(30) os.dup2(self.request.fileno(), 0) os.dup2(self.request.fileno(), 1) os.dup2(self.request.fileno(), 2) os.execl("./connman", "connman") self.request.send("something real bad happened\n") self.request.close()
SKIP_SECRET = sys.argv[1] if len(sys.argv) > 1 else None bits = 25 rand_resource = ''.join( random.choice(string.ascii_lowercase) for i in range(8)) print 'hashcash -mb{} {}'.format(bits, rand_resource) sys.stdout.flush() stamp = sys.stdin.readline().strip() if SKIP_SECRET is None or stamp != SKIP_SECRET: if not stamp.startswith('1:'): print 'only hashcash v1 supported' exit(1) if not check(stamp, resource=rand_resource, bits=bits): print 'invalid' exit(1) print 'Any other modules? (space split) > ', sys.stdout.flush() mods = sys.stdin.readline().strip() if '/' in mods: print 'You can load modules only in this directory' exit(1) args = ['./kvm.elf', 'kernel.bin', 'memo-static.elf'] args += mods.split() print '\nexecuting : {}\n'.format(' '.join(args))
def verify_proof(self, parameters_obj, data, proof): bits = parameters_obj['bits'] # should the salt be verified? return hashcash.check(proof, resource=data, bits=bits)
def requestAddNeighbour(self, name, address, limit, proof): if not check(proof, (address+self.address).replace(':', '?'), PoW_bits): print("Invalid proof of work") print(proof) return False Y = strMake(name, address, limit) if(self.neighbourSemaphore.acquire(False)): # we have room for another neighbour if not self.addNeighbour(Y): # we already had this neighbour self.neighbourSemaphore.release() return True else: # find subset of lower-capacity peers subset = [n for n in self.neighbourSet if strLimit(n) <= limit] if len(subset) == 0: # no such set -> reject return False # else find highest degree neighbour from subset Z = None ZDegree = 0 for n in subset: try: nDegree = self.makeProxy(strAddress(n)).getNeighbourDegree() if nDegree > ZDegree: Z = n ZDegree = nDegree except ConnectionError as err: print(self.name+': Error getting neighbourhood degree from peer ' + n + str(err)) self.evictPeers([n]) # now we have room if(self.neighbourSemaphore.acquire(False)): if not self.addNeighbour(Y): # we already had this neighbour self.neighbourSemaphore.release() return True if Z is None: # no such neighbour -> reject return False neighbourMaxCapacity = max([strLimit(n) for n in self.neighbourSet]) try: YDegree = self.makeProxy(address).getNeighbourDegree() except ConnectionError as err: print(self.name+': Error getting neighbourhood degree from peer ' + Y + str(err)) return False if strLimit(Y) > neighbourMaxCapacity or ZDegree > YDegree: with self.neighbourSetLock: try: self.neighbourSet.remove(Z) except KeyError as err: return False #Someone stole our neighbour!!! Damn them! self.addNeighbour(Y) try: self.makeProxy(strAddress(Z)).removeNeighbour(self.myString) except ConnectionError as err: print (self.name+': Error removing myself as neighbour from peer ' + Z + str(err)) self.evictPeers([Z]) return True else: return False