Пример #1
0
    def send_client_com(self,dst,cleartext):
		""" Process a client-com message from client """
		msg = {'type':'client-com', 'src': self.id,'dst': dst, 'data': {}}
		# Client in session
		client = self.clients[str(dst)]
		 
		# Cipher: new private key + old public key
		client.new_public_key,client.new_private_key = keys.verify_cipher_suite(client.cipher_suite)
		client.client_client_master_secret = keys.generate_master_secret(client.received_public_key, client.new_private_key)
		client.random = os.urandom(32)
		client.client_client_final_master = keys.generate_final_master_secret(client.client_client_master_secret,client.received_random + client.random)
		 
		ciphertext ,iv = keys.encrypt(client.cipher_suite,client.client_client_final_master ,cleartext)
		client.digest = keys.message_authentication(client.cipher_suite, client.client_client_final_master, ciphertext)
		
		client.private_key = client.new_private_key
		 
		msg['data'] = {'hash':base64.b64encode(client.digest),
					   'iv' : base64.b64encode(iv),
					   'public_key': client.new_public_key,
					   'ciphertext': base64.b64encode(ciphertext),
					   'random': base64.b64encode(client.random)
					   }

		self.secure_send(msg)
    def send(self, obj):
        """Send an object to this client.
        """
        try:
            if obj['type'] == 'secure':
                new_public_key, new_private_key = keys.verify_cipher_suite(
                    self.cipher_suite)
                #print type(self.received_public_key)
                new_master_secret = keys.generate_master_secret(
                    self.received_public_key, new_private_key)
                self.rand_server = os.urandom(32)
                self.final_master_secret = keys.generate_final_master_secret(
                    new_master_secret, self.random_client + self.rand_server)
                ciphertext, server_iv = keys.encrypt(self.cipher_suite,
                                                     self.final_master_secret,
                                                     obj['payload'])
                obj['payload'] = {
                    'ciphertext': base64.b64encode(ciphertext),
                    'public_key': new_public_key
                }
                server_hash = keys.message_authentication(
                    self.cipher_suite, self.final_master_secret, ciphertext)
                obj['sa-data'] = {
                    'hash': base64.b64encode(server_hash),
                    'iv': base64.b64encode(server_iv),
                    'random': base64.b64encode(self.rand_server)
                }
                self.private_key = new_private_key
                self.bufout += json.dumps(obj) + "\n\n"
            else:
                self.bufout += json.dumps(obj) + "\n\n"

        except:
            # It should never happen! And not be reported to the client!
            logging.exception("Client.send(%s)", self)
    def send_client_com(self,dst,cleartext):
		""" Process a client-com message from client """
		msg = {'type':'client-com', 'src': self.id,'dst': dst, 'data': {}}
		# Client in session
		client = self.clients[str(dst)]
		 
		# Cipher: new private key + old public key
		new_public_key, new_private_key = keys.verify_cipher_suite(client.cipher_suite)
		client.client_client_master_secret = keys.generate_master_secret(client.received_public_key, new_private_key)
		tmp_random = os.urandom(32)
		client.client_client_final_master = keys.generate_final_master_secret(client.client_client_master_secret,client.received_random + tmp_random)
		 
		ciphertext ,iv = keys.encrypt(client.cipher_suite,client.client_client_final_master ,cleartext)
		client.digest = keys.message_authentication(client.cipher_suite, client.client_client_final_master, ciphertext)
		
		 
		msg['data'] = {'hash':base64.b64encode(client.digest),
					   'iv' : base64.b64encode(iv),
					   'public_key': new_public_key,
					   'ciphertext': base64.b64encode(ciphertext),
					   'random': base64.b64encode(tmp_random)
					   }

		# Assinar toda a mensagem
		signature = keys.signClient(self.session, self.obj[0], json.dumps(msg,sort_keys = True))
		msg['sign'] = base64.b64encode(signature)

		Hash = keys.hash(msg)
		self.dst_val[Hash] = msg.copy()

		self.secure_send(msg)
Пример #4
0
def encrypt(key, input_file):
    encrypted_data = b''
    while True:
        data = input_file.read(64)
        if not data:
            break
        block = keys.encrypt(key, data)
        encrypted_data += block + b'\n'
    return encrypted_data
Пример #5
0
    def secure_send(self, msg_json):
		""" Process a secure message from server """
		# Cipher: new private key + old public key
		msg = {'type': 'secure', 'sa-data':{}, 'payload':{}}
		new_public_key, self.new_private_key = keys.verify_cipher_suite(self.cipher_suite)
					
		new_master_secret = keys.generate_master_secret(self.server_public_key, self.new_private_key)		
		self.rand_client = os.urandom(32)
		new_final_master_secret = keys.generate_final_master_secret(new_master_secret, self.rand_client + self.rand_srv)
		ciphertext , client_iv = keys.encrypt(self.cipher_suite,new_final_master_secret,msg_json)
				
		msg['sa-data'] = {'hash': base64.b64encode(keys.message_authentication(self.cipher_suite, new_final_master_secret, ciphertext)),
			'iv': base64.b64encode(client_iv), 'random':base64.b64encode(self.rand_client)}
		msg['payload'] = {'ciphertext': base64.b64encode(ciphertext),'public_key': new_public_key}
		
		self.sock.send(msg)
    def send(self, obj):
        """Send an object to this client.
        """
        try:
            tmp = obj.copy()

            if obj['type'] == 'secure':
                new_public_key, new_private_key = keys.verify_cipher_suite(
                    self.cipher_suite)
                #print type(self.received_public_key)
                new_master_secret = keys.generate_master_secret(
                    self.received_public_key, new_private_key)
                tmp_rand_server = os.urandom(32)
                self.final_master_secret = keys.generate_final_master_secret(
                    new_master_secret, self.rand_client + tmp_rand_server)
                ciphertext, server_iv = keys.encrypt(self.cipher_suite,
                                                     self.final_master_secret,
                                                     obj['payload'])
                obj['payload'] = {
                    'ciphertext': base64.b64encode(ciphertext),
                    'public_key': new_public_key
                }
                server_hash = keys.message_authentication(
                    self.cipher_suite, self.final_master_secret, ciphertext)
                obj['sa-data'] = {
                    'hash': base64.b64encode(server_hash),
                    'iv': base64.b64encode(server_iv),
                    'random': base64.b64encode(tmp_rand_server)
                }

                # Assinatura
                serversign = keys.signServer(serverKey,
                                             json.dumps(obj, sort_keys=True))
                obj['sign'] = base64.b64encode(serversign)

                if 'ack' not in tmp['payload']['type']:
                    #print 'TMP'
                    Hash = keys.hash(obj)
                    dst_val[Hash] = obj.copy()

                self.bufout += json.dumps(obj) + "\n\n"
            else:
                self.bufout += json.dumps(obj) + "\n\n"

        except:
            # It should never happen! And not be reported to the client!
            logging.exception("Client.send(%s)", self)
    def secure_send(self, msg_json):
		""" Process a secure message from server """
		# Cipher: new private key + old public key
		msg = {'type': 'secure', 'sa-data':{}, 'payload':{} }
		new_public_key, new_private_key = keys.verify_cipher_suite(self.cipher_suite)
					
		new_master_secret = keys.generate_master_secret(self.server_public_key, new_private_key)		
		tmp_rand_client = os.urandom(32)
		new_final_master_secret = keys.generate_final_master_secret(new_master_secret, self.rand_srv + tmp_rand_client)
		ciphertext , client_iv = keys.encrypt(self.cipher_suite,new_final_master_secret,msg_json)
				
		msg['sa-data'] = {'hash': base64.b64encode(keys.message_authentication(self.cipher_suite, new_final_master_secret, ciphertext)),
			'iv': base64.b64encode(client_iv), 'random':base64.b64encode(tmp_rand_client)}
		msg['payload'] = {'ciphertext': base64.b64encode(ciphertext),'public_key': new_public_key}

		# assinar toda a msg
		signature = keys.signClient(self.session, self.obj[0], json.dumps(msg,sort_keys = True))
		msg['sign'] = base64.b64encode(signature)

		if 'src' in msg_json.keys() and msg_json['type'] != 'ack':
			h = keys.hash(msg_json)
			self.dst_val[h] = msg_json

			#save secure msg
			Hash = keys.hash(msg)
			self.dst_val[Hash] = msg.copy()

			self.sock.send(msg)

			return

		#save secure msg
		Hash = keys.hash(msg)
		self.dst_val[Hash] = msg.copy()

		self.sock.send(msg)
		return
Пример #8
0
import keys
import os 
key = os.urandom(32)
text = 'foobarnsvnsnvs svdsdv'

ciphertext = keys.encrypt('ECDHE-AES128_OFB-SHA256',key,text)
print ciphertext


    def receive_client_connect(self, reply):
		""" Process a client-connect message from client (phase > 1) """
		msg = {'type':'client-connect'}

		if reply['phase'] == 1:

			Hash = keys.hash(reply)
			ack = {'type':'ack','hash':Hash, 'src': self.id, 'dst': reply['src']}
			self.secure_send(ack)

			#get peer_client cert
			cli_cert = base64.b64decode(reply['data']['certificate'])

			#cert verification
			cert = openssl.load_certificate(openssl.FILETYPE_ASN1, cli_cert)

			if keys.verifycert(cert,self.store) == False:
				logging.warning("Invalid Certificate!!")
				return

			self.addClient(str(reply['src']))
			client= self.clients[str(reply['src'])]
			
			if str(reply['src']) not in self.clients:
				logging.warning('Client not supported!')
				
			ciphers = ['ECDHE-RSA-CTR-SHA256', 'ECDHE-AES256_CTR-SHA384','ECDHE-AES128_CTR-SHA256']
			
			# Cipher_suite selection mode
			cipher = [c for c in reply['ciphers'] if c in ciphers]
			
			if cipher == []:
				logging.warning('Does not support cipher spec!')
				return	


			msg['src'] =  reply['dst']	
			msg['dst'] =  reply['src']
			msg['phase'] = reply['phase']+1
			msg['ciphers'] = cipher[0]

			# Update
			client.cipher_suite = msg['ciphers']
			client.cert = cli_cert

			client.randomCH = os.urandom(32)

			msg['data'] = {'certificate': base64.b64encode(self.cert),'challenge':base64.b64encode(client.randomCH)}

			Hash = keys.hash(msg)
			self.dst_val[Hash] = msg.copy()

			self.secure_send(msg)
			return

		if reply['phase'] == 2:

			Hash = keys.hash(reply)
			ack = {'type':'ack','hash':Hash, 'src': self.id, 'dst': reply['src']}
			self.secure_send(ack)


			#get peer_client cert
			cli_cert = base64.b64decode(reply['data']['certificate'])

			#cert verification
			cert = openssl.load_certificate(openssl.FILETYPE_ASN1,cli_cert)

			if keys.verifycert(cert,self.store) == False:
				logging.warning("Invalid Certificate!!")
				return

			client = self.clients[str(reply['src'])]
			
			if reply['ciphers'] not in client.cipher_suite:
				logging.warning('Does not support cipher spec!')
				return
				
			# Update
			client.cipher_suite = reply['ciphers']
			client.cert = cli_cert

			peerRandom = base64.b64decode(reply['data']['challenge'])
			client.randomCH = os.urandom(32)

			sign_peerRandom = keys.signClient(self.session, self.obj[0], peerRandom)

			msg['dst'] =  reply['src']
			msg['src'] =  reply['dst']
			msg['phase'] = reply['phase'] +1
			msg['ciphers'] = reply['ciphers']

			msg['data'] = {'sign_challenge':base64.b64encode(sign_peerRandom),'challenge':base64.b64encode(client.randomCH)}

			Hash = keys.hash(msg)
			self.dst_val[Hash] = msg.copy()

			self.secure_send(msg)
			return


		if reply['phase'] == 3:

			Hash = keys.hash(reply)
			ack = {'type':'ack','hash':Hash, 'src': self.id, 'dst': reply['src']}
			self.secure_send(ack)

			client = self.clients[str(reply['src'])]

			# get client sign
			sign = base64.b64decode(reply['data']['sign_challenge'])

			#validation
			if keys.verifySign(sign, client.cert, client.randomCH)== False:
				logging.warning("Invalid Signature!!")
				return



			peerRandom = base64.b64decode(reply['data']['challenge'])

			sign_peerRandom = keys.signClient(self.session, self.obj[0], peerRandom)

			msg['data'] = {'sign_challenge':base64.b64encode(sign_peerRandom)}


			client.cipher_suite = reply['ciphers']

			msg['dst'] =  reply['src']
			msg['src'] =  reply['dst']
			msg['phase'] = reply['phase'] +1


			Hash = keys.hash(msg)
			self.dst_val[Hash] = msg.copy()

			self.secure_send(msg)
			return

		if reply['phase'] == 4:

			Hash = keys.hash(reply)
			ack = {'type':'ack','hash':Hash, 'src': self.id, 'dst': reply['src']}
			self.secure_send(ack)

			client = self.clients[str(reply['src'])]

			# get client sign
			sign = base64.b64decode(reply['data']['sign_challenge'])

			#validation
			if keys.verifySign(sign, client.cert, client.randomCH) == False:
				logging.warning("Invalid Signature!!")
				return

			print "\n\n"
			print "Challenge Response Complete!!"
			print "\n\n"

			client.public_key, client.private_key = keys.verify_cipher_suite(client.cipher_suite)
			client.random = os.urandom(32)
			msg['data'] = {'public_key': client.public_key, 'random': base64.b64encode(client.random)}

			msg['dst'] =  reply['src']
			msg['src'] =  reply['dst']
			msg['phase'] = reply['phase']+1
			#msg['ciphers'] = reply['ciphers']


			# Assinar toda a mensagem
			signature = keys.signClient(self.session, self.obj[0], json.dumps(msg,sort_keys = True))
			msg['sign'] = base64.b64encode(signature)

			Hash = keys.hash(msg)
			self.dst_val[Hash] = msg.copy()

			self.secure_send(msg)
			return

		if reply['phase'] == 5:

			Hash = keys.hash(reply)
			ack = {'type':'ack','hash':Hash, 'src': self.id, 'dst': reply['src']}
			sign_ack = keys.signClient(self.session, self.obj[0], json.dumps(ack,sort_keys = True))
			ack['sign'] = base64.b64encode(sign_ack)
			self.secure_send(ack)

			client = self.clients[str(reply['src'])]


			# get client sign
			sign = base64.b64decode(reply['sign'])
			del reply['sign']

			#validation
			if keys.verifySign(sign, client.cert, json.dumps(reply,sort_keys=True)) == False:
				logging.warning("Invalid Signature!!")
				return

			# CONTINUE

			#client.cipher_suite = reply['ciphers']



			client.public_key, client.private_key = keys.verify_cipher_suite(client.cipher_suite)

			client.random = os.urandom(32)
			client.received_public_key = keys.deserialize_public_key(base64.b64decode(reply['data']['public_key']))
			client.received_random = base64.b64decode(reply['data']['random'])
			client.client_client_master_secret = keys.generate_master_secret(client.received_public_key,client.private_key)
			client.client_client_final_master = keys.generate_final_master_secret(client.client_client_master_secret,client.received_random+client.random)

			msg['data'] = {'public_key': client.public_key, 'random':base64.b64encode(client.random)}
			msg['dst'] =  reply['src']
			msg['src'] =  reply['dst']
			msg['phase'] = reply['phase'] +1

			# enviar info do Hardware
			info_hash = keys.participantConsistency_Hash()
			info = keys.participantConsistency()

			# cifrar info do Hardware
			tmp  = { 'hash': info_hash, 'info':info}
			encrypt_info, iv  = keys.encrypt(client.cipher_suite, client.client_client_final_master, tmp )

			msg['encrypt_hardware'] ={ 'encrypt_info':base64.b64encode(encrypt_info) , 'iv': base64.b64encode(iv)}


			# Assinar toda a mensagem
			signature = keys.signClient(self.session, self.obj[0], json.dumps(msg,sort_keys = True))
			msg['sign'] = base64.b64encode(signature)


			Hash = keys.hash(msg)
			self.dst_val[Hash] = msg.copy()

			self.secure_send(msg)
			return

		if reply['phase'] == 6:

			Hash = keys.hash(reply)
			ack = {'type':'ack','hash':Hash, 'src': self.id, 'dst': reply['src']}
			sign_ack = keys.signClient(self.session, self.obj[0], json.dumps(ack,sort_keys = True))
			ack['sign'] = base64.b64encode(sign_ack)
			self.secure_send(ack)

			client = self.clients[str(reply['src'])]

			# get client sign
			sign = base64.b64decode(reply['sign'])
			del reply['sign']

			#validation
			if keys.verifySign(sign, client.cert, json.dumps(reply,sort_keys=True)) == False:
				logging.warning("Invalid Signature!!")
				return

			# CONTINUE

			client.received_public_key = keys.deserialize_public_key(base64.b64decode(reply['data']['public_key']))
			client.client_client_master_secret = keys.generate_master_secret(client.received_public_key,client.private_key )
			client.received_random = base64.b64decode(reply['data']['random'])
			client.client_client_final_master = keys.generate_final_master_secret(client.client_client_master_secret,client.random+client.received_random )


			to_decrypt = base64.b64decode(reply['encrypt_hardware']['encrypt_info'])
			iv_todecrypt =  base64.b64decode(reply['encrypt_hardware']['iv'])

			cleartext = keys.decrypt(client.cipher_suite , client.client_client_final_master, to_decrypt ,iv_todecrypt)

			if client.cert in self.part_cons.keys():
				if self.part_cons[client.cert] != (cleartext['hash'][1], cleartext['info'][1]):
					print 'Hard novo!'
					print '\n Mac Adrress'+ str(cleartext['info']['brand'])

			# Update
			self.part_cons[client.cert] = (cleartext['hash'][1], cleartext['info'][1])

			print 'Connection to the Client finished with sucess!\n'
			return