예제 #1
0
def build_json_message(data,
                       message_id,
                       message_time=None,
                       sender=None,
                       recipient=None,
                       message_type=None,
                       direction=None):
    """
    """
    if not sender:
        sender = my_id.getGlobalID(key_alias='master')
    if not recipient:
        recipient = my_id.getGlobalID(key_alias='master')
    new_json = {
        "payload": {
            "type": message_type or "message",
            "message_id": strng.to_text(message_id),
            "time": message_time or utime.utcnow_to_sec1970(),
            "data": data,
        },
        'sender': {
            'glob_id': sender,
        },
        'recipient': {
            'glob_id': recipient,
        },
        'direction': direction,
    }
    return new_json
예제 #2
0
def get_key_info(key_id, include_private=False, include_signature=False):
    """
    Returns dictionary with full key info or raise an Exception.
    """
    key_id = latest_key_id(strng.to_text(key_id))
    if key_id == 'master' or key_id == my_id.getGlobalID(
            key_alias='master') or key_id == my_id.getGlobalID():
        return make_master_key_info(include_private=include_private)
    key_alias, creator_idurl = split_key_id(key_id)
    if not key_alias or not creator_idurl:
        raise Exception('incorrect key_id format: %s' % key_id)
    if key_id not in known_keys():
        key_id = make_key_id(
            alias=key_alias,
            creator_idurl=creator_idurl,
        )
    if key_id not in known_keys():
        raise Exception('key %s is unknown' % key_id)
    if known_keys()[key_id] is None:
        if not load_key(key_id):
            raise Exception('key load failed: %s' % key_id)
    key_object = known_keys()[key_id]
    key_info = make_key_info(key_object,
                             key_id=key_id,
                             include_private=include_private,
                             include_signature=include_signature)
    return key_info
예제 #3
0
def decrypt(key_id, inp):
    """
    Decrypt ``inp`` string with given private key.

    :param key_id: private key id to be used
    :param inp: input string with encrypted data

    Return decrypted string or raise exception.
    """
    if key_id == 'master':  # master
        if _Debug:
            lg.out(_DebugLevel, 'my_keys.decrypt  payload of %d bytes using my master key' % len(inp))
        return key.DecryptLocalPrivateKey(inp)
    key_id = latest_key_id(key_id)
    if key_id == my_id.getGlobalID(key_alias='master'):  # [email protected]
        if _Debug:
            lg.out(_DebugLevel, 'my_keys.decrypt  payload of %d bytes using my master key' % len(inp))
        return key.DecryptLocalPrivateKey(inp)
    if key_id == my_id.getGlobalID():  # [email protected]
        if _Debug:
            lg.out(_DebugLevel, 'my_keys.decrypt  payload of %d bytes using my master key' % len(inp))
        return key.DecryptLocalPrivateKey(inp)
    if key_id not in known_keys():
        raise Exception('key %s is unknown' % key_id)
    if known_keys()[key_id] is None:
        if not load_key(key_id):
            raise Exception('key load failed: %s' % key_id)
    key_object = known_keys()[key_id]
    if _Debug:
        lg.out(_DebugLevel, 'my_keys.decrypt  payload of %d bytes with key %s' % (len(inp), key_id, ))
    result = key_object.decrypt(inp)
    return result
예제 #4
0
 def doCancelServiceQueue(self, *args, **kwargs):
     """
     Action method.
     """
     service_info = {
         'items': [{
             'scope': 'consumer',
             'action': 'unsubscribe',
             'consumer_id': strng.to_text(my_id.getGlobalID()),
             'queue_id': global_id.MakeGlobalQueueID(
                 queue_alias='supplier-file-modified',
                 owner_id=my_id.getGlobalID(),
                 supplier_id=global_id.MakeGlobalID(idurl=self.supplier_idurl),
             ),
         }, {
             'scope': 'consumer',
             'action': 'remove_callback',
             'consumer_id': strng.to_text(my_id.getGlobalID()),
             'method': strng.to_text(my_id.getLocalID()),
         }, {
             'scope': 'consumer',
             'action': 'stop',
             'consumer_id': strng.to_text(my_id.getGlobalID()),
         }, ],
     }
     p2p_service.SendCancelService(
         remote_idurl=self.supplier_idurl,
         service_name='service_p2p_notifications',
         json_payload=service_info,
         callbacks={
             commands.Ack(): self._supplier_acked,
             commands.Fail(): self._supplier_failed,
         },
     )
예제 #5
0
def build_json_message(data, message_id, message_time=None, sender=None, recipient=None, message_type=None, direction=None, conversation_id=None):
    if not sender:
        sender = my_id.getGlobalID(key_alias='master')
    if not recipient:
        recipient = my_id.getGlobalID(key_alias='master')
    if direction is None:
        if message_type in ['private_message', None, ]:
            direction = 'out' if sender == my_id.getGlobalID(key_alias='master') else 'in'
        else:
            direction = 'in'
    else:
        direction = direction.replace('incoming', 'in').replace('outgoing', 'out')
    new_json = {
        "payload": {
            "msg_type": message_type or "message",
            "message_id": strng.to_text(message_id),
            "time": message_time or utime.utcnow_to_sec1970(),
            "data": data,
        },
        'sender': {
            'glob_id': sender,
        },
        'recipient': {
            'glob_id': recipient,
        },
        'direction': direction,
        'conversation_id': conversation_id,
    }
    return new_json
예제 #6
0
def get_local_key_id(key_id):
    key_id = strng.to_text(key_id)
    if key_id == 'master':
        return 0
    if key_id == my_id.getGlobalID():
        return 0
    if key_id == my_id.getGlobalID(key_alias='master'):
        return 0
    if not is_key_registered(key_id, include_master=False):
        return None
    return key_obj(key_id).local_key_id
예제 #7
0
def is_key_private(key_id, include_master=True):
    if not is_key_registered(key_id):
        return False
    if include_master:
        if key_id == 'master':
            return True
        if key_id == my_id.getGlobalID():
            return True
        if key_id == my_id.getGlobalID(key_alias='master'):
            return True
    return not key_obj(key_id).isPublic()
예제 #8
0
 def doRequestQueueService(self, *args, **kwargs):
     """
     Action method.
     """
     if not self.queue_subscribe:
         reactor.callLater(0, self.automat,
                           'queue-skip')  # @UndefinedVariable
         return
     service_info = {
         'items': [
             {
                 'scope': 'consumer',
                 'action': 'start',
                 'consumer_id': strng.to_text(my_id.getGlobalID()),
             },
             {
                 'scope': 'consumer',
                 'action': 'add_callback',
                 'consumer_id': strng.to_text(my_id.getGlobalID()),
                 'method': strng.to_text(my_id.getLocalID()),
             },
             {
                 'scope':
                 'consumer',
                 'action':
                 'subscribe',
                 'consumer_id':
                 strng.to_text(my_id.getGlobalID()),
                 'queue_id':
                 global_id.MakeGlobalQueueID(
                     queue_alias='supplier-file-modified',
                     owner_id=my_id.getGlobalID(),
                     supplier_id=global_id.MakeGlobalID(
                         idurl=self.supplier_idurl),
                 ),
             },
         ],
     }
     request = p2p_service.SendRequestService(
         remote_idurl=self.supplier_idurl,
         service_name='service_p2p_notifications',
         json_payload=service_info,
         callbacks={
             commands.Ack(): self._supplier_queue_acked,
             commands.Fail(): self._supplier_queue_failed,
         },
     )
     self.request_queue_packet_id = request.PacketID
 def _do_check_sync_keys(self, result):
     from logs import lg
     from interface import api
     from storage import keys_synchronizer
     from userid import global_id
     from userid import my_id
     self.sync_keys_requested = False
     global_keys_folder_path = global_id.MakeGlobalID(
         key_alias='master', customer=my_id.getGlobalID(), path='.keys')
     res = api.file_exists(global_keys_folder_path)
     if res['status'] != 'OK' or not res['result'] or not res['result'].get(
             'exist'):
         res = api.file_create(global_keys_folder_path, as_folder=True)
         if res['status'] != 'OK':
             lg.err(
                 'failed to create ".keys" folder "%s" in the catalog: %r' %
                 (global_keys_folder_path, res))
             result.errback(
                 Exception(
                     'failed to create keys folder "%s" in the catalog: %r'
                     % (global_keys_folder_path, res)))
             return
         lg.info('created new remote folder ".keys" in the catalog: %r' %
                 global_keys_folder_path)
     keys_synchronizer.A('sync', result)
예제 #10
0
파일: signed.py 프로젝트: riyazudheen/devel
 def __init__(self, Command, OwnerID, CreatorID, PacketID, Payload, RemoteID, KeyID=None, Date=None, Signature=None, ):
     """
     Init all fields and sign the packet.
     """
     # Legal Commands are in commands.py
     self.Command = strng.to_text(Command)
     # who owns this data and pays bills - http://cate.com/id1.xml
     self.OwnerID = strng.to_bin(OwnerID)
     # signer - http://cate.com/id1.xml - might be an authorized scrubber
     self.CreatorID = strng.to_bin(CreatorID)
     # string of the above 4 "Number"s with "-" separator to uniquely identify a packet
     # on the local machine.  Can be used for filenames, and to prevent duplicates.
     self.PacketID = strng.to_text(PacketID)
     # create a string to remember current world time
     self.Date = strng.to_text(Date or utime.sec1970_to_datetime_utc().strftime("%Y/%m/%d %I:%M:%S %p"))
     # datetime.datetime.now().strftime("%Y/%m/%d %I:%M:%S %p")
     # main body of binary data
     self.Payload = strng.to_bin(Payload)
     # want full IDURL for other party so troublemaker could not
     # use his packets to mess up other nodes by sending it to them
     self.RemoteID = strng.to_bin(RemoteID)
     # which private key to use to generate signature
     self.KeyID = strng.to_text(KeyID or my_id.getGlobalID(key_alias='master'))
     if Signature:
         self.Signature = Signature
     else:
         # signature on Hash is always by CreatorID
         self.Signature = None
         # must be signed to be valid
         self.Sign()
     # stores list of related objects packet_in() or packet_out()
     self.Packets = []
예제 #11
0
def _download(params):
    # localName = params['name']
    backupID = global_id.CanonicalID(params['backupid'])
    destpath = params['dest_path']
    if bpio.Linux() or bpio.Mac():
        destpath = '/' + destpath.lstrip('/')
    restorePath = bpio.portablePath(destpath)
    # overwrite = params['overwrite']
    customerGlobalID, remotePath, version = packetid.SplitBackupID(backupID)
    pathID = packetid.MakeBackupID(customerGlobalID, remotePath)
    if not customerGlobalID:
        customerGlobalID = my_id.getGlobalID()
    if not packetid.IsCanonicalVersion(version):
        return {'result': {"success": False, "error": "path %s is not valid" % backupID}}
    if not remotePath:
        return {'result': {"success": False, "error": "path %s is not valid" % backupID}}
    if not packetid.Valid(remotePath):
        return {'result': {"success": False, "error": "path %s is not valid" % backupID}}
    if backup_control.IsBackupInProcess(backupID):
        return {'result': {"success": True, "error": None}}
    if backup_control.HasTask(pathID):
        return {'result': {"success": True, "error": None}}
    localPath = backup_fs.ToPath(remotePath)
    if localPath == restorePath:
        restorePath = os.path.dirname(restorePath)

    def _itemRestored(backupID, result):
        customerGlobalID, remotePath, _ = packetid.SplitBackupID(backupID)
        backup_fs.ScanID(remotePath, customer_idurl=global_id.GlobalUserToIDURL(customerGlobalID))
        backup_fs.Calculate()

    restore_monitor.Start(backupID, restorePath, callback=_itemRestored)
    return {'result': {"success": True, "error": None}}
예제 #12
0
def do_restore_key(key_id, is_private, keys_folder=None, wait_result=False):
    """
    Restore given key from my suppliers if I do not have it locally.
    """
    if _Debug:
        lg.out(_DebugLevel, 'key_ring.do_restore_key     key_id=%r    is_private=%r' % (key_id, is_private, ))
    if my_keys.is_key_registered(key_id):
        lg.err('local key already exist: "%s"' % key_id)
        if wait_result:
            return fail(Exception('local key already exist: "%s"' % key_id))
        return False
    if not keys_folder:
        keys_folder = settings.KeyStoreDir()
    if is_private:
        remote_path_for_key = '.keys/%s.private' % key_id
    else:
        remote_path_for_key = '.keys/%s.public' % key_id
    global_key_path = global_id.MakeGlobalID(
        key_alias='master', customer=my_id.getGlobalID(), path=remote_path_for_key)
    ret = api.file_download_start(
        remote_path=global_key_path,
        destination_path=keys_folder,
        wait_result=True,
        open_share=False,
    )
    if not isinstance(ret, Deferred):
        lg.err('failed to download key "%s": %s' % (key_id, ret))
        if wait_result:
            return fail(Exception('failed to download key "%s": %s' % (key_id, ret)))
        return False

    result = Deferred()

    def _on_result(res):
        if not isinstance(res, dict):
            lg.err('failed to download key "%s": %s' % (key_id, res))
            if wait_result:
                result.errback(Exception('failed to download key "%s": %s' % (key_id, res)))
            return None
        if res['status'] != 'OK':
            lg.err('failed to download key "%s": %r' % (key_id, res))
            if wait_result:
                result.errback(Exception('failed to download key "%s": %r' % (key_id, res)))
            return None
        if not my_keys.load_key(key_id, keys_folder):
            lg.err('failed to read key "%s" from local folder "%s"' % (key_id, keys_folder))
            if wait_result:
                result.errback(Exception('failed to read key "%s" from local folder "%s"' % (key_id, keys_folder)))
            return None
        if _Debug:
            lg.out(_DebugLevel, 'key_ring.do_restore_key._on_result key_id=%s  is_private=%r : %r' % (key_id, is_private, res))
        if wait_result:
            result.callback(res)
        return None

    ret.addBoth(_on_result)

    if not wait_result:
        return True
    return result
예제 #13
0
def _delete_version(params):
    lg.out(6, '_delete_version %s' % str(params))
    backupID = params['backupid']
    if not packetid.Valid(backupID):
        return {
            'result': {
                "success": False,
                "error": "backupID %s is not valid" % backupID
            }
        }
    customerGlobalID, remotePath, version = packetid.SplitBackupID(backupID)
    if not customerGlobalID:
        customerGlobalID = my_id.getGlobalID()
    if not backup_fs.ExistsID(
            remotePath,
            iterID=backup_fs.fsID(
                global_id.GlobalUserToIDURL(customerGlobalID))):
        return {
            'result': {
                "success": False,
                "error": "path %s not found" % remotePath
            }
        }
    if version:
        backup_control.DeleteBackup(backupID, saveDB=False, calculate=False)
    backup_fs.Scan()
    backup_fs.Calculate()
    backup_control.Save()
    backup_monitor.A('restart')
    control.request_update([
        ('backupID', backupID),
    ])
    return {'result': {"success": True, "error": None}}
예제 #14
0
 def doCancelService(self, *args, **kwargs):
     """
     Action method.
     """
     service_info = {}
     my_customer_key_id = my_id.getGlobalID(key_alias='customer')
     if my_keys.is_key_registered(my_customer_key_id):
         service_info['customer_public_key'] = my_keys.get_key_info(
             key_id=my_customer_key_id,
             include_private=False,
             include_signature=False,
             generate_signature=False,
         )
     ecc_map = kwargs.get('ecc_map')
     if ecc_map:
         service_info['ecc_map'] = ecc_map
     request = p2p_service.SendCancelService(
         remote_idurl=self.supplier_idurl,
         service_name='service_supplier',
         json_payload=service_info,
         callbacks={
             commands.Ack(): self._supplier_service_acked,
             commands.Fail(): self._supplier_service_failed,
         },
     )
     self.request_packet_id = request.PacketID
예제 #15
0
def is_key_registered(key_id, include_master=True):
    """
    Returns True if this key is known.
    """
    if include_master and (key_id == my_id.getGlobalID(key_alias='master') or key_id == 'master'):
        return True
    return key_id in known_keys()
예제 #16
0
 def doRequestService(self, arg):
     """
     Action method.
     """
     service_info = {
         'needed_bytes': self.needed_bytes,
         'customer_id': global_id.UrlToGlobalID(self.customer_idurl),
     }
     my_customer_key_id = my_id.getGlobalID(key_alias='customer')
     if my_keys.is_key_registered(my_customer_key_id):
         service_info['customer_public_key'] = my_keys.get_key_info(
             key_id=my_customer_key_id,
             include_private=False,
         )
     if self.key_id:
         service_info['key_id'] = self.key_id
     if self.customer_idurl == my_id.getLocalIDURL():
         service_info['ecc_map'] = eccmap.Current().name
     request = p2p_service.SendRequestService(
         remote_idurl=self.supplier_idurl,
         service_name='service_supplier',
         json_payload=service_info,
         callbacks={
             commands.Ack(): self._supplier_acked,
             commands.Fail(): self._supplier_failed,
         },
     )
     self.request_packet_id = request.PacketID
예제 #17
0
파일: my_keys.py 프로젝트: StasEvseev/devel
def get_key_info(key_id, include_private=False):
    """
    Returns dictionary with full key info or raise an Exception.
    """
    key_id = strng.to_text(key_id)
    if key_id == 'master' or key_id == my_id.getGlobalID(key_alias='master'):
        return make_master_key_info(include_private=include_private)
    key_alias, creator_idurl = split_key_id(key_id)
    if not key_alias or not creator_idurl:
        raise Exception('incorrect key_id format')
    key_object = known_keys().get(key_id)
    if not key_object:
        key_id_full = make_key_id(
            alias=key_alias,
            creator_idurl=creator_idurl,
        )
        key_object = known_keys().get(key_id_full)
        if key_object:
            key_id = key_id_full
    if not key_object:
        raise Exception('key not found')
    key_info = make_key_info(
        key_object,
        key_id=key_id,
        include_private=include_private,
    )
    return key_info
예제 #18
0
def MakeBackupID(customer=None,
                 path_id=None,
                 version=None,
                 normalize_key_alias=True,
                 key_alias=None):
    """
    Run:

        MakeBackupID('*****@*****.**', '0/0/1/0', 'F20131120053803PM')

    Will create a string like that:

        "[email protected]:0/0/1/0/F20131120053803PM"
    """
    if normalize_key_alias and not customer:
        from userid import my_id
        customer = my_id.getGlobalID(key_alias=key_alias or 'master')
    if customer:
        if '$' not in customer and normalize_key_alias:
            customer = '{}${}'.format(key_alias or 'master', customer)
        if version:
            return '{}:{}/{}'.format(customer, path_id, version)
        return '{}:{}'.format(customer, path_id)
    if version:
        return '{}/{}'.format(path_id, version)
    return path_id
예제 #19
0
 def _do_retrieve(self, x=None):
     packetID = global_id.MakeGlobalID(
         customer=my_id.getGlobalID(key_alias='master'),
         path=settings.BackupIndexFileName(),
     )
     localID = my_id.getIDURL()
     for supplier_idurl in contactsdb.suppliers():
         if not supplier_idurl:
             continue
         sc = supplier_connector.by_idurl(supplier_idurl)
         if sc is None or sc.state != 'CONNECTED':
             continue
         if online_status.isOffline(supplier_idurl):
             continue
         pkt_out = p2p_service.SendRetreive(ownerID=localID,
                                            creatorID=localID,
                                            packetID=packetID,
                                            remoteID=supplier_idurl,
                                            response_timeout=60 * 2,
                                            callbacks={
                                                commands.Data():
                                                self._on_supplier_response,
                                                commands.Fail():
                                                self._on_supplier_fail,
                                            })
         if pkt_out:
             self.requesting_suppliers.add(supplier_idurl)
             self.requested_suppliers_number += 1
             self.requests_packets_sent.append((packetID, supplier_idurl))
         if _Debug:
             lg.out(
                 _DebugLevel, '    %s sending to %s' %
                 (pkt_out, nameurl.GetName(supplier_idurl)))
예제 #20
0
 def doRequestService(self, *args, **kwargs):
     """
     Action method.
     """
     service_info = {
         'needed_bytes': self.needed_bytes,
         'customer_id': global_id.UrlToGlobalID(self.customer_idurl),
     }
     my_customer_key_id = my_id.getGlobalID(key_alias='customer')
     if my_keys.is_key_registered(my_customer_key_id):
         service_info['customer_public_key'] = my_keys.get_key_info(
             key_id=my_customer_key_id,
             include_private=False,
         )
     if self.key_id:
         service_info['key_id'] = self.key_id
     self._last_known_ecc_map = kwargs.get('ecc_map')
     if self._last_known_ecc_map is not None:
         service_info['ecc_map'] = self._last_known_ecc_map
     self._last_known_family_position = kwargs.get('family_position')
     if self._last_known_family_position is not None:
         service_info['position'] = self._last_known_family_position
     self._last_known_family_snapshot = kwargs.get('family_snapshot')
     if self._last_known_family_snapshot is not None:
         service_info['family_snapshot'] = self._last_known_family_snapshot
     request = p2p_service.SendRequestService(
         remote_idurl=self.supplier_idurl,
         service_name='service_supplier',
         json_payload=service_info,
         callbacks={
             commands.Ack(): self._supplier_acked,
             commands.Fail(): self._supplier_failed,
         },
     )
     self.request_packet_id = request.PacketID
예제 #21
0
파일: signed.py 프로젝트: riyazudheen/devel
 def GenerateSignature(self):
     """
     Call ``crypt.key.Sign`` to generate digital signature.
     """
     _hash_base = self.GenerateHash()
     if not self.KeyID or self.KeyID == my_id.getGlobalID(key_alias='master'):
         return key.Sign(_hash_base)
     return my_keys.sign(self.KeyID, _hash_base)
예제 #22
0
 def doRequestQueueService(self, arg):
     """
     Action method.
     """
     if not self.queue_subscribe:
         self.automat('fail')
         return
     service_info = {
         'items': [
             {
                 'scope': 'consumer',
                 'action': 'start',
                 'consumer_id': my_id.getGlobalID(),
             },
             {
                 'scope': 'consumer',
                 'action': 'add_callback',
                 'consumer_id': my_id.getGlobalID(),
                 'method': my_id.getLocalID(),
             },
             {
                 'scope':
                 'consumer',
                 'action':
                 'subscribe',
                 'consumer_id':
                 my_id.getGlobalID(),
                 'queue_id':
                 global_id.MakeGlobalQueueID(
                     queue_alias='supplier-file-modified',
                     owner_id=my_id.getGlobalID(),
                     supplier_id=global_id.MakeGlobalID(
                         idurl=self.supplier_idurl),
                 ),
             },
         ],
     }
     p2p_service.SendRequestService(
         remote_idurl=self.supplier_idurl,
         service_name='service_p2p_notifications',
         json_payload=service_info,
         callbacks={
             commands.Ack(): self._supplier_acked,
             commands.Fail(): self._supplier_failed,
         },
     )
예제 #23
0
def encrypt(key_id, inp):
    """
    Encrypt ``inp`` string using given private key ID.

    :param key_id: private key id to be used
    :param inp: raw input string to be encrypted

    Return encrypted string.
    """
    if key_id == 'master':  # master
        if _Debug:
            lg.out(
                _DebugLevel,
                'my_keys.encrypt  payload of %d bytes using my master key' %
                len(inp))
        return key.EncryptLocalPublicKey(inp)
    if key_id == my_id.getGlobalID(key_alias='master'):  # [email protected]
        if _Debug:
            lg.out(
                _DebugLevel,
                'my_keys.encrypt  payload of %d bytes using my master key' %
                len(inp))
        return key.EncryptLocalPublicKey(inp)
    if key_id == my_id.getGlobalID():  # [email protected]
        if _Debug:
            lg.out(
                _DebugLevel,
                'my_keys.encrypt  payload of %d bytes using my master key' %
                len(inp))
        return key.EncryptLocalPublicKey(inp)
    key_object = known_keys().get(key_id)
    if not key_object:
        lg.warn('key %s is unknown' % key_id)
        return None
    if _Debug:
        lg.out(
            _DebugLevel, 'my_keys.encrypt  payload of %d bytes with key %s' % (
                len(inp),
                key_id,
            ))
    # There is a bug in rsa.encrypt if there is a leading '\0' in the string.
    # See bug report in http://permalink.gmane.org/gmane.comp.python.cryptography.cvs/217
    # So we add a "1" in front now and in decrypt() we will remove it
    atuple = key_object.keyObject.encrypt('1' + inp, "")
    return atuple[0]
예제 #24
0
def encrypt(key_id, inp):
    """
    Encrypt ``inp`` string using given private key ID.

    :param key_id: private key id to be used
    :param inp: raw binary input string to be encrypted

    Return encrypted string.
    """
    if key_id == 'master':  # master
        if _Debug:
            lg.out(
                _DebugLevel,
                'my_keys.encrypt  payload of %d bytes using my "master" key alias'
                % len(inp))
        return key.EncryptLocalPublicKey(inp)
    if key_id == my_id.getGlobalID():  # [email protected]
        if _Debug:
            lg.out(
                _DebugLevel,
                'my_keys.encrypt  payload of %d bytes using my "master" key, short format'
                % len(inp))
        return key.EncryptLocalPublicKey(inp)
    if key_id == my_id.getGlobalID(key_alias='master'):  # [email protected]
        if _Debug:
            lg.out(
                _DebugLevel,
                'my_keys.encrypt  payload of %d bytes using my "master" key, full format'
                % len(inp))
        return key.EncryptLocalPublicKey(inp)
    key_id = latest_key_id(key_id)
    if not is_key_registered(key_id):
        raise Exception('key %s is not registered' % key_id)
    if known_keys()[key_id] is None:
        if not load_key(key_id):
            raise Exception('key load failed: %s' % key_id)
    key_object = known_keys()[key_id]
    if _Debug:
        lg.out(
            _DebugLevel, 'my_keys.encrypt  payload of %d bytes with key %s' % (
                len(inp),
                key_id,
            ))
    result = key_object.encrypt(inp)
    return result
예제 #25
0
def DeleteFile(request):
    """
    Delete one ore multiple files (that belongs to another user) or folders on my machine.
    """
    if _Debug:
        lg.out(
            _DebugLevel, 'p2p_service.DeleteFile [%s] by %s | %s' %
            (request.PacketID, request.OwnerID, request.CreatorID))
    if not driver.is_on('service_supplier'):
        return SendFail(request, 'supplier service is off')
    if request.Payload == '':
        ids = [request.PacketID]
    else:
        ids = request.Payload.split('\n')
    filescount = 0
    dirscount = 0
    for pcktID in ids:
        glob_path = global_id.ParseGlobalID(pcktID)
        if not glob_path['path']:
            # backward compatible check
            glob_path = global_id.ParseGlobalID(my_id.getGlobalID() + ':' +
                                                request.PacketID)
        if not glob_path['path']:
            lg.warn("got incorrect PacketID")
            SendFail(request, 'incorrect PacketID')
            return
        # TODO: add validation of customerGlobID
        # TODO: process requests from another customer
        filename = makeFilename(request.OwnerID, glob_path['path'])
        if filename == "":
            filename = constructFilename(request.OwnerID, glob_path['path'])
            if not os.path.exists(filename):
                lg.warn(
                    "had unknown customer: %s or pathID is not correct or not exist: %s"
                    % (nameurl.GetName(request.OwnerID), glob_path['path']))
                return SendFail(request, 'not a customer, or file not found')
        if os.path.isfile(filename):
            try:
                os.remove(filename)
                filescount += 1
            except:
                lg.exc()
        elif os.path.isdir(filename):
            try:
                bpio._dir_remove(filename)
                dirscount += 1
            except:
                lg.exc()
        else:
            lg.warn("path not found %s" % filename)
    if _Debug:
        lg.out(
            _DebugLevel,
            "p2p_service.DeleteFile from [%s] with %d IDs, %d files and %d folders were removed"
            % (nameurl.GetName(
                request.OwnerID), len(ids), filescount, dirscount))
    SendAck(request)
예제 #26
0
 def __init__(self,
              recipient_global_id,
              sender=None,
              encrypted_session=None,
              encrypted_body=None):
     self.sender = sender or my_id.getGlobalID(key_alias='master')
     self.recipient = recipient_global_id
     self.encrypted_session = encrypted_session
     self.encrypted_body = encrypted_body
예제 #27
0
def decrypt(key_id, inp):
    """
    Decrypt ``inp`` string with given private key.

    :param key_id: private key id to be used
    :param inp: input string with encrypted data

    Return decrypted string or raise exception.
    """
    if key_id == 'master':  # master
        if _Debug:
            lg.out(
                _DebugLevel,
                'my_keys.decrypt  payload of %d bytes using my master key' %
                len(inp))
        return key.DecryptLocalPrivateKey(inp)
    if key_id == 'master$%s' % my_id.getGlobalID():  # [email protected]
        if _Debug:
            lg.out(
                _DebugLevel,
                'my_keys.decrypt  payload of %d bytes using my master key' %
                len(inp))
        return key.DecryptLocalPrivateKey(inp)
    if key_id == my_id.getGlobalID():  # [email protected]
        if _Debug:
            lg.out(
                _DebugLevel,
                'my_keys.decrypt  payload of %d bytes using my master key' %
                len(inp))
        return key.DecryptLocalPrivateKey(inp)
    key_object = known_keys().get(key_id)
    if not key_object:
        lg.warn('key %s is unknown' % key_id)
        return None
    if _Debug:
        lg.out(
            _DebugLevel, 'my_keys.decrypt  payload of %d bytes with key %s' % (
                len(inp),
                key_id,
            ))
    atuple = (inp, )
    padresult = key_object.keyObject.decrypt(atuple)
    # remove the "1" added in encrypt() method
    return padresult[1:]
예제 #28
0
def is_key_registered(key_id, include_master=True):
    """
    Returns True if this key is known.
    """
    if include_master:
        if key_id == 'master':
            return True
        if key_id == my_id.getGlobalID():
            return True
        if key_id == my_id.getGlobalID(key_alias='master'):
            return True
    if key_id in known_keys():
        return True
    new_key_id = latest_key_id(key_id)
    if new_key_id in known_keys():
        rename_key(key_id, new_key_id)
        return True
    check_rename_my_keys(prefix=new_key_id.split('@')[0])
    return key_id in known_keys()
예제 #29
0
def SendListFiles(target_supplier, customer_idurl=None, key_id=None, query_items=[], wide=False, callbacks={}, timeout=None):
    """
    This is used as a request method from your supplier : if you send him a ListFiles() packet
    he will reply you with a list of stored files in a Files() packet.
    """
    MyID = my_id.getLocalID()
    if not customer_idurl:
        customer_idurl = MyID
    if not str(target_supplier).isdigit():
        RemoteID = target_supplier
    else:
        RemoteID = contactsdb.supplier(target_supplier, customer_idurl=customer_idurl)
    if not RemoteID:
        lg.warn("RemoteID is empty target_supplier=%s" % str(target_supplier))
        return None
    if not key_id:
        # key_id = global_id.MakeGlobalID(idurl=customer_idurl, key_alias='customer')
        # TODO: due to issue with "customer" key backup/restore decided to always use my "master" key
        # to retrieve my list files info from supplier
        # expect remote user always poses my master public key from my identity.
        # probably require more work to build more reliable solution without using my master key at all
        # when my identity rotated supplier first needs to receive my new identity and then sending ListFiles()
        key_id = my_id.getGlobalID(key_alias='master')
    if not my_keys.is_key_registered(key_id) or not my_keys.is_key_private(key_id):
        lg.warn('key %r not exist or public, my "master" key to be used with ListFiles() packet' % key_id)
        key_id = my_id.getGlobalID(key_alias='master')
    PacketID = "%s:%s" % (key_id, packetid.UniqueID(), )
    if not query_items:
        query_items = ['*', ]
    Payload = serialization.DictToBytes({'items': query_items, })
    if _Debug:
        lg.out(_DebugLevel, "p2p_service.SendListFiles %r to %s with query : %r" % (
            PacketID, nameurl.GetName(RemoteID), query_items, ))
    result = signed.Packet(
        Command=commands.ListFiles(),
        OwnerID=MyID,
        CreatorID=MyID,
        PacketID=PacketID,
        Payload=Payload,
        RemoteID=RemoteID,
    )
    gateway.outbox(result, wide=wide, callbacks=callbacks, response_timeout=timeout)
    return result
예제 #30
0
 def __init__(self,
              recipient,
              sender=None,
              encrypted_session=None,
              encrypted_body=None):
     self.sender = strng.to_text(sender
                                 or my_id.getGlobalID(key_alias='master'))
     self.recipient = strng.to_text(recipient)
     self.encrypted_session = encrypted_session
     self.encrypted_body = encrypted_body