Example #1
0
def local_transform_runner(transform, value, fields, params, config, message_writer=message):
    """
    Internal API: The local transform runner is responsible for executing the local transform.

    Parameters:

    transform      - The name or module of the transform to execute (i.e sploitego.transforms.whatismyip).
    value          - The input entity value.
    fields         - A dict of the field names and their respective values.
    params         - The extra parameters passed into the transform via the command line.
    config         - The Canari configuration object.
    message_writer - The message writing function used to write the MaltegoTransformResponseMessage to stdout. This is
                     can either be the console_message or message functions. Alternatively, the message_writer function
                     can be any callable object that accepts the MaltegoTransformResponseMessage as the first parameter
                     and writes the output to a destination of your choosing.

    This helper function is only used by the run-transform, debug-transform, and dispatcher commands.
    """

    try:
        transform = load_object(transform)()

        if os.name == 'posix' and transform.superuser and os.geteuid():
            rc = sudo(sys.argv)
            if rc == 1:
                message_writer(MaltegoTransformResponseMessage() + UIMessage('User cancelled transform.'))
            elif rc == 2:
                message_writer(MaltegoTransformResponseMessage() + UIMessage('Too many incorrect password attempts.'))
            elif rc:
                message_writer(MaltegoTransformResponseMessage() + UIMessage('Unknown error occurred.'))
            exit(rc)

        on_terminate(transform.on_terminate)

        request = MaltegoTransformRequestMessage(
            parameters={'canari.local.arguments': Field(name='canari.local.arguments', value=params)}
        )

        request._entities = [to_entity(transform.input_type, value, fields)]

        msg = transform.do_transform(
            request,
            MaltegoTransformResponseMessage(),
            config
        )
        if isinstance(msg, MaltegoTransformResponseMessage):
            message_writer(msg)
        elif isinstance(msg, basestring):
            raise MaltegoException(msg)
        else:
            raise MaltegoException('Could not resolve message type returned by transform.')
    except MaltegoException, me:
        croak(me, message_writer)
Example #2
0
def run(args):

    [transform, params, value,
     fields] = parseargs(['canari %s' % cmd_name(__name__)] + args)

    transform_module = None

    fix_binpath(config['default/path'])
    try:
        transform_module = import_transform(transform)

        if os.name == 'posix' and hasattr(transform_module.dotransform,
                                          'privileged') and os.geteuid():
            rc = sudo(sys.argv)
            if rc == 1:
                message(MaltegoTransformResponseMessage() +
                        UIMessage('User cancelled transform.'))
            elif rc == 2:
                message(MaltegoTransformResponseMessage() +
                        UIMessage('Too many incorrect password attempts.'))
            elif rc:
                message(MaltegoTransformResponseMessage() +
                        UIMessage('Unknown error occurred.'))
            exit(0)

        if hasattr(transform_module, 'onterminate'):
            onterminate(transform_module.onterminate)
        else:
            transform_module.__setattr__('onterminate', lambda *args: exit(-1))

        input_entity = to_entity(guess_entity_type(transform_module, fields),
                                 value, fields)

        msg = transform_module.dotransform(
            MaltegoTransformRequestMessage(value, fields, params,
                                           input_entity),
            MaltegoTransformResponseMessage()) if get_transform_version(
                transform_module.dotransform
            ) == 2 else transform_module.dotransform(
                MaltegoTransformRequestMessage(value, fields, params,
                                               input_entity),
                MaltegoTransformResponseMessage(), config)

        if isinstance(msg, MaltegoTransformResponseMessage):
            message(msg)
        elif isinstance(msg, basestring):
            raise MaltegoException(msg)
        else:
            raise MaltegoException(
                'Could not resolve message type returned by transform.')
    except MaltegoException, me:
        croak(str(me))
Example #3
0
def run(args):

    [transform, params, value, fields] = parseargs(['canari %s' % cmd_name(__name__)] + args)

    m = None
    pysudo = path.join(get_bin_dir(), 'pysudo')

    fix_binpath(config['default/path'])
    try:
        m = import_transform(transform)

        if name == 'posix' and hasattr(m.dotransform, 'privileged') and geteuid():
# Keep it for another day
#            if platform == 'darwin':
#                execvp(
#                    'osascript',
#                    ['osascript', '-e', 'do shell script "%s" with administrator privileges' % ' '.join(sys.argv)]
#                )
#            if sys.platform.startswith('linux') and path.exists("/usr/bin/gksudo"):
#                execvp('/usr/bin/gksudo', ['/usr/bin/gksudo'] + list(sys.argv))
#            else:
            execvp(pysudo, [pysudo] + list(argv))
            exit(-1)

        if hasattr(m, 'onterminate'):
            onterminate(m.onterminate)
        else:
            m.__setattr__('onterminate', lambda *args: exit(-1))

        msg = m.dotransform(
            type(
                'MaltegoTransformRequestMessage',
                (object,),
                    {
                    'value' : value,
                    'fields' : fields,
                    'params' : params
                }
            )(),
            MaltegoTransformResponseMessage()
        )

        if isinstance(msg, MaltegoTransformResponseMessage):
            message(msg)
        elif isinstance(msg, basestring):
            raise MaltegoException(msg)
        else:
            raise MaltegoException('Could not resolve message type returned by transform.')
    except MaltegoException, me:
        croak(str(me))
Example #4
0
def run(args):

    [transform, params, value, fields] = parseargs(['canari %s' % cmd_name(__name__)] + args)

    m = None

    fix_binpath(config['default/path'])
    try:
        m = import_transform(transform)

        if os.name == 'posix' and hasattr(m.dotransform, 'privileged') and os.geteuid():
            rc = sudo(sys.argv)
            if rc == 1:
                message(MaltegoTransformResponseMessage() + UIMessage('User cancelled transform.'))
            elif rc == 2:
                message(MaltegoTransformResponseMessage() + UIMessage('Too many incorrect password attempts.'))
            elif rc:
                message(MaltegoTransformResponseMessage() + UIMessage('Unknown error occurred.'))
            exit(0)

        if hasattr(m, 'onterminate'):
            onterminate(m.onterminate)
        else:
            m.__setattr__('onterminate', lambda *args: exit(-1))

        msg = m.dotransform(
            type(
                'MaltegoTransformRequestMessage',
                (object,),
                    {
                    'value' : value,
                    'fields' : fields,
                    'params' : params
                }
            )(),
            MaltegoTransformResponseMessage()
        )

        if isinstance(msg, MaltegoTransformResponseMessage):
            message(msg)
        elif isinstance(msg, basestring):
            raise MaltegoException(msg)
        else:
            raise MaltegoException('Could not resolve message type returned by transform.')
    except MaltegoException, me:
        croak(str(me))
Example #5
0
def run(args):

    [transform, params, value, fields] = parseargs(['canari %s' % cmd_name(__name__)] + args)

    transform_module = None

    fix_binpath(config['default/path'])
    try:
        transform_module = import_transform(transform)

        if os.name == 'posix' and hasattr(transform_module.dotransform, 'privileged') and os.geteuid():
            rc = sudo(sys.argv)
            if rc == 1:
                message(MaltegoTransformResponseMessage() + UIMessage('User cancelled transform.'))
            elif rc == 2:
                message(MaltegoTransformResponseMessage() + UIMessage('Too many incorrect password attempts.'))
            elif rc:
                message(MaltegoTransformResponseMessage() + UIMessage('Unknown error occurred.'))
            exit(0)

        if hasattr(transform_module, 'onterminate'):
            onterminate(transform_module.onterminate)
        else:
            transform_module.__setattr__('onterminate', lambda *args: exit(-1))

        input_entity = to_entity(guess_entity_type(transform_module, fields), value, fields)

        msg = transform_module.dotransform(
            MaltegoTransformRequestMessage(value, fields, params, input_entity),
            MaltegoTransformResponseMessage()
        ) if get_transform_version(transform_module.dotransform) == 2 else transform_module.dotransform(
            MaltegoTransformRequestMessage(value, fields, params, input_entity),
            MaltegoTransformResponseMessage(),
            config
        )

        if isinstance(msg, MaltegoTransformResponseMessage):
            message(msg)
        elif isinstance(msg, basestring):
            raise MaltegoException(msg)
        else:
            raise MaltegoException('Could not resolve message type returned by transform.')
    except MaltegoException, me:
        croak(str(me))
Example #6
0
def local_transform_runner(transform,
                           value,
                           fields,
                           params,
                           config,
                           message_writer=message):
    """
    Internal API: The local transform runner is responsible for executing the local transform.

    Parameters:

    transform      - The name or module of the transform to execute (i.e sploitego.transforms.whatismyip).
    value          - The input entity value.
    fields         - A dict of the field names and their respective values.
    params         - The extra parameters passed into the transform via the command line.
    config         - The Canari configuration object.
    message_writer - The message writing function used to write the MaltegoTransformResponseMessage to stdout. This is
                     can either be the console_message or message functions. Alternatively, the message_writer function
                     can be any callable object that accepts the MaltegoTransformResponseMessage as the first parameter
                     and writes the output to a destination of your choosing.

    This helper function is only used by the run-transform, debug-transform, and dispatcher commands.
    """

    try:
        transform = load_object(transform)()

        if os.name == 'posix' and transform.superuser and os.geteuid():
            rc = sudo(sys.argv)
            if rc == 1:
                message_writer(MaltegoTransformResponseMessage() +
                               UIMessage('User cancelled transform.'))
            elif rc == 2:
                message_writer(
                    MaltegoTransformResponseMessage() +
                    UIMessage('Too many incorrect password attempts.'))
            elif rc:
                message_writer(MaltegoTransformResponseMessage() +
                               UIMessage('Unknown error occurred.'))
            exit(rc)

        on_terminate(transform.on_terminate)

        request = MaltegoTransformRequestMessage(
            parameters={
                'canari.local.arguments':
                Field(name='canari.local.arguments', value=params)
            })

        request._entities = [to_entity(transform.input_type, value, fields)]

        msg = transform.do_transform(request,
                                     MaltegoTransformResponseMessage(), config)
        if isinstance(msg, MaltegoTransformResponseMessage):
            message_writer(msg)
        elif isinstance(msg, basestring):
            raise MaltegoException(msg)
        else:
            raise MaltegoException(
                'Could not resolve message type returned by transform.')
    except MaltegoException, me:
        croak(me, message_writer)
Example #7
0
            message_writer(msg)
        elif isinstance(msg, basestring):
            raise MaltegoException(msg)
        else:
            raise MaltegoException(
                'Could not resolve message type returned by transform.')
    except MaltegoException, me:
        croak(me, message_writer)
    except KeyboardInterrupt:
        # Ensure that the keyboard interrupt handler does not execute twice if a transform is sudo'd
        if (transform.superuser
                and not os.geteuid()) or (not transform.superuser
                                          and os.geteuid()):
            transform.on_terminate()
    except Exception:
        croak(traceback.format_exc(), message_writer)


class Response(object):
    def __init__(self, maltego_response):
        self._response = maltego_response
        self._entities = [
            EntityTypeFactory.create(e.type)(e)
            for e in maltego_response.entities
        ]
        self._messages = defaultdict(list)
        for m in maltego_response.messages:
            self._messages[m.type].append(m.message)

    def toXML(self):
        return self._response.render(fragment=True)
Example #8
0
        msg = m.dotransform(
            type(
                'MaltegoTransformRequestMessage',
                (object,),
                    {
                    'value' : value,
                    'fields' : fields,
                    'params' : params
                }
            )(),
            MaltegoTransformResponseMessage()
        )

        if isinstance(msg, MaltegoTransformResponseMessage):
            message(msg)
        elif isinstance(msg, basestring):
            raise MaltegoException(msg)
        else:
            raise MaltegoException('Could not resolve message type returned by transform.')
    except MaltegoException, me:
        croak(str(me))
    except ImportError:
        e = format_exc()
        croak(e)
    except Exception:
        e = format_exc()
        croak(e)
    except KeyboardInterrupt, be:
        if m is not None:
            m.onterminate()
Example #9
0
                                 value, fields)

        msg = transform_module.dotransform(
            MaltegoTransformRequestMessage(value, fields, params,
                                           input_entity),
            MaltegoTransformResponseMessage()) if get_transform_version(
                transform_module.dotransform
            ) == 2 else transform_module.dotransform(
                MaltegoTransformRequestMessage(value, fields, params,
                                               input_entity),
                MaltegoTransformResponseMessage(), config)

        if isinstance(msg, MaltegoTransformResponseMessage):
            message(msg)
        elif isinstance(msg, basestring):
            raise MaltegoException(msg)
        else:
            raise MaltegoException(
                'Could not resolve message type returned by transform.')
    except MaltegoException, me:
        croak(str(me))
    except ImportError:
        e = format_exc()
        croak(e)
    except Exception:
        e = format_exc()
        croak(e)
    except KeyboardInterrupt:
        if transform_module is not None:
            transform_module.onterminate()
Example #10
0
            config
        )
        if isinstance(msg, MaltegoTransformResponseMessage):
            message_writer(msg)
        elif isinstance(msg, basestring):
            raise MaltegoException(msg)
        else:
            raise MaltegoException('Could not resolve message type returned by transform.')
    except MaltegoException, me:
        croak(me, message_writer)
    except KeyboardInterrupt:
        # Ensure that the keyboard interrupt handler does not execute twice if a transform is sudo'd
        if (transform.superuser and not os.geteuid()) or (not transform.superuser and os.geteuid()):
            transform.on_terminate()
    except Exception:
        croak(traceback.format_exc(), message_writer)


class Response(object):
    def __init__(self, maltego_response):
        self._response = maltego_response
        self._entities = [EntityTypeFactory.create(e.type)(e) for e in maltego_response.entities]
        self._messages = defaultdict(list)
        for m in maltego_response.messages:
            self._messages[m.type].append(m.message)

    def toXML(self):
        return self._response.render(fragment=True)

    @property
    def entities(self):