示例#1
0
    def extract(self):
        try:
            if 'Encoding' not in self._header:
                if isinstance(self._body, basestring):
                    return(json.loads(
                        self._re_json_cruft.sub(r'\g<1>', self._body)))
                elif isinstance(self._body, dict):
                    return self._body
                else:
                    raise EventException('No body encoding')

            t = self._header['Encoding']
            if str(t).lower() != 'base64':
                raise EventException('Unkown encoding: ' + t)

            t = self._header.get('Algorithm', 'aes128cbc')
            if str(t).lower() != 'aes128cbc':
                raise EventException('Unsupported algorithm: ' + t)

            key = None
            if 'KeyURL' in self._header:
                key = self._kws._key_from_json(
                    self._kws._get_resource(self._header['KeyURL']))
            elif 'KeyId' in self._header:
                key = self._kws.get_key(self._header['KeyId'])
            else:
                try:
                    key = self._kws.get_current_key(
                        self._header['MessageType'])
                    if not re.match(r'^\s*{.+}\s*$', self._body):
                        raise CryptoException()
                except (ValueError, CryptoException) as err:
                    RestClientsCache().delete_cached_kws_current_key(
                        self._header['MessageType'])
                    key = self._kws.get_current_key(
                        self._header['MessageType'])

            cipher = aes128cbc(b64decode(key.key),
                               b64decode(self._header['IV']))
            body = cipher.decrypt(b64decode(self._body))
            return(json.loads(self._re_json_cruft.sub(r'\g<1>', body)))
        except KeyError as err:
            self._log.error(
                "Key Error: %s\nHEADER: %s" % (err, self._header))
            raise
        except (ValueError, CryptoException) as err:
            raise EventException('Cannot decrypt: %s' % (err))
        except DataFailureException as err:
            msg = "Request failure for %s: %s (%s)" % (
                err.url, err.msg, err.status)
            self._log.error(msg)
            raise EventException(msg)
        except Exception as err:
            raise EventException('Cannot read: %s' % (err))
    def decrypt_message_body(self, message):
        header = message['header']
        body = message['body']
        try:
            if set(['keyId', 'iv']).issubset(header):
                key = header['keyId']
                keys = self.settings.get('BODY_DECRYPT_KEYS', {})

                cipher = aes128cbc(b64decode(keys[key]),
                                   b64decode(header['iv']))
                body = cipher.decrypt(b64decode(body))
                return body

        except KeyError as ex:
            raise ProcessorException('Invalid keyId: {}'.format(key))
        except CryptoException as ex:
            raise ProcessorException('Cannot decrypt: {}'.format(ex))
        except Exception as ex:
            raise ProcessorException('Cannot read: {}'.format(ex))
示例#3
0
    def _raw_message(self):
        if self._settings.get('VALIDATE_MSG_SIGNATURE', True):
            self._validate()

        body = b64decode(self._body)

        try:
            if set(['keyId', 'iv']).issubset(self._header):
                key = self._header['keyId']
                keys = self._settings.get('KEYS', {})
                if key not in keys:
                    raise ExtractException('Invalid keyId : %s' (key))

                cipher = aes128cbc(b64decode(keys[key]),
                                   b64decode(self._header['iv']))
                body = cipher.decrypt(body)
        except CryptoException as err:
            raise ExtractException('Cannot decrypt: %s' % (err))
        except Exception as err:
            raise ExtractException('Cannot read: %s' % (err))

        return body
    def decrypt_message_body(self, message):
        header = message['Header']
        body = message['Body']

        try:
            if 'Encoding' not in header:
                if isinstance(body, str):
                    return json.loads(self._re_json_cruft.sub(r'\g<1>', body))
                elif isinstance(body, dict):
                    return body
                else:
                    raise ProcessorException('No body encoding')

            encoding = header['Encoding']
            if str(encoding).lower() != 'base64':
                raise ProcessorException(
                    'Unkown encoding: {}'.format(encoding))

            algorithm = header.get('Algorithm', 'aes128cbc')
            if str(algorithm).lower() != 'aes128cbc':
                raise ProcessorException(
                    'Unsupported algorithm: {}'.format(algorithm))

            kws = KWS()
            key = None
            if 'KeyURL' in header:
                key = kws.get_key(url=header['KeyURL'])
            elif 'KeyId' in self._header:
                key = kws.get_key(key_id=self._header['KeyId'])
            else:
                try:
                    key = kws.get_current_key(header['MessageType'])
                    if not re.match(r'^\s*{.+}\s*$', body):
                        raise CryptoException()
                except (ValueError, CryptoException):
                    RestClientsCache().delete_cached_kws_current_key(
                        header['MessageType'])
                    key = kws.get_current_key(header['MessageType'])

            cipher = aes128cbc(b64decode(key.key), b64decode(header['IV']))
            body = cipher.decrypt(b64decode(body))

            return json.loads(
                self._re_json_cruft.sub(r'\g<1>', body.decode('utf-8')))

        except KeyError as ex:
            logger.error('Key Error: {}\nHEADER: {}'.format(ex, header))
            raise
        except ValueError as ex:
            logger.error('Error: {}\nHEADER: {}\nBODY: {}'.format(
                ex, header, body))
            return {}
        except CryptoException as ex:
            logger.error('Error: {}\nHEADER: {}\nBODY: {}'.format(
                ex, header, body))
            raise ProcessorException('Cannot decrypt: {}'.format(ex))
        except DataFailureException as ex:
            msg = 'Request failure for {}: {} ({})'.format(
                ex.url, ex.msg, ex.status)
            logger.error(msg)
            raise ProcessorException(msg)
        except Exception as ex:
            raise ProcessorException('Cannot read: {}'.format(ex))