reticulum/RNS/Destination.py

366 wiersze
14 KiB
Python
Czysty Zwykły widok Historia

2016-05-29 20:20:44 +00:00
import base64
2018-03-16 09:50:37 +00:00
import math
import RNS
2018-03-19 15:39:08 +00:00
2016-05-29 20:20:44 +00:00
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives.asymmetric import padding
2018-04-16 15:13:39 +00:00
class Callbacks:
2020-08-13 10:15:56 +00:00
def __init__(self):
self.link_established = None
self.packet = None
self.proof_requested = None
2018-03-19 15:39:08 +00:00
2016-05-29 20:20:44 +00:00
class Destination:
"""
A class used to describe endpoints in a Reticulum Network. Destination
instances are used both to create outgoing and incoming endpoints. The
destination type will decide if encryption, and what type, is used in
communication with the endpoint. A destination can also announce its
presence on the network, which will also distribute necessary keys for
encrypted communication with it.
:param identity: An instance of :ref:`RNS.Identity<Identity>`. Can hold only public keys for an outgoing destination, or holding private keys for an ingoing.
:param direction: ``RNS.Destination.IN`` or ``RNS.Destination.OUT``
:param type: ``RNS.Destination.SINGLE``, ``RNS.Destination.GROUP`` or ``RNS.Destination.PLAIN``.
:param app_name: A string specifying the app name.
:param \*aspects: Any non-zero number of string arguments.
"""
2020-08-13 10:15:56 +00:00
KEYSIZE = RNS.Identity.KEYSIZE;
PADDINGSIZE= RNS.Identity.PADDINGSIZE;
2018-03-16 09:50:37 +00:00
2020-08-13 10:15:56 +00:00
# Constants
SINGLE = 0x00
GROUP = 0x01
PLAIN = 0x02
LINK = 0x03
types = [SINGLE, GROUP, PLAIN, LINK]
2016-05-29 20:20:44 +00:00
2020-08-13 10:15:56 +00:00
PROVE_NONE = 0x21
PROVE_APP = 0x22
PROVE_ALL = 0x23
proof_strategies = [PROVE_NONE, PROVE_APP, PROVE_ALL]
2018-03-20 11:32:41 +00:00
2020-08-13 10:15:56 +00:00
IN = 0x11;
OUT = 0x12;
directions = [IN, OUT]
2016-05-29 20:20:44 +00:00
2020-08-13 10:15:56 +00:00
@staticmethod
2021-05-15 08:57:54 +00:00
def full_name(app_name, *aspects):
"""
:returns: A string containing the full human-readable name of the destination, for an app_name and a number of aspects.
"""
2020-08-13 10:15:56 +00:00
# Check input values and build name string
if "." in app_name: raise ValueError("Dots can't be used in app names")
2016-05-29 20:20:44 +00:00
2020-08-13 10:15:56 +00:00
name = app_name
for aspect in aspects:
if "." in aspect: raise ValueError("Dots can't be used in aspects")
name = name + "." + aspect
2016-05-29 20:20:44 +00:00
2020-08-13 10:15:56 +00:00
return name
2016-05-29 20:20:44 +00:00
2020-08-13 10:15:56 +00:00
@staticmethod
2021-05-15 08:57:54 +00:00
def hash(app_name, *aspects):
"""
:returns: A destination name in adressable hash form, for an app_name and a number of aspects.
"""
2021-05-15 08:57:54 +00:00
name = Destination.full_name(app_name, *aspects)
2016-05-29 20:20:44 +00:00
2020-08-13 10:15:56 +00:00
# Create a digest for the destination
digest = hashes.Hash(hashes.SHA256(), backend=default_backend())
digest.update(name.encode("UTF-8"))
2016-05-29 20:20:44 +00:00
2020-08-13 10:15:56 +00:00
return digest.finalize()[:10]
2016-05-29 20:20:44 +00:00
2021-05-15 08:57:54 +00:00
@staticmethod
def app_and_aspects_from_name(full_name):
"""
:returns: A tuple containing the app name and a list of aspects, for a full-name string.
"""
2021-05-15 08:57:54 +00:00
components = full_name.split(".")
return (components[0], components[1:])
@staticmethod
def hash_from_name_and_identity(full_name, identity):
"""
:returns: A destination name in adressable hash form, for a full name string and Identity instance.
"""
2021-05-15 08:57:54 +00:00
app_name, aspects = Destination.app_and_aspects_from_name(full_name)
aspects.append(identity.hexhash)
return Destination.hash(app_name, *aspects)
2016-05-29 20:20:44 +00:00
2020-08-13 10:15:56 +00:00
def __init__(self, identity, direction, type, app_name, *aspects):
# Check input values and build name string
if "." in app_name: raise ValueError("Dots can't be used in app names")
if not type in Destination.types: raise ValueError("Unknown destination type")
if not direction in Destination.directions: raise ValueError("Unknown destination direction")
self.callbacks = Callbacks()
self.type = type
self.direction = direction
self.proof_strategy = Destination.PROVE_NONE
self.mtu = 0
2016-05-29 20:20:44 +00:00
2020-08-13 10:15:56 +00:00
self.links = []
2018-04-16 15:13:39 +00:00
2020-08-13 10:15:56 +00:00
if identity != None and type == Destination.SINGLE:
aspects = aspects+(identity.hexhash,)
2018-03-20 11:32:41 +00:00
2020-08-13 10:15:56 +00:00
if identity == None and direction == Destination.IN and self.type != Destination.PLAIN:
identity = RNS.Identity()
aspects = aspects+(identity.hexhash,)
2018-03-16 10:40:37 +00:00
2020-08-13 10:15:56 +00:00
self.identity = identity
2018-03-16 10:40:37 +00:00
2021-05-15 08:57:54 +00:00
self.name = Destination.full_name(app_name, *aspects)
self.hash = Destination.hash(app_name, *aspects)
2020-08-13 10:15:56 +00:00
self.hexhash = self.hash.hex()
2021-05-15 11:06:50 +00:00
self.default_app_data = None
2016-05-29 20:20:44 +00:00
2020-08-13 10:15:56 +00:00
self.callback = None
self.proofcallback = None
2016-05-29 20:20:44 +00:00
2020-08-13 10:15:56 +00:00
RNS.Transport.registerDestination(self)
2016-06-03 17:02:02 +00:00
2016-05-29 20:20:44 +00:00
2020-08-13 10:15:56 +00:00
def __str__(self):
"""
:returns: A human-readable representation of the destination including addressable hash and full name.
"""
2020-08-13 10:15:56 +00:00
return "<"+self.name+"/"+self.hexhash+">"
2016-05-29 20:20:44 +00:00
2020-08-13 10:15:56 +00:00
def link_established_callback(self, callback):
"""
Registers a function to be called when a link has been established to
this destination.
:param callback: A function or method to be called
"""
2020-08-13 10:15:56 +00:00
self.callbacks.link_established = callback
2018-04-16 15:13:39 +00:00
2020-08-13 10:15:56 +00:00
def packet_callback(self, callback):
"""
Registers a function to be called when a packet has been received by
this destination.
:param callback: A function or method to be called
"""
2020-08-13 10:15:56 +00:00
self.callbacks.packet = callback
2016-05-29 20:20:44 +00:00
2020-08-13 10:15:56 +00:00
def proof_requested_callback(self, callback):
"""
Registers a function to be called when a proof has been requested for
a packet sent to this destination. Allows control over when and if
proofs should be returned for received packets.
:param callback: A function or method to be called. The callback must return one of True or False. If the callback returns True, a proof will be sent. If it returns False, a proof will not be sent.
"""
2020-08-13 10:15:56 +00:00
self.callbacks.proof_requested = callback
2018-03-20 11:32:41 +00:00
2020-08-13 10:15:56 +00:00
def set_proof_strategy(self, proof_strategy):
"""
Sets the destinations proof strategy.
:param proof_strategy: One of ``RNS.Destination.PROVE_NONE``, ``RNS.Destination.PROVE_ALL`` or ``RNS.Destination.PROVE_APP``. If ``RNS.Destination.PROVE_APP`` is set, the `proof_requested_callback` will be called to determine whether a proof should be sent or not.
"""
2020-08-13 10:15:56 +00:00
if not proof_strategy in Destination.proof_strategies:
raise TypeError("Unsupported proof strategy")
else:
self.proof_strategy = proof_strategy
2016-05-29 20:20:44 +00:00
2020-08-13 10:15:56 +00:00
def receive(self, packet):
plaintext = self.decrypt(packet.data)
if plaintext != None:
if packet.packet_type == RNS.Packet.LINKREQUEST:
2021-05-16 14:37:12 +00:00
self.incoming_link_request(plaintext, packet)
2018-04-16 15:13:39 +00:00
2020-08-13 10:15:56 +00:00
if packet.packet_type == RNS.Packet.DATA:
if self.callbacks.packet != None:
self.callbacks.packet(plaintext, packet)
2018-04-16 15:13:39 +00:00
2021-05-16 14:37:12 +00:00
def incoming_link_request(self, data, packet):
link = RNS.Link.validate_request(self, data, packet)
2020-08-13 10:15:56 +00:00
if link != None:
self.links.append(link)
2016-05-29 20:20:44 +00:00
def create_keys(self):
"""
For a ``RNS.Destination.GROUP`` type destination, creates a new symmetric key.
:raises: ``TypeError`` if called on an incompatible type of destination.
"""
2020-08-13 10:15:56 +00:00
if self.type == Destination.PLAIN:
raise TypeError("A plain destination does not hold any keys")
2016-05-29 20:20:44 +00:00
2020-08-13 10:15:56 +00:00
if self.type == Destination.SINGLE:
raise TypeError("A single destination holds keys through an Identity instance")
2016-05-29 20:20:44 +00:00
2020-08-13 10:15:56 +00:00
if self.type == Destination.GROUP:
self.prv_bytes = Fernet.generate_key()
self.prv = Fernet(self.prv_bytes)
2016-05-29 20:20:44 +00:00
def get_private_key(self):
"""
For a ``RNS.Destination.GROUP`` type destination, returns the symmetric private key.
:raises: ``TypeError`` if called on an incompatible type of destination.
"""
2020-08-13 10:15:56 +00:00
if self.type == Destination.PLAIN:
raise TypeError("A plain destination does not hold any keys")
elif self.type == Destination.SINGLE:
raise TypeError("A single destination holds keys through an Identity instance")
else:
return self.prv_bytes
2016-05-29 20:20:44 +00:00
def load_private_key(self, key):
"""
For a ``RNS.Destination.GROUP`` type destination, loads a symmetric private key.
:param key: A *bytes-like* containing the symmetric key.
:raises: ``TypeError`` if called on an incompatible type of destination.
"""
2020-08-13 10:15:56 +00:00
if self.type == Destination.PLAIN:
raise TypeError("A plain destination does not hold any keys")
2016-05-29 20:20:44 +00:00
2020-08-13 10:15:56 +00:00
if self.type == Destination.SINGLE:
raise TypeError("A single destination holds keys through an Identity instance")
2016-05-29 20:20:44 +00:00
2020-08-13 10:15:56 +00:00
if self.type == Destination.GROUP:
self.prv_bytes = key
self.prv = Fernet(self.prv_bytes)
2016-05-29 20:20:44 +00:00
def load_public_key(self, key):
2020-08-13 10:15:56 +00:00
if self.type != Destination.SINGLE:
raise TypeError("Only the \"single\" destination type can hold a public key")
else:
raise TypeError("A single destination holds keys through an Identity instance")
2016-05-29 20:20:44 +00:00
2020-08-13 10:15:56 +00:00
def encrypt(self, plaintext):
"""
Encrypts information for ``RNS.Destination.SINGLE`` or ``RNS.Destination.GROUP`` type destination.
:param plaintext: A *bytes-like* containing the plaintext to be encrypted.
:raises: ``ValueError`` if destination does not hold a necessary key for encryption.
"""
2020-08-13 10:15:56 +00:00
if self.type == Destination.PLAIN:
return plaintext
2016-05-29 20:20:44 +00:00
2020-08-13 10:15:56 +00:00
if self.type == Destination.SINGLE and self.identity != None:
return self.identity.encrypt(plaintext)
2016-05-29 20:20:44 +00:00
2020-08-13 10:15:56 +00:00
if self.type == Destination.GROUP:
if hasattr(self, "prv") and self.prv != None:
try:
return base64.urlsafe_b64decode(self.prv.encrypt(plaintext))
except Exception as e:
RNS.log("The GROUP destination could not encrypt data", RNS.LOG_ERROR)
RNS.log("The contained exception was: "+str(e), RNS.LOG_ERROR)
else:
raise ValueError("No private key held by GROUP destination. Did you create or load one?")
2016-05-29 20:20:44 +00:00
2020-08-13 10:15:56 +00:00
def decrypt(self, ciphertext):
"""
Decrypts information for ``RNS.Destination.SINGLE`` or ``RNS.Destination.GROUP`` type destination.
:param ciphertext: A *bytes-like* containing the ciphertext to be decrypted.
:raises: ``ValueError`` if destination does not hold a necessary key for decryption.
"""
2020-08-13 10:15:56 +00:00
if self.type == Destination.PLAIN:
return ciphertext
2016-05-29 20:20:44 +00:00
2020-08-13 10:15:56 +00:00
if self.type == Destination.SINGLE and self.identity != None:
return self.identity.decrypt(ciphertext)
2016-05-29 20:20:44 +00:00
2020-08-13 10:15:56 +00:00
if self.type == Destination.GROUP:
if hasattr(self, "prv") and self.prv != None:
try:
return self.prv.decrypt(base64.urlsafe_b64encode(ciphertext))
except Exception as e:
RNS.log("The GROUP destination could not decrypt data", RNS.LOG_ERROR)
RNS.log("The contained exception was: "+str(e), RNS.LOG_ERROR)
else:
raise ValueError("No private key held by GROUP destination. Did you create or load one?")
2016-05-29 20:20:44 +00:00
2020-08-13 10:15:56 +00:00
def sign(self, message):
"""
Signs information for ``RNS.Destination.SINGLE`` type destination.
:param message: A *bytes-like* containing the message to be signed.
:returns: A *bytes-like* containing the message signature, or *None* if the destination could not sign the message.
"""
2020-08-13 10:15:56 +00:00
if self.type == Destination.SINGLE and self.identity != None:
return self.identity.sign(message)
else:
return None
2021-05-15 11:06:50 +00:00
def set_default_app_data(self, app_data=None):
"""
Sets the default app_data for the destination. If set, the default
app_data will be included in every announce sent by the destination,
unless other app_data is specified in the *announce* method.
:param app_data: A *bytes-like* containing the default app_data, or a *callable* returning a *bytes-like* containing the app_data.
"""
2021-05-15 11:06:50 +00:00
self.default_app_data = app_data
def clear_default_app_data(self):
"""
Clears default app_data previously set for the destination.
"""
2021-05-15 11:06:50 +00:00
self.set_default_app_data(app_data=None)
2018-03-16 10:40:37 +00:00
2020-08-13 10:15:56 +00:00
def announce(self, app_data=None, path_response=False):
"""
Creates an announce packet for this destination and broadcasts it on
all interfaces. Application specific data can be added to the announce.
:param app_data: *bytes* containing the app_data.
:param path_response: Internal flag used by :ref:`RNS.Transport<Transport>`. Ignore.
"""
2020-08-13 10:15:56 +00:00
destination_hash = self.hash
2021-05-16 14:15:57 +00:00
random_hash = RNS.Identity.get_random_hash()
2021-05-15 11:06:50 +00:00
if app_data == None and self.default_app_data != None:
if isinstance(self.default_app_data, bytes):
app_data = self.default_app_data
elif callable(self.default_app_data):
returned_app_data = self.default_app_data()
if isinstance(returned_app_data, bytes):
app_data = returned_app_data
2020-08-13 10:15:56 +00:00
2021-05-16 14:15:57 +00:00
signed_data = self.hash+self.identity.get_public_key()+random_hash
2020-08-13 10:15:56 +00:00
if app_data != None:
signed_data += app_data
2018-03-19 17:11:50 +00:00
2020-08-13 10:15:56 +00:00
signature = self.identity.sign(signed_data)
2018-03-19 17:11:50 +00:00
2020-08-13 10:15:56 +00:00
# TODO: Check if this could be optimised by only
# carrying the hash in the destination field, not
# also redundantly inside the signed blob as here
2021-05-16 14:15:57 +00:00
announce_data = self.hash+self.identity.get_public_key()+random_hash+signature
2019-11-09 22:47:42 +00:00
2020-08-13 10:15:56 +00:00
if app_data != None:
announce_data += app_data
2018-03-19 17:11:50 +00:00
2020-08-13 10:15:56 +00:00
if path_response:
announce_context = RNS.Packet.PATH_RESPONSE
else:
announce_context = RNS.Packet.NONE
2020-03-06 13:28:26 +00:00
2020-08-13 10:15:56 +00:00
RNS.Packet(self, announce_data, RNS.Packet.ANNOUNCE, context = announce_context).send()
2018-03-19 17:11:50 +00:00