Reticulum/RNS/Destination.py

357 lines
14 KiB
Python
Raw Normal View History

2016-05-29 22:20:44 +02:00
import base64
2018-03-16 10:50:37 +01:00
import math
import RNS
2018-03-19 16:39:08 +01:00
2016-05-29 22:20:44 +02:00
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.backends import default_backend
2018-04-16 17:13:39 +02:00
class Callbacks:
2020-08-13 12:15:56 +02:00
def __init__(self):
self.link_established = None
self.packet = None
self.proof_requested = None
2018-03-19 16:39:08 +01:00
2016-05-29 22:20:44 +02: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.
2021-05-16 21:57:49 +02:00
:param identity: An instance of :ref:`RNS.Identity<api-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 12:15:56 +02:00
# Constants
SINGLE = 0x00
GROUP = 0x01
PLAIN = 0x02
LINK = 0x03
types = [SINGLE, GROUP, PLAIN, LINK]
2016-05-29 22:20:44 +02:00
2020-08-13 12:15:56 +02:00
PROVE_NONE = 0x21
PROVE_APP = 0x22
PROVE_ALL = 0x23
proof_strategies = [PROVE_NONE, PROVE_APP, PROVE_ALL]
2018-03-20 12:32:41 +01:00
2020-08-13 12:15:56 +02:00
IN = 0x11;
OUT = 0x12;
directions = [IN, OUT]
2016-05-29 22:20:44 +02:00
2020-08-13 12:15:56 +02:00
@staticmethod
2021-05-15 10:57:54 +02: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 12:15:56 +02: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 22:20:44 +02:00
2020-08-13 12:15:56 +02: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 22:20:44 +02:00
2020-08-13 12:15:56 +02:00
return name
2016-05-29 22:20:44 +02:00
2020-08-13 12:15:56 +02:00
@staticmethod
2021-05-15 10:57:54 +02: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 10:57:54 +02:00
name = Destination.full_name(app_name, *aspects)
2016-05-29 22:20:44 +02:00
2020-08-13 12:15:56 +02:00
# Create a digest for the destination
digest = hashes.Hash(hashes.SHA256(), backend=default_backend())
digest.update(name.encode("UTF-8"))
2016-05-29 22:20:44 +02:00
2020-08-13 12:15:56 +02:00
return digest.finalize()[:10]
2016-05-29 22:20:44 +02:00
2021-05-15 10:57:54 +02: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 10:57:54 +02: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 10:57:54 +02: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 22:20:44 +02:00
2020-08-13 12:15:56 +02: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 22:20:44 +02:00
2020-08-13 12:15:56 +02:00
self.links = []
2018-04-16 17:13:39 +02:00
2020-08-13 12:15:56 +02:00
if identity != None and type == Destination.SINGLE:
aspects = aspects+(identity.hexhash,)
2018-03-20 12:32:41 +01:00
2020-08-13 12:15:56 +02:00
if identity == None and direction == Destination.IN and self.type != Destination.PLAIN:
identity = RNS.Identity()
aspects = aspects+(identity.hexhash,)
2018-03-16 11:40:37 +01:00
2020-08-13 12:15:56 +02:00
self.identity = identity
2018-03-16 11:40:37 +01:00
2021-05-15 10:57:54 +02:00
self.name = Destination.full_name(app_name, *aspects)
self.hash = Destination.hash(app_name, *aspects)
2020-08-13 12:15:56 +02:00
self.hexhash = self.hash.hex()
2021-05-15 13:06:50 +02:00
self.default_app_data = None
2016-05-29 22:20:44 +02:00
2020-08-13 12:15:56 +02:00
self.callback = None
self.proofcallback = None
2016-05-29 22:20:44 +02:00
2021-05-16 16:48:54 +02:00
RNS.Transport.register_destination(self)
2016-06-03 19:02:02 +02:00
2016-05-29 22:20:44 +02:00
2020-08-13 12:15:56 +02:00
def __str__(self):
"""
:returns: A human-readable representation of the destination including addressable hash and full name.
"""
2020-08-13 12:15:56 +02:00
return "<"+self.name+"/"+self.hexhash+">"
2016-05-29 22:20:44 +02:00
2021-05-16 23:14:19 +02:00
def announce(self, app_data=None, path_response=False):
"""
Creates an announce packet for this destination and broadcasts it on all
relevant interfaces. Application specific data can be added to the announce.
2021-05-16 23:14:19 +02:00
:param app_data: *bytes* containing the app_data.
:param path_response: Internal flag used by :ref:`RNS.Transport<api-transport>`. Ignore.
"""
destination_hash = self.hash
random_hash = RNS.Identity.get_random_hash()
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
signed_data = self.hash+self.identity.get_public_key()+random_hash
if app_data != None:
signed_data += app_data
signature = self.identity.sign(signed_data)
2021-05-20 16:56:08 +02:00
announce_data = self.identity.get_public_key()+random_hash+signature
2021-05-16 23:14:19 +02:00
if app_data != None:
announce_data += app_data
if path_response:
announce_context = RNS.Packet.PATH_RESPONSE
else:
announce_context = RNS.Packet.NONE
RNS.Packet(self, announce_data, RNS.Packet.ANNOUNCE, context = announce_context).send()
def set_link_established_callback(self, callback):
"""
Registers a function to be called when a link has been established to
this destination.
2021-05-16 23:14:19 +02:00
:param callback: A function or method to be called.
"""
2020-08-13 12:15:56 +02:00
self.callbacks.link_established = callback
2018-04-16 17:13:39 +02:00
def set_packet_callback(self, callback):
"""
Registers a function to be called when a packet has been received by
this destination.
2021-05-16 23:14:19 +02:00
:param callback: A function or method to be called.
"""
2020-08-13 12:15:56 +02:00
self.callbacks.packet = callback
2016-05-29 22:20:44 +02:00
def set_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 12:15:56 +02:00
self.callbacks.proof_requested = callback
2018-03-20 12:32:41 +01:00
2020-08-13 12:15:56 +02: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 12:15:56 +02:00
if not proof_strategy in Destination.proof_strategies:
raise TypeError("Unsupported proof strategy")
else:
self.proof_strategy = proof_strategy
2016-05-29 22:20:44 +02:00
2020-08-13 12:15:56 +02:00
def receive(self, packet):
2021-05-20 20:32:08 +02:00
if packet.packet_type == RNS.Packet.LINKREQUEST:
plaintext = packet.data
self.incoming_link_request(plaintext, packet)
else:
plaintext = self.decrypt(packet.data)
if plaintext != None:
if packet.packet_type == RNS.Packet.DATA:
if self.callbacks.packet != None:
self.callbacks.packet(plaintext, packet)
2018-04-16 17:13:39 +02:00
2021-05-16 16:37:12 +02:00
def incoming_link_request(self, data, packet):
link = RNS.Link.validate_request(self, data, packet)
2020-08-13 12:15:56 +02:00
if link != None:
self.links.append(link)
2016-05-29 22:20:44 +02: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 12:15:56 +02:00
if self.type == Destination.PLAIN:
raise TypeError("A plain destination does not hold any keys")
2016-05-29 22:20:44 +02:00
2020-08-13 12:15:56 +02:00
if self.type == Destination.SINGLE:
raise TypeError("A single destination holds keys through an Identity instance")
2016-05-29 22:20:44 +02:00
2020-08-13 12:15:56 +02:00
if self.type == Destination.GROUP:
self.prv_bytes = base64.urlsafe_b64decode(Fernet.generate_key())
self.prv = Fernet(base64.urlsafe_b64encode(self.prv_bytes))
2016-05-29 22:20:44 +02: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 12:15:56 +02: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 22:20:44 +02: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 12:15:56 +02:00
if self.type == Destination.PLAIN:
raise TypeError("A plain destination does not hold any keys")
2016-05-29 22:20:44 +02:00
2020-08-13 12:15:56 +02:00
if self.type == Destination.SINGLE:
raise TypeError("A single destination holds keys through an Identity instance")
2016-05-29 22:20:44 +02:00
2020-08-13 12:15:56 +02:00
if self.type == Destination.GROUP:
self.prv_bytes = key
self.prv = Fernet(base64.urlsafe_b64encode(self.prv_bytes))
2016-05-29 22:20:44 +02:00
def load_public_key(self, key):
2020-08-13 12:15:56 +02: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 22:20:44 +02:00
2020-08-13 12:15:56 +02: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 12:15:56 +02:00
if self.type == Destination.PLAIN:
return plaintext
2016-05-29 22:20:44 +02:00
2020-08-13 12:15:56 +02:00
if self.type == Destination.SINGLE and self.identity != None:
return self.identity.encrypt(plaintext)
2016-05-29 22:20:44 +02:00
2020-08-13 12:15:56 +02: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 22:20:44 +02:00
2020-08-13 12:15:56 +02:00
def decrypt(self, ciphertext):
"""
Decrypts information for ``RNS.Destination.SINGLE`` or ``RNS.Destination.GROUP`` type destination.
2021-05-16 21:57:49 +02:00
:param ciphertext: *Bytes* containing the ciphertext to be decrypted.
:raises: ``ValueError`` if destination does not hold a necessary key for decryption.
"""
2020-08-13 12:15:56 +02:00
if self.type == Destination.PLAIN:
return ciphertext
2016-05-29 22:20:44 +02:00
2020-08-13 12:15:56 +02:00
if self.type == Destination.SINGLE and self.identity != None:
return self.identity.decrypt(ciphertext)
2016-05-29 22:20:44 +02:00
2020-08-13 12:15:56 +02: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 22:20:44 +02:00
2020-08-13 12:15:56 +02:00
def sign(self, message):
"""
Signs information for ``RNS.Destination.SINGLE`` type destination.
2021-05-16 21:57:49 +02:00
:param message: *Bytes* 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 12:15:56 +02:00
if self.type == Destination.SINGLE and self.identity != None:
return self.identity.sign(message)
else:
return None
2021-05-15 13:06:50 +02: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 13:06:50 +02:00
self.default_app_data = app_data
def clear_default_app_data(self):
"""
Clears default app_data previously set for the destination.
"""
2021-05-16 23:14:19 +02:00
self.set_default_app_data(app_data=None)