2018-03-16 04:40:37 -06:00
|
|
|
import base64
|
|
|
|
import math
|
2018-03-19 11:11:50 -06:00
|
|
|
import os
|
2018-04-04 06:14:22 -06:00
|
|
|
import RNS
|
2018-03-19 13:51:26 -06:00
|
|
|
import time
|
|
|
|
import atexit
|
2018-04-18 15:31:17 -06:00
|
|
|
import vendor.umsgpack as umsgpack
|
2018-03-16 04:40:37 -06:00
|
|
|
from cryptography.hazmat.primitives import hashes
|
|
|
|
from cryptography.hazmat.backends import default_backend
|
|
|
|
from cryptography.hazmat.primitives import serialization
|
2018-03-19 11:11:50 -06:00
|
|
|
from cryptography.hazmat.primitives.serialization import load_der_public_key
|
|
|
|
from cryptography.hazmat.primitives.serialization import load_der_private_key
|
2018-03-16 04:40:37 -06:00
|
|
|
from cryptography.hazmat.primitives.asymmetric import rsa
|
|
|
|
from cryptography.hazmat.primitives.asymmetric import padding
|
2018-03-16 03:50:37 -06:00
|
|
|
|
|
|
|
class Identity:
|
2018-04-17 09:46:48 -06:00
|
|
|
#KEYSIZE = 1536
|
|
|
|
KEYSIZE = 1024
|
|
|
|
DERKEYSIZE = KEYSIZE+272
|
2018-03-16 03:50:37 -06:00
|
|
|
|
2018-04-17 09:46:48 -06:00
|
|
|
# Non-configurable constants
|
|
|
|
PADDINGSIZE = 336 # In bits
|
|
|
|
HASHLENGTH = 256 # In bits
|
|
|
|
SIGLENGTH = KEYSIZE
|
2018-03-16 04:40:37 -06:00
|
|
|
|
2018-03-19 11:11:50 -06:00
|
|
|
# Storage
|
2018-03-19 13:51:26 -06:00
|
|
|
known_destinations = {}
|
2018-03-19 11:11:50 -06:00
|
|
|
|
2018-03-16 04:40:37 -06:00
|
|
|
@staticmethod
|
2018-03-20 05:32:41 -06:00
|
|
|
def remember(packet_hash, destination_hash, public_key, app_data = None):
|
2018-04-04 06:14:22 -06:00
|
|
|
RNS.log("Remembering "+RNS.prettyhexrep(destination_hash), RNS.LOG_VERBOSE)
|
2018-03-20 05:32:41 -06:00
|
|
|
Identity.known_destinations[destination_hash] = [time.time(), packet_hash, public_key, app_data]
|
|
|
|
|
2018-03-19 11:11:50 -06:00
|
|
|
|
|
|
|
@staticmethod
|
2018-03-20 05:32:41 -06:00
|
|
|
def recall(destination_hash):
|
2018-04-04 06:14:22 -06:00
|
|
|
RNS.log("Searching for "+RNS.prettyhexrep(destination_hash)+"...", RNS.LOG_DEBUG)
|
2018-03-20 05:32:41 -06:00
|
|
|
if destination_hash in Identity.known_destinations:
|
|
|
|
identity_data = Identity.known_destinations[destination_hash]
|
|
|
|
identity = Identity(public_only=True)
|
|
|
|
identity.loadPublicKey(identity_data[2])
|
2018-04-04 06:14:22 -06:00
|
|
|
RNS.log("Found "+RNS.prettyhexrep(destination_hash)+" in known destinations", RNS.LOG_DEBUG)
|
2018-03-20 05:32:41 -06:00
|
|
|
return identity
|
|
|
|
else:
|
2018-04-04 06:14:22 -06:00
|
|
|
RNS.log("Could not find "+RNS.prettyhexrep(destination_hash)+" in known destinations", RNS.LOG_DEBUG)
|
2018-03-20 05:32:41 -06:00
|
|
|
return None
|
2018-03-19 11:11:50 -06:00
|
|
|
|
2018-03-19 13:51:26 -06:00
|
|
|
@staticmethod
|
|
|
|
def saveKnownDestinations():
|
2018-04-04 06:14:22 -06:00
|
|
|
RNS.log("Saving known destinations to storage...", RNS.LOG_VERBOSE)
|
|
|
|
file = open(RNS.Reticulum.storagepath+"/known_destinations","w")
|
2018-04-18 15:31:17 -06:00
|
|
|
umsgpack.dump(Identity.known_destinations, file)
|
2018-03-19 13:51:26 -06:00
|
|
|
file.close()
|
2018-04-04 06:14:22 -06:00
|
|
|
RNS.log("Done saving known destinations to storage", RNS.LOG_VERBOSE)
|
2018-03-19 13:51:26 -06:00
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def loadKnownDestinations():
|
2018-04-04 06:14:22 -06:00
|
|
|
if os.path.isfile(RNS.Reticulum.storagepath+"/known_destinations"):
|
|
|
|
file = open(RNS.Reticulum.storagepath+"/known_destinations","r")
|
2018-04-18 15:31:17 -06:00
|
|
|
Identity.known_destinations = umsgpack.load(file)
|
2018-03-19 13:51:26 -06:00
|
|
|
file.close()
|
2018-04-04 06:14:22 -06:00
|
|
|
RNS.log("Loaded "+str(len(Identity.known_destinations))+" known destinations from storage", RNS.LOG_VERBOSE)
|
2018-03-19 13:51:26 -06:00
|
|
|
else:
|
2018-04-04 06:14:22 -06:00
|
|
|
RNS.log("Destinations file does not exist, so no known destinations loaded", RNS.LOG_VERBOSE)
|
2018-03-19 13:51:26 -06:00
|
|
|
|
2018-03-19 11:11:50 -06:00
|
|
|
@staticmethod
|
|
|
|
def fullHash(data):
|
|
|
|
digest = hashes.Hash(hashes.SHA256(), backend=default_backend())
|
|
|
|
digest.update(data)
|
|
|
|
|
|
|
|
return digest.finalize()
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def truncatedHash(data):
|
2018-03-16 04:40:37 -06:00
|
|
|
digest = hashes.Hash(hashes.SHA256(), backend=default_backend())
|
2018-03-19 11:11:50 -06:00
|
|
|
digest.update(data)
|
2018-03-16 04:40:37 -06:00
|
|
|
|
|
|
|
return digest.finalize()[:10]
|
|
|
|
|
2018-04-18 15:31:17 -06:00
|
|
|
@staticmethod
|
|
|
|
def getRandomHash():
|
|
|
|
return Identity.truncatedHash(os.urandom(10))
|
|
|
|
|
2018-03-19 11:11:50 -06:00
|
|
|
@staticmethod
|
|
|
|
def validateAnnounce(packet):
|
2018-04-04 06:14:22 -06:00
|
|
|
if packet.packet_type == RNS.Packet.ANNOUNCE:
|
|
|
|
RNS.log("Validating announce from "+RNS.prettyhexrep(packet.destination_hash), RNS.LOG_VERBOSE)
|
2018-03-19 11:11:50 -06:00
|
|
|
destination_hash = packet.destination_hash
|
|
|
|
public_key = packet.data[10:Identity.DERKEYSIZE/8+10]
|
|
|
|
random_hash = packet.data[Identity.DERKEYSIZE/8+10:Identity.DERKEYSIZE/8+20]
|
|
|
|
signature = packet.data[Identity.DERKEYSIZE/8+20:Identity.DERKEYSIZE/8+20+Identity.KEYSIZE/8]
|
|
|
|
app_data = ""
|
|
|
|
if len(packet.data) > Identity.DERKEYSIZE/8+20+Identity.KEYSIZE/8:
|
|
|
|
app_data = packet.data[Identity.DERKEYSIZE/8+20+Identity.KEYSIZE/8:]
|
|
|
|
|
|
|
|
signed_data = destination_hash+public_key+random_hash+app_data
|
|
|
|
|
2018-03-19 13:51:26 -06:00
|
|
|
announced_identity = Identity(public_only=True)
|
2018-03-19 11:11:50 -06:00
|
|
|
announced_identity.loadPublicKey(public_key)
|
|
|
|
|
2018-03-20 09:57:26 -06:00
|
|
|
if announced_identity.pub != None and announced_identity.validate(signature, signed_data):
|
2018-04-04 06:14:22 -06:00
|
|
|
RNS.Identity.remember(RNS.Identity.fullHash(packet.raw), destination_hash, public_key)
|
|
|
|
RNS.log("Stored valid announce from "+RNS.prettyhexrep(destination_hash), RNS.LOG_INFO)
|
2018-03-20 05:32:41 -06:00
|
|
|
del announced_identity
|
|
|
|
return True
|
2018-03-19 11:11:50 -06:00
|
|
|
else:
|
2018-04-24 16:20:57 -06:00
|
|
|
RNS.log("Received invalid announce", RNS.LOG_DEBUG)
|
2018-03-20 05:32:41 -06:00
|
|
|
del announced_identity
|
|
|
|
return False
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def exitHandler():
|
|
|
|
Identity.saveKnownDestinations()
|
2018-03-19 11:11:50 -06:00
|
|
|
|
|
|
|
|
2018-04-24 09:50:58 -06:00
|
|
|
@staticmethod
|
|
|
|
def from_file(path):
|
|
|
|
identity = Identity(public_only=True)
|
|
|
|
if identity.load(path):
|
|
|
|
return identity
|
|
|
|
else:
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
def __init__(self,public_only=False):
|
|
|
|
# Initialize keys to none
|
|
|
|
self.prv = None
|
|
|
|
self.pub = None
|
|
|
|
self.prv_bytes = None
|
|
|
|
self.pub_bytes = None
|
|
|
|
self.hash = None
|
|
|
|
self.hexhash = None
|
|
|
|
|
|
|
|
if not public_only:
|
|
|
|
self.createKeys()
|
|
|
|
|
2018-03-16 04:40:37 -06:00
|
|
|
def createKeys(self):
|
|
|
|
self.prv = rsa.generate_private_key(
|
|
|
|
public_exponent=65337,
|
|
|
|
key_size=Identity.KEYSIZE,
|
|
|
|
backend=default_backend()
|
|
|
|
)
|
|
|
|
self.prv_bytes = self.prv.private_bytes(
|
|
|
|
encoding=serialization.Encoding.DER,
|
|
|
|
format=serialization.PrivateFormat.PKCS8,
|
|
|
|
encryption_algorithm=serialization.NoEncryption()
|
|
|
|
)
|
|
|
|
self.pub = self.prv.public_key()
|
|
|
|
self.pub_bytes = self.pub.public_bytes(
|
|
|
|
encoding=serialization.Encoding.DER,
|
|
|
|
format=serialization.PublicFormat.SubjectPublicKeyInfo
|
|
|
|
)
|
|
|
|
|
2018-03-20 05:32:41 -06:00
|
|
|
self.updateHashes()
|
2018-03-16 04:40:37 -06:00
|
|
|
|
2018-04-24 09:50:58 -06:00
|
|
|
RNS.log("Identity keys created for "+RNS.prettyhexrep(self.hash), RNS.LOG_VERBOSE)
|
2018-03-16 04:40:37 -06:00
|
|
|
|
|
|
|
def getPrivateKey(self):
|
|
|
|
return self.prv_bytes
|
|
|
|
|
|
|
|
def getPublicKey(self):
|
|
|
|
return self.pub_bytes
|
|
|
|
|
2018-04-24 09:50:58 -06:00
|
|
|
def loadPrivateKey(self, prv_bytes):
|
|
|
|
try:
|
|
|
|
self.prv_bytes = prv_bytes
|
|
|
|
self.prv = serialization.load_der_private_key(
|
|
|
|
self.prv_bytes,
|
|
|
|
password=None,
|
|
|
|
backend=default_backend()
|
|
|
|
)
|
|
|
|
self.pub = self.prv.public_key()
|
|
|
|
self.pub_bytes = self.pub.public_bytes(
|
|
|
|
encoding=serialization.Encoding.DER,
|
|
|
|
format=serialization.PublicFormat.SubjectPublicKeyInfo
|
|
|
|
)
|
|
|
|
self.updateHashes()
|
|
|
|
|
|
|
|
return True
|
|
|
|
|
|
|
|
except Exception as e:
|
|
|
|
RNS.log("Failed to load identity key", RNS.LOG_ERROR)
|
|
|
|
RNS.log("The contained exception was: "+str(e))
|
|
|
|
return False
|
2018-03-16 04:40:37 -06:00
|
|
|
|
|
|
|
def loadPublicKey(self, key):
|
2018-03-20 09:57:26 -06:00
|
|
|
try:
|
|
|
|
self.pub_bytes = key
|
|
|
|
self.pub = load_der_public_key(self.pub_bytes, backend=default_backend())
|
|
|
|
self.updateHashes()
|
|
|
|
except Exception as e:
|
2018-04-04 06:14:22 -06:00
|
|
|
RNS.log("Error while loading public key, the contained exception was: "+str(e), RNS.LOG_ERROR)
|
2018-03-20 05:32:41 -06:00
|
|
|
|
|
|
|
def updateHashes(self):
|
|
|
|
self.hash = Identity.truncatedHash(self.pub_bytes)
|
|
|
|
self.hexhash = self.hash.encode("hex_codec")
|
2018-03-16 04:40:37 -06:00
|
|
|
|
2018-04-24 09:50:58 -06:00
|
|
|
def save(self, path):
|
|
|
|
try:
|
|
|
|
with open(path, "w") as key_file:
|
|
|
|
key_file.write(self.prv_bytes)
|
|
|
|
return True
|
|
|
|
return False
|
|
|
|
except Exception as e:
|
|
|
|
RNS.log("Error while saving identity to "+str(path), RNS.LOG_ERROR)
|
|
|
|
RNS.log("The contained exception was: "+str(e))
|
2018-03-16 04:40:37 -06:00
|
|
|
|
2018-04-24 09:50:58 -06:00
|
|
|
def load(self, path):
|
|
|
|
try:
|
|
|
|
with open(path, "r") as key_file:
|
|
|
|
prv_bytes = key_file.read()
|
|
|
|
return self.loadPrivateKey(prv_bytes)
|
|
|
|
return False
|
|
|
|
except Exception as e:
|
|
|
|
RNS.log("Error while loading identity from "+str(path), RNS.LOG_ERROR)
|
|
|
|
RNS.log("The contained exception was: "+str(e))
|
2018-03-16 04:40:37 -06:00
|
|
|
|
|
|
|
def encrypt(self, plaintext):
|
2018-03-20 05:32:41 -06:00
|
|
|
if self.pub != None:
|
2018-03-16 04:40:37 -06:00
|
|
|
chunksize = (Identity.KEYSIZE-Identity.PADDINGSIZE)/8
|
|
|
|
chunks = int(math.ceil(len(plaintext)/(float(chunksize))))
|
|
|
|
|
|
|
|
ciphertext = "";
|
|
|
|
for chunk in range(chunks):
|
|
|
|
start = chunk*chunksize
|
|
|
|
end = (chunk+1)*chunksize
|
|
|
|
if (chunk+1)*chunksize > len(plaintext):
|
|
|
|
end = len(plaintext)
|
|
|
|
|
|
|
|
ciphertext += self.pub.encrypt(
|
|
|
|
plaintext[start:end],
|
|
|
|
padding.OAEP(
|
|
|
|
mgf=padding.MGF1(algorithm=hashes.SHA1()),
|
|
|
|
algorithm=hashes.SHA1(),
|
|
|
|
label=None
|
|
|
|
)
|
|
|
|
)
|
|
|
|
return ciphertext
|
|
|
|
else:
|
2018-03-20 05:32:41 -06:00
|
|
|
raise KeyError("Encryption failed because identity does not hold a public key")
|
2018-03-16 04:40:37 -06:00
|
|
|
|
|
|
|
|
|
|
|
def decrypt(self, ciphertext):
|
|
|
|
if self.prv != None:
|
2018-03-20 09:57:26 -06:00
|
|
|
plaintext = None
|
|
|
|
try:
|
|
|
|
chunksize = (Identity.KEYSIZE)/8
|
|
|
|
chunks = int(math.ceil(len(ciphertext)/(float(chunksize))))
|
|
|
|
|
|
|
|
plaintext = "";
|
|
|
|
for chunk in range(chunks):
|
|
|
|
start = chunk*chunksize
|
|
|
|
end = (chunk+1)*chunksize
|
|
|
|
if (chunk+1)*chunksize > len(ciphertext):
|
|
|
|
end = len(ciphertext)
|
|
|
|
|
|
|
|
plaintext += self.prv.decrypt(
|
|
|
|
ciphertext[start:end],
|
|
|
|
padding.OAEP(
|
|
|
|
mgf=padding.MGF1(algorithm=hashes.SHA1()),
|
|
|
|
algorithm=hashes.SHA1(),
|
|
|
|
label=None
|
|
|
|
)
|
2018-03-16 04:40:37 -06:00
|
|
|
)
|
2018-03-20 09:57:26 -06:00
|
|
|
except:
|
2018-04-16 09:13:39 -06:00
|
|
|
RNS.log("Decryption by "+RNS.prettyhexrep(self.hash)+" failed", RNS.LOG_VERBOSE)
|
2018-03-20 09:57:26 -06:00
|
|
|
|
2018-03-16 04:40:37 -06:00
|
|
|
return plaintext;
|
|
|
|
else:
|
|
|
|
raise KeyError("Decryption failed because identity does not hold a private key")
|
|
|
|
|
|
|
|
|
|
|
|
def sign(self, message):
|
|
|
|
if self.prv != None:
|
|
|
|
signer = self.prv.signer(
|
|
|
|
padding.PSS(
|
|
|
|
mgf=padding.MGF1(hashes.SHA256()),
|
|
|
|
salt_length=padding.PSS.MAX_LENGTH
|
|
|
|
),
|
|
|
|
hashes.SHA256()
|
|
|
|
)
|
|
|
|
signer.update(message)
|
|
|
|
return signer.finalize()
|
|
|
|
else:
|
|
|
|
raise KeyError("Signing failed because identity does not hold a private key")
|
|
|
|
|
2018-03-19 11:11:50 -06:00
|
|
|
def validate(self, signature, message):
|
|
|
|
if self.pub != None:
|
|
|
|
try:
|
|
|
|
self.pub.verify(
|
|
|
|
signature,
|
|
|
|
message,
|
|
|
|
padding.PSS(
|
|
|
|
mgf=padding.MGF1(hashes.SHA256()),
|
|
|
|
salt_length=padding.PSS.MAX_LENGTH
|
|
|
|
),
|
|
|
|
hashes.SHA256()
|
|
|
|
)
|
|
|
|
return True
|
2018-04-17 09:46:48 -06:00
|
|
|
except Exception as e:
|
2018-03-19 11:11:50 -06:00
|
|
|
return False
|
|
|
|
else:
|
|
|
|
raise KeyError("Signature validation failed because identity does not hold a public key")
|
|
|
|
|
2018-04-17 09:46:48 -06:00
|
|
|
def prove(self, packet, destination=None):
|
|
|
|
signature = self.sign(packet.packet_hash)
|
|
|
|
if RNS.Reticulum.should_use_implicit_proof():
|
|
|
|
proof_data = signature
|
|
|
|
else:
|
|
|
|
proof_data = packet.packet_hash + signature
|
|
|
|
|
|
|
|
if destination == None:
|
|
|
|
destination = packet.generateProofDestination()
|
|
|
|
|
2018-04-04 06:14:22 -06:00
|
|
|
proof = RNS.Packet(destination, proof_data, RNS.Packet.PROOF)
|
2018-03-20 05:32:41 -06:00
|
|
|
proof.send()
|
2018-04-24 09:50:58 -06:00
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
return RNS.prettyhexrep(self.hash)
|