def authenticate(self): auth_message = auth_pb2.AuthMessage() auth_message.type = auth_pb2.AuthMessage.HELLO auth_message.name = self.name self.auth_server.send(auth_message.SerializeToString()) data = self.auth_server.recv() challenge = auth_pb2.AuthMessage() challenge.ParseFromString(data) if challenge.type != auth_pb2.AuthMessage.CHALLENGE: raise Exception("Unexpected response from server %s " % str(challenge)) else: response = auth_pb2.AuthMessage() response.name = self.name response.type = auth_pb2.AuthMessage.RESPONSE response.response = hashlib.sha256(challenge.nonce + self.secret).hexdigest() self.auth_server.send(response.SerializeToString()) data = self.auth_server.recv() response = auth_pb2.AuthMessage() response.ParseFromString(data) if response.type == auth_pb2.AuthMessage.TOKEN: self.token = response.token return True else: print response.error_message return False
def make_challenge(self): self.nonce = auth_helper.make_nonce() auth_message = auth_pb2.AuthMessage() auth_message.name = self.name auth_message.type = auth_pb2.AuthMessage.CHALLENGE auth_message.nonce = self.nonce return auth_message
def run(self): while True: # Receive a "packet" data = self.auth.recv() auth_message = auth_pb2.AuthMessage() # Parse into object auth_message.ParseFromString(data) # handle request t = auth_message.type if t == auth_pb2.AuthMessage.HELLO: response = self.handle_hello(auth_message) elif t == auth_pb2.AuthMessage.RESPONSE: response = self.handle_response(auth_message) elif t == auth_pb2.AuthMessage.ERROR: response = self.handle_error(auth_message) # send response self.auth.send(response.SerializeToString())
def handle_response(self, response): if response.name in self.clients_by_name: client = self.clients_by_name[response.name] expected_response = auth_helper.sign_nonce(client.nonce, client.secret) if response.response == expected_response: token = auth_helper.make_nonce() token_message = auth_pb2.AuthMessage() token_message.name = response.name token_message.type = auth_pb2.AuthMessage.TOKEN token_message.token = token client.token = token return token_message # Sweet. User authenicated else: return self.make_error( "Failed to authenticated %s" % response.name, response.name) else: return self.make_error("Client %s does not exist" % response.name, response.name)
def make_error(self, message, name="Unknown"): error_message = auth_pb2.AuthMessage() error_message.name = name error_message.type = auth_pb2.AuthMessage.ERROR error_message.error_message = message return error_message