def login(): name = request.form['username'] app.logger.info("LOGIN: %s" % (name)) client_key = key_for(name) if client_key is None: app.logger.warn("No key exists for user %s. User may not be registered." % name) abort(401) secret = auth.generate_secret() p1 = auth.encrypt(secret, client_key) p2 = auth.encrypt(secret, auth.key()) return json.dumps({'client_secret': b64e(p1), 'server_secret': b64e(p2)})
def registerClient(self, host, group): # send an authorization request to the server. The server should # return a nonce value. ret = self.publishToHost(host, createMessage(cmd='AUTH')) nonce = ret['nonce'] # encrypt the nonce with pre-shared key and send it back to the host. decVal = auth.encrypt(nonce).decode('UTF8') message = createMessage(cmd='SUBSCRIBE', ip=self.addr[0], port=self.addr[1], group=self.group, nonce=decVal) # TODO: What to do with ret? ret = self.publishToHost(host, message) # save the IP of the publisher. self._publisher = host # start a heartbeat for fault tolerance self._heartBeatThread = threading.Thread(target = self.heartBeat) self._heartBeatThread.start() # Insert the ndoe into the database myConnector = mysql(str(host[0]), 3306) myConnector.connect() myConnector.insertNode(self.name, self.addr[0]+':'+str(self.addr[1]), self.group) myConnector.disconnect()
def send_message(name, msg): keyA, body = auth.aes_encrypt(msg) body = b64e(body) recipient_key = key_for(name) if recipient_key is None: return False keyA2 = keyA keyA = b64e(auth.encrypt(keyA, recipient_key)) keyA2 = b64e(auth.encrypt(keyA2, auth.public_key())) payload = {'sender': username, 'recipient': name, 'body': body, 'key': keyA, 'sender_key': keyA2} sig = b64e(str(auth.sign(username+name+body))) payload['signature'] = str(sig) keyB, payload = auth.aes_encrypt(json.dumps(payload)) payload = b64e(payload) keyB = b64e(auth.encrypt(keyB, auth.server_key())) post("messages", {'key': keyB, 'payload': payload})
def registerClient(self, host, group): # send an authorization request to the server. The server should # return a nonce value. ret = self.publishToHost(host, createMessage(cmd='AUTH')) nonce = ret['nonce'] # encrypt the nonce with pre-shared key and send it back to the host. decVal = auth.encrypt(nonce).decode('UTF8') message = createMessage(cmd='SUBSCRIBE', ip=self.addr[0], port=self.addr[1], group=self.group, nonce=decVal) # TODO: What to do with ret? ret = self.publishToHost(host, message) # save the IP of the publisher. self._publisher = host # start a heartbeat for fault tolerance self._heartBeatThread = threading.Thread(target=self.heartBeat) self._heartBeatThread.start() # Insert the ndoe into the database myConnector = mysql(str(host[0]), 3306) myConnector.connect() myConnector.insertNode(self.name, self.addr[0] + ':' + str(self.addr[1]), self.group) myConnector.disconnect()
def start_listening(self): def run_bash(cmd): return subprocess.check_output(['bash', '-c', cmd]) def get_pack(msg): porta = self.MCAST_PORT ram = run_bash("head -2 /proc/meminfo | grep -Po '[0-9]+'" + "|sed -e ':a' -e 'N' -e '$!ba' -e 's/\\n/ /g'" + "|awk -F ' ' '{print ((($1 - $2) / $1) * 100)}'") bandwidth = int(run_bash("netstat | grep tcp | wc -l") ) / int(run_bash("ulimit -n")) * 100 cpu = run_bash( "uptime | awk -F'[a-z]:' '{ print $2}' | awk -F ',' '{print $1}'") return create_packet({'ip': "", 'porta': str(porta), 'ram': ram.decode('utf-8'), 'cpu': cpu.decode('utf-8'), 'rtt': msg['rtt'], 'bandwidth': bandwidth}) while True: request, to = self.socket.recvfrom(10240) packet = json.loads(decrypt(request).decode()) request = check_packet(packet) if request: if request['n_packet'] > self.n_packet: self.n_packet = request['n_packet'] print(request, to) msg = (str(get_pack(request))).encode() time.sleep(randint(0, 10)) self.socket.sendto(encrypt(msg), to)
def send(plaintext, auth, recipient, ttl=0, **kwargs): ''' Encrypt the contents to a keybase-saltpack; push it to Twitter, GitHub. ''' queue = kwargs['queue'] if 'queue' in kwargs else None debug = kwargs['debug'] if 'debug' in kwargs else False future = int(datetime.utcnow().strftime('%s')) + ttl prefix = 'twitter-message-bus' if status(debug): LOGGER.info('[keybase-status] client-up; signed-in') # Do a look-up on Keybase for a valid recipient ID. if lookup(recipient, debug): LOGGER.info('[keybase-lookup] %s exists', recipient) # Encrypt the document. encrypted = encrypt(plaintext, recipient, debug) # Sign the document. signed = sign(encrypted, debug) # Post the gist. gist_id, _hash = post(content=signed, username=recipient, debug=debug, token=auth[0]) if gist_id: prefix = '-'.join([prefix, _hash]) LOGGER.info('[gist] %s', gist_id) try: # Logic for gists/tweets with TTL. if gist_id and ttl and queue and encrypted: message = '~'.join(['gist', gist_id, str(future)]) queue.add_job('out', message) LOGGER.info('[gist-queue] added %s to \'out\'', message) tweet = None if gist_id: tweet = auth[1].update_status(':'.join([prefix, gist_id])) LOGGER.debug('[tweet] %s', tweet) LOGGER.info('[tweet] %s', tweet.id) if tweet and ttl and queue: message = '~'.join(['tweet', tweet.id_str, str(future)]) queue.add_job('out', message) LOGGER.info('[tweet-queue] added %s to \'out\'', message) return gist_id, tweet.id except Exception: LOGGER.error('[queue] unable to write to queue; data lost!') else: LOGGER.error('[keybase-lookup] lookup for %s failed!', recipient) else: LOGGER.error('[keybase-status] client-down/signed-out!')
def test(): print "DATABASE TESTS\n" conn = auth.initDB("test.db") random_number = random.randint(0, 500) print "Set salt: %d" % random_number auth.setHex(conn, auth.SALT, "Mr. Mustafa", random_number) retrieved_random_number = auth.getHex(conn, auth.SALT, "Mr. Mustafa") print "Got salt: %d" % retrieved_random_number assert (retrieved_random_number == random_number), "setHex/getHex do not match" print "\n\nKEY GENERATION TESTS\n" keydict = auth.generateKey(conn, "Mr. Mustafa", random.randint(0, 500)) print "Generated session key %s" % auth.hexify(keydict["K"]) print "Verification hash is %d" % keydict["M"] print "\n\nENCRYPTION TESTS\n" message = """ And Aaron would have to explain about the modular design of the coffins and how they could be folded up and put inside one another "They are not one use only", he would say "They are recyclable" """ print "\nTrue encryption\n" encrypted = auth.encrypt(keydict["K"], message) print "Encrypted to \"%s\"" % encrypted decrypted = auth.decrypt(keydict["K"], encrypted) print "Decrypted to \"%s\"" % decrypted assert (decrypted == message), "encrypt/decrypt do not match" print "\nFalse encryption\n" encrypted = auth.encrypt("Incorrect keyIncorrect keyIncorr", message) print "False encrypted to \"%s\"" % encrypted decrypted = auth.decrypt(keydict["K"], encrypted) assert (decrypted == None), "Accepted false information" if (decrypted == None): print "Rejected false information"
def auth_passwordreset_reset(reset_code, new_password): # Check if new password is valid. is_valid_password(new_password) # Check if reset_code is valid. u_id = get_u_id_from_reset_code(reset_code) # Reset password database["users"][u_id]["password"] = encrypt(new_password) # Delete reset code for reset_code_id, code in database["reset_codes"].items(): if code["reset_code"] == reset_code: to_remove = reset_code_id del database["reset_codes"][to_remove] return {}
def authorized(): resp = github_auth.authorized_response() if resp is None or not resp.get("access_token"): return "Access denied: reason=%s error=%s resp=%s" % ( request.args["error"], request.args["error_description"], resp, ) github_token = resp["access_token"] print(github_token) auth_token = auth.encrypt(github_token).decode() user = get_user_details( github_token=github_token, auth_token=auth_token, bypass_cache=True ) params = { "token": auth_token, "login": user["login"], "avatar_url": user["avatar_url"], } response = redirect(f"https://bilara.suttacentral.net/auth?{urlencode(params)}") return response
def pack(self): self.n_packet += 1 return encrypt(json.dumps(create_packet({'n_packet': self.n_packet, 'rtt': str(int(time.time()))}), separators=(',', ':')).encode())
c.execute(""" CREATE TABLE IF NOT EXISTS keys (id INTEGER PRIMARY KEY ASC, uname TEXT, key TEXT) """) c.execute(""" SELECT * FROM keys WHERE uname=? """, (qwargs["uname"], )) keyrow = c.fetchone() if keyrow is not None: key = base64.b64decode(keyrow[2]) info = json.loads(auth.decrypt(key, qwargs["info"])) if info is not None: #Create the user and tell the client whether or not this was successfull print auth.encrypt( key, json.dumps({ "success": auth.createUser(conn, info["uname"], info["verifier"], info["salt"]) })) conn.commit() conn.close() else: print auth.encrypt(key, json.dumps({"error": "DATA CORRUPTION"})) else: print json.dumps({"error": "NO ESTABLISHED SESSKEY"})
u.execute(""" CREATE TABLE IF NOT EXISTS keys (id INTEGER PRIMARY KEY ASC, uname TEXT, key TEXT); """) u.execute(""" SELECT * FROM keys WHERE uname=? """, (qwargs["uname"],)) keyrow = u.fetchone() if keyrow is not None: key = base64.b64decode(keyrow[2]) info = json.loads(auth.decrypt(key, pargs["info"])) n.execute(""" INSERT INTO news (title, body, timestamp) VALUES (?, ?, ?) """, (info["title"], info["body"], time.time())) nconn.commit() print "Content-type: application/json" print "" print auth.encrypt(key, json.dumps({ "success": True })) else: print "Content-type: application/json" print "" print json.dumps({ "error": "NO ESTABLISHED SESSKEY" })
#Enforce one value per query string argument for key in qwargs: qwargs[key] = qwargs[key][0] #Connect to the users database conn = auth.initDB("/home/daemon/ecc-index/db/users.db") #Create the session key table if it's not there yet, and delete any old session keys c = conn.cursor() c.execute(""" SELECT * FROM keys WHERE uname=? """, (qwargs["uname"],)) key = base64.b64decode(c.fetchone()[2]) print "Content-Type: application/json" print "" decrypted = auth.decrypt(key, qwargs["message"]) if decrypted == "SRP_CLIENT_SUCCESS_MESSAGE": print json.dumps({ "message": auth.encrypt(key, "SRP_SERVER_SUCCESS_MESSAGE") }) else: print json.dumps({ "error":True, "decrypted":decrypted })
u.execute(""" SELECT * FROM keys WHERE uname=? """, (qwargs["uname"],)) keyrow = u.fetchone() print "Content-Type: application/json" print "" if keyrow is None: print json.dumps({ "error": "NO ESTABLISHED SESSKEY" }) else: key = base64.b64decode(keyrow[2]) u.execute(""" SELECT * FROM team WHERE uname=? """, (qwargs["uname"],)) teamrow = u.fetchone() if teamrow is None: print auth.encrypt(key, json.dumps({ "teams":[] })) else: print auth.encrypt(key, json.dumps({ "teams":json.loads(teamrow[2]) }))
CREATE TABLE IF NOT EXISTS keys (id INTEGER PRIMARY KEY ASC, uname TEXT, key TEXT); """) u.execute(""" CREATE TABLE IF NOT EXISTS team (id INTEGER PRIMARY KEY ASC, uname TEXT, projects TEXT) """) u.execute(""" SELECT * FROM keys WHERE uname=? """, (qwargs["uname"], )) keyrow = u.fetchone() print "Content-Type: application/json" print "" if keyrow is None: print json.dumps({"error": "NO ESTABLISHED SESSKEY"}) else: key = base64.b64decode(keyrow[2]) u.execute(""" SELECT * FROM team WHERE uname=? """, (qwargs["uname"], )) teamrow = u.fetchone() if teamrow is None: print auth.encrypt(key, json.dumps({"teams": []})) else: print auth.encrypt(key, json.dumps({"teams": json.loads(teamrow[2])}))
c.execute(""" CREATE TABLE IF NOT EXISTS keys (id INTEGER PRIMARY KEY ASC, uname TEXT, key TEXT) """) c.execute(""" SELECT * FROM keys WHERE uname=? """, (qwargs["uname"],)) keyrow = c.fetchone() if keyrow is not None: key = base64.b64decode(keyrow[2]) new_keyset = json.loads(auth.decrypt(key, qwargs["info"])) if new_keyset is not None: auth.setHex(conn, auth.VERIFIER, qwargs["uname"], new_keyset["verifier"]) auth.setHex(conn, auth.SALT, qwargs["uname"], new_keyset["salt"]) print auth.encrypt(key, json.dumps({ "success": True })) else: print auth.encrypt(key, json.dumps({ "success": False, "error": "DATA CORRUPTION" })) else: print json.dumps({ "success": False, "error": "NO ESTABLISHED SESSKEY" })
conn = auth.initDB("/home/daemon/ecc-index/db/users.db") c = conn.cursor() c.execute(""" CREATE TABLE IF NOT EXISTS keys (id INTEGER PRIMARY KEY ASC, uname TEXT, key TEXT) """) c.execute(""" SELECT * FROM keys WHERE uname=? """, (qwargs["uname"], )) keyrow = c.fetchone() if keyrow is not None: key = base64.b64decode(keyrow[2]) new_keyset = json.loads(auth.decrypt(key, qwargs["info"])) if new_keyset is not None: auth.setHex(conn, auth.VERIFIER, qwargs["uname"], new_keyset["verifier"]) auth.setHex(conn, auth.SALT, qwargs["uname"], new_keyset["salt"]) print auth.encrypt(key, json.dumps({"success": True})) else: print auth.encrypt( key, json.dumps({ "success": False, "error": "DATA CORRUPTION" })) else: print json.dumps({"success": False, "error": "NO ESTABLISHED SESSKEY"})
c.execute(""" CREATE TABLE IF NOT EXISTS keys (id INTEGER PRIMARY KEY ASC, uname TEXT, key TEXT) """) c.execute(""" SELECT * FROM keys WHERE uname=? """, (qwargs["uname"],)) keyrow = c.fetchone() if keyrow is not None: key = base64.b64decode(keyrow[2]) info = json.loads(auth.decrypt(key, qwargs["info"])) if info is not None: #Create the user and tell the client whether or not this was successfull print auth.encrypt(key, json.dumps({ "success": auth.createUser(conn, info["uname"], info["verifier"], info["salt"]) })) conn.commit() conn.close() else: print auth.encrypt(key, json.dumps({ "error": "DATA CORRUPTION" })) else: print json.dumps({ "error": "NO ESTABLISHED SESSKEY" })
}) else: team = json.loads(row[2]) info = { "team": team } # This will be the actual info that's returned to the client # Make sure that this user is actually on the project team if not qwargs["uname"] in team: print json.dumps({ "error": "NOT ON TEAM" }) # See if github is better than us request = httplib.HTTPSConnection("api.github.com") request.putrequest("GET", row[3]) request.putheader("User-Agent", "dabbler0") request.endheaders() loaded = json.loads(request.getresponse().read()) # Tell it to the client info["needs_launching"] = (row[6] < loaded["updated_at"]) # Put in the analytics stuff that's in the database info["analytics"] = json.loads(row[5]) print auth.encrypt(key, json.dumps(info)) else: print json.dumps({ "error": "NO ESTABLISHED SESSKEY" })
CREATE TABLE IF NOT EXISTS projects (id INTEGER PRIMARY KEY ASC, name TEXT, team TEXT, github TEXT, path TEXT, analytics TEXT, updated TEXT) """) # Get this user's session key kconn = auth.initDB("/home/daemon/ecc-index/db/users.db") k = kconn.cursor() k.execute(""" SELECT * FROM keys WHERE uname=? """, (qwargs["uname"],)) keyrow = k.fetchone() if keyrow is not None: key = base64.b64decode(keyrow[2]) # Get the row that we want c.execute(""" SELECT * FROM projects WHERE name=? """, (path[2],)) row = c.fetchone() if row is not None: analytics = json.loads(row[5]) analytics["failures"] = filter(lambda (x): x["id"] != rid, analytics["failures"]) print auth.encrypt(key, json.dumps({ "success": True }) else: print auth.encrypt(key, json.dumps({ "error": "NO SUCH PROJECT" })