Exemplo n.º 1
0
 def encrypt(self, message_body, encrypt_session_func=None):
     if _Debug:
         lg.args(_DebugLevel, encrypt_session_func=encrypt_session_func, recipient=self.recipient)
     new_sessionkey = key.NewSessionKey(session_key_type=key.SessionKeyType())
     if not encrypt_session_func:
         if my_keys.is_key_registered(self.recipient):
             if _Debug:
                 lg.dbg(_DebugLevel, 'with registered key %r' % self.recipient)
             encrypt_session_func = lambda inp: my_keys.encrypt(self.recipient, inp)
     if not encrypt_session_func:
         glob_id = global_id.NormalizeGlobalID(self.recipient)
         if glob_id['key_alias'] == 'master':
             if glob_id['idurl'] == my_id.getIDURL():
                 lg.warn('making encrypted message addressed to me ?')
                 encrypt_session_func = lambda inp: my_keys.encrypt('master', inp)
             else:
                 remote_identity = identitycache.FromCache(glob_id['idurl'])
                 if not remote_identity:
                     raise Exception('remote identity is not cached yet, not able to encrypt the message')
                 if _Debug:
                     lg.dbg(_DebugLevel, 'with remote identity public key %r' % glob_id['idurl'])
                 encrypt_session_func = remote_identity.encrypt
         else:
             own_key = global_id.MakeGlobalID(idurl=my_id.getIDURL(), key_alias=glob_id['key_alias'])
             if my_keys.is_key_registered(own_key):
                 if _Debug:
                     lg.dbg(_DebugLevel, 'with registered key (found by alias) %r' % own_key)
                 encrypt_session_func = lambda inp: my_keys.encrypt(own_key, inp)
     if not encrypt_session_func:
         raise Exception('can not find key for given recipient')
     self.encrypted_session = encrypt_session_func(new_sessionkey)
     self.encrypted_body = key.EncryptWithSessionKey(new_sessionkey, message_body, session_key_type=key.SessionKeyType())
     return self.encrypted_session, self.encrypted_body
Exemplo n.º 2
0
 def encrypt(self, message_body, encrypt_session_func=None):
     new_sessionkey = key.NewSessionKey()
     if not encrypt_session_func:
         if my_keys.is_key_registered(self.recipient):
             if _Debug:
                 lg.out(_DebugLevel, 'message.PrivateMessage.encrypt with "%s" key' % self.recipient)
             encrypt_session_func = lambda inp: my_keys.encrypt(self.recipient, inp)
     if not encrypt_session_func:
         glob_id = global_id.ParseGlobalID(self.recipient)
         if glob_id['key_alias'] == 'master':
             if glob_id['idurl'] == my_id.getLocalID():
                 lg.warn('making private message addressed to me ???')
                 if _Debug:
                     lg.out(_DebugLevel, 'message.PrivateMessage.encrypt with "master" key')
                 encrypt_session_func = lambda inp: my_keys.encrypt('master', inp)
             else:
                 remote_identity = identitycache.FromCache(glob_id['idurl'])
                 if not remote_identity:
                     raise Exception('remote identity is not cached yet, not able to encrypt the message')
                 if _Debug:
                     lg.out(_DebugLevel, 'message.PrivateMessage.encrypt with remote identity public key')
                 encrypt_session_func = remote_identity.encrypt
         else:
             own_key = global_id.MakeGlobalID(idurl=my_id.getLocalID(), key_alias=glob_id['key_alias'])
             if my_keys.is_key_registered(own_key):
                 if _Debug:
                     lg.out(_DebugLevel, 'message.PrivateMessage.encrypt with "%s" key' % own_key)
                 encrypt_session_func = lambda inp: my_keys.encrypt(own_key, inp)
     if not encrypt_session_func:
         raise Exception('can not find key for given recipient')
     self.encrypted_session = encrypt_session_func(new_sessionkey)
     self.encrypted_body = key.EncryptWithSessionKey(new_sessionkey, message_body)
     return self.encrypted_session, self.encrypted_body
Exemplo n.º 3
0
 def __init__(
     self,
     CreatorID=None,
     BackupID='',
     BlockNumber=0,
     SessionKey='',
     SessionKeyType=None,
     LastBlock=True,
     Data=b'',
     EncryptKey=None,
     DecryptKey=None,
     EncryptedSessionKey=None,
     EncryptedData=None,
     Length=None,
     Signature=None,
 ):
     self.CreatorID = CreatorID
     if not self.CreatorID:
         self.CreatorID = my_id.getLocalID()
     if not isinstance(self.CreatorID, id_url.ID_URL_FIELD):
         self.CreatorID = id_url.field(self.CreatorID)
     self.BackupID = strng.to_text(BackupID)
     self.BlockNumber = BlockNumber
     self.LastBlock = bool(LastBlock)
     self.SessionKeyType = SessionKeyType or key.SessionKeyType()
     if EncryptedSessionKey:
         # this block to be decrypted after receiving
         self.EncryptedSessionKey = EncryptedSessionKey
     else:
         # this block to be encrypted before sending
         if callable(EncryptKey):
             self.EncryptedSessionKey = EncryptKey(SessionKey)
         elif strng.is_text(EncryptKey):
             self.EncryptedSessionKey = my_keys.encrypt(
                 EncryptKey, SessionKey)
         elif strng.is_bin(EncryptKey):
             self.EncryptedSessionKey = my_keys.encrypt(
                 strng.to_text(EncryptKey), SessionKey)
         else:
             self.EncryptedSessionKey = key.EncryptLocalPublicKey(
                 SessionKey)
     if EncryptedData and Length is not None:
         self.Length = Length
         self.EncryptedData = EncryptedData
     else:
         self.Length = len(Data)
         self.EncryptedData = key.EncryptWithSessionKey(
             SessionKey, Data, session_key_type=self.SessionKeyType)
     if Signature:
         self.Signature = Signature
     else:
         self.Signature = None
         self.Sign(signing_key=EncryptKey)
     self.DecryptKey = DecryptKey
     if _Debug:
         lg.out(_DebugLevel, 'new data in %s' % self)
Exemplo n.º 4
0
 def __init__(
     self,
     CreatorID=None,
     BackupID='',
     BlockNumber=0,
     SessionKey='',
     SessionKeyType=None,
     LastBlock=True,
     Data='',
     EncryptKey=None,
     DecryptKey=None,
 ):
     self.CreatorID = CreatorID
     if not self.CreatorID:
         self.CreatorID = my_id.getLocalID()
     self.BackupID = str(BackupID)
     self.BlockNumber = BlockNumber
     if callable(EncryptKey):
         self.EncryptedSessionKey = EncryptKey(SessionKey)
     elif isinstance(EncryptKey, basestring):
         self.EncryptedSessionKey = my_keys.encrypt(EncryptKey, SessionKey)
     else:
         self.EncryptedSessionKey = key.EncryptLocalPublicKey(SessionKey)
     self.SessionKeyType = SessionKeyType
     if not self.SessionKeyType:
         self.SessionKeyType = key.SessionKeyType()
     self.Length = len(Data)
     self.LastBlock = bool(LastBlock)
     self.EncryptedData = key.EncryptWithSessionKey(SessionKey,
                                                    Data)  # DataLonger
     self.Signature = None
     self.Sign()
     self.DecryptKey = DecryptKey
     if _Debug:
         lg.out(_DebugLevel, 'new data in %s' % self)
Exemplo n.º 5
0
def audit_private_key(key_id, untrusted_idurl, timeout=10):
    """
    Be sure remote user posses given private key.
    I need to posses the public key to be able to audit.
    I will generate a random string, encrypt it with given key public key and send encrypted string to him.
    He will decrypt and send me back original string.
    Returns Deferred object.
    """
    if _Debug:
        lg.out(_DebugLevel, 'key_ring.audit_private_key   testing %s from %s' % (key_id, untrusted_idurl))
    result = Deferred()
    recipient_id_obj = identitycache.FromCache(untrusted_idurl)
    if not recipient_id_obj:
        lg.warn('not found "%s" in identity cache' % untrusted_idurl)
        result.errback(Exception('not found "%s" in identity cache' % untrusted_idurl))
        return result
    key_alias, creator_idurl = my_keys.split_key_id(key_id)
    if not key_alias or not creator_idurl:
        lg.warn('wrong key_id')
        result.errback(Exception('wrong key_id'))
        return result
    private_test_sample = key.NewSessionKey()
    if untrusted_idurl == creator_idurl and key_alias == 'master':
        lg.warn('doing audit of master key (private part) of remote user')
        private_test_encrypted_sample = recipient_id_obj.encrypt(private_test_sample)
    else:
        if not my_keys.is_key_registered(key_id):
            lg.warn('unknown key: "%s"' % key_id)
            result.errback(Exception('unknown key: "%s"' % key_id))
            return result
        private_test_encrypted_sample = my_keys.encrypt(key_id, private_test_sample)
    json_payload = {
        'key_id': key_id,
        'audit': {
            'public_sample': '',
            'private_sample': base64.b64encode(private_test_encrypted_sample),
        }
    }
    raw_payload = serialization.DictToBytes(json_payload, values_to_text=True)
    block = encrypted.Block(
        BackupID=key_id,
        Data=raw_payload,
        SessionKey=key.NewSessionKey(),
        # encrypt data using public key of recipient
        EncryptKey=lambda inp: recipient_id_obj.encrypt(inp),
    )
    encrypted_payload = block.Serialize()
    p2p_service.SendAuditKey(
        remote_idurl=recipient_id_obj.getIDURL(),
        encrypted_payload=encrypted_payload,
        packet_id=key_id,
        timeout=timeout,
        callbacks={
            commands.Ack(): lambda response, info:
                _on_audit_private_key_response(response, info, key_id, untrusted_idurl, private_test_sample, result),
            commands.Fail(): lambda response, info: result.errback(Exception(response)),
            None: lambda pkt_out: result.errback(Exception('timeout')),  # timeout
        },
    )
    return result
Exemplo n.º 6
0
def _on_audit_public_key_response(response, info, key_id, untrusted_idurl, test_sample, result):
    try:
        response_sample = base64.b64decode(response.Payload)
    except:
        lg.exc()
        result.callback(False)
        return False
    key_alias, creator_idurl = my_keys.split_key_id(key_id)
    if creator_idurl == untrusted_idurl and key_alias == 'master':
        recipient_id_obj = identitycache.FromCache(creator_idurl)
        if not recipient_id_obj:
            lg.warn('not found "%s" in identity cache' % creator_idurl)
            result.errback(Exception('not found "%s" in identity cache' % creator_idurl))
            return result
        orig_sample = recipient_id_obj.encrypt(test_sample)
    else:
        orig_sample = my_keys.encrypt(key_id, test_sample)
    if response_sample == orig_sample:
        if _Debug:
            lg.out(_DebugLevel, 'key_ring._on_audit_public_key_response : %s on %s' % (key_id, untrusted_idurl, ))
            lg.out(_DebugLevel, '         is OK !!!!!!!!!!!!!!!!!!!!!!!!!')
        result.callback(True)
        return True
    lg.warn('key %s on %s is not OK' % (key_id, untrusted_idurl, ))
    result.callback(False)
    return False
Exemplo n.º 7
0
def on_audit_key_received(newpacket, info, status, error_message):
    """
    Callback will be executed when remote user would like to check if I poses given key locally.
    """
    block = encrypted.Unserialize(newpacket.Payload)
    if block is None:
        lg.out(
            2, 'key_ring.on_audit_key_received ERROR reading data from %s' %
            newpacket.RemoteID)
        return False
    try:
        raw_payload = block.Data()
        json_payload = serialization.BytesToDict(raw_payload,
                                                 keys_to_text=True,
                                                 values_to_text=True)
        key_id = json_payload['key_id']
        json_payload['audit']
        public_sample = base64.b64decode(
            json_payload['audit']['public_sample'])
        private_sample = base64.b64decode(
            json_payload['audit']['private_sample'])
    except Exception as exc:
        lg.exc()
        p2p_service.SendFail(newpacket, str(exc))
        return False
    if not my_keys.is_valid_key_id(key_id):
        p2p_service.SendFail(newpacket, 'invalid key id')
        return False
    if not my_keys.is_key_registered(key_id, include_master=True):
        p2p_service.SendFail(newpacket, 'key not registered')
        return False
    if public_sample:
        response_payload = base64.b64encode(
            my_keys.encrypt(key_id, public_sample))
        p2p_service.SendAck(newpacket, response_payload)
        if _Debug:
            lg.info('remote user %s requested audit of public key %s' %
                    (newpacket.OwnerID, key_id))
        return True
    if private_sample:
        if not my_keys.is_key_private(key_id):
            p2p_service.SendFail(newpacket, 'private key not registered')
            return False
        response_payload = base64.b64encode(
            my_keys.decrypt(key_id, private_sample))
        p2p_service.SendAck(newpacket, response_payload)
        if _Debug:
            lg.info('remote user %s requested audit of private key %s' %
                    (newpacket.OwnerID, key_id))
        return True
    p2p_service.SendFail(newpacket, 'wrong audit request')
    return False
Exemplo n.º 8
0
 def __init__(
     self,
     CreatorID=None,
     BackupID='',
     BlockNumber=0,
     SessionKey='',
     SessionKeyType=None,
     LastBlock=True,
     Data='',
     EncryptKey=None,
     DecryptKey=None,
     EncryptedSessionKey=None,
     EncryptedData=None,
     Length=None,
     Signature=None,
 ):
     self.CreatorID = CreatorID
     if not self.CreatorID:
         self.CreatorID = my_id.getLocalID()
     self.CreatorID = strng.to_bin(self.CreatorID)
     self.BackupID = strng.to_text(BackupID)
     self.BlockNumber = BlockNumber
     self.LastBlock = bool(LastBlock)
     self.SessionKeyType = SessionKeyType or key.SessionKeyType()
     if EncryptedSessionKey:
         self.EncryptedSessionKey = EncryptedSessionKey
     else:
         if callable(EncryptKey):
             self.EncryptedSessionKey = EncryptKey(SessionKey)
         elif isinstance(EncryptKey, six.string_types):
             self.EncryptedSessionKey = my_keys.encrypt(
                 EncryptKey, SessionKey)
         else:
             self.EncryptedSessionKey = key.EncryptLocalPublicKey(
                 SessionKey)
     if EncryptedData and Length:
         self.Length = Length
         self.EncryptedData = EncryptedData
     else:
         self.Length = len(Data)
         self.EncryptedData = key.EncryptWithSessionKey(SessionKey, Data)
     if Signature:
         self.Signature = Signature
     else:
         self.Signature = None
         self.Sign()
     self.DecryptKey = DecryptKey
     if _Debug:
         lg.out(_DebugLevel, 'new data in %s' % self)