Esempio n. 1
0
    def kill_listener(self, listener_name):
        """
        Shut down the server associated with a listenerName and delete the
        listener from the database.

        To kill all listeners, use listenerName == 'all'
        """

        if listener_name.lower() == 'all':
            listener_names = list(self.activeListeners.keys())
        else:
            listener_names = [listener_name]

        for listener_name in listener_names:
            if listener_name not in self.activeListeners:
                print(
                    helpers.color("[!] Listener '%s' not active!" %
                                  (listener_name)))
                return False
            listener = Session().query(models.Listener).filter(
                models.Listener.name == listener_name).first()

            # shut down the listener and remove it from the cache
            if self.mainMenu.listeners.get_listener_module(
                    listener_name) == 'redirector':
                del self.activeListeners[listener_name]
                Session().delete(listener)
                continue

            self.shutdown_listener(listener_name)

            # remove the listener from the database
            Session().delete(listener)
        Session().commit()
Esempio n. 2
0
    def disable_user(self, uid, disable):
        """
        Disable user
        """
        user = Session().query(models.User).filter(models.User.id == uid).first()

        if not self.user_exists(uid):
                message = False
        elif self.is_admin(uid):
            signal = json.dumps({
                'print': True,
                'message': "Cannot disable admin account"
            })
            message = False
        else:
            user.enabled = not(disable)
            Session.commit()

            signal = json.dumps({
                'print': True,
                'message': 'User {}'.format('disabled' if disable else 'enabled')
            })
            message = True

        dispatcher.send(signal, sender="Users")
        return message
Esempio n. 3
0
 def add_credential_note(self, credential_id, note):
     """
     Update a note to a credential in the database.
     """
     results = Session().query(models.Agent).filter(models.Credential.id == credential_id).first()
     results.notes = note
     Session().commit()
Esempio n. 4
0
    def delete_listener(self, listener_name):
        """
        Delete listener(s) from database.
        """

        try:
            listeners = Session().query(models.Listener).all()

            db_names = [x['name'] for x in listeners]
            if listener_name.lower() == "all":
                names = db_names
            else:
                names = [listener_name]

            for name in names:
                if not name in db_names:
                    print(
                        helpers.color("[!] Listener '%s' does not exist!" %
                                      name))
                    return False

                if name in list(self.activeListeners.keys()):
                    self.shutdown_listener(name)

                listener = Session().query(models.Listener).filter(
                    models.Listener.name == name).first()
                Session().delete(listener)
            Session().commit()

        except Exception as e:
            print(helpers.color("[!] Error deleting listener '%s'" % name))
Esempio n. 5
0
    def add_new_user(self, user_name, password):
        """
        Add new user to cache
        """
        last_logon = helpers.getutcnow()
        success = Session().add(models.User(username=user_name,
                                   password=self.get_hashed_password(password),
                                   last_logon_time=last_logon,
                                   enabled=True,
                                   admin=False,
                                   ))
        Session().commit()

        if success:
            # dispatch the event
            signal = json.dumps({
                'print': True,
                'message': "Added {} to Users".format(user_name)
            })
            dispatcher.send(signal, sender="Users")
            message = True
        else:
            message = False

        return message
Esempio n. 6
0
 def remove_credentials(self, credIDs):
     """
     Removes a list of IDs from the database
     """
     for credID in credIDs:
         cred_entry = Session().query(models.Credential).filter(models.Credential.id == credID).first()
         Session().delete(cred_entry)
     Session().commit()
Esempio n. 7
0
 def remove_all_credentials(self):
     """
     Remove all credentials from the database.
     """
     creds = Session().query(models.Credential).all()
     for cred in creds:
         Session().delete(cred)
     Session().commit()
Esempio n. 8
0
    def user_logout(self, uid):
        user = Session().query(models.User).filter(models.User.id == uid).first()
        user.api_token = ''
        Session.commit()

        # dispatch the event
        signal = json.dumps({
            'print': True,
            'message': "User disconnected"
        })
        dispatcher.send(signal, sender="Users")
Esempio n. 9
0
    def enable_listener(self, listener_name):
        """
        Starts an existing listener and sets it to enabled
        """
        if listener_name in list(self.activeListeners.keys()):
            print(helpers.color("[!] Listener already running!"))
            return False

        result = Session().query(models.Listener).filter(
            models.Listener.name == listener_name).first()

        if not result:
            print(
                helpers.color("[!] Listener %s doesn't exist!" %
                              listener_name))
            return False
        module_name = result['module']
        options = result['options']

        try:
            listener_module = self.loadedListeners[module_name]

            for option, value in options.items():
                listener_module.options[option] = value

            print(helpers.color("[*] Starting listener '%s'" % listener_name))
            if module_name == 'redirector':
                success = True
            else:
                success = listener_module.start(name=listener_name)

            if success:
                print(helpers.color('[+] Listener successfully started!'))
                listener_options = copy.deepcopy(listener_module.options)
                self.activeListeners[listener_name] = {
                    'moduleName': module_name,
                    'options': listener_options
                }

                listener = Session().query(models.Listener).filter(
                    and_(models.Listener.name == listener_name,
                         models.Listener.module != 'redirector')).first()
                listener.enabled = True
                Session().commit()
            else:
                print(helpers.color('[!] Listener failed to start!'))
        except Exception as e:
            traceback.print_exc()
            if listener_name in self.activeListeners:
                del self.activeListeners[listener_name]
            print(helpers.color("[!] Error starting listener: %s" % e))
Esempio n. 10
0
    def update_listener_options(self, listener_name, option_name, option_value):
        """
        Updates a listener option in the database
        """
        listener = Session().query(models.Listener).filter(models.Listener.name == listener_name).first()

        if not listener:
            print(helpers.color("[!] Listener %s not found" % listener_name))
            return
        if option_name not in list(listener.options.keys()):
            print(helpers.color("[!] Listener %s does not have the option %s" % (listener_name, option_name)))
            return
        listener.options[option_name]['Value'] = option_value
        Session().commit()
Esempio n. 11
0
    def get_user_from_token(self, token):
        user = Session().query(models.User).filter(models.User.api_token == token).first()

        if user:
            return {'id': user.id, 'username': user.username, 'api_token': user.api_token, 'last_logon_time': user.last_logon_time, 'enabled': user.enabled, 'admin': user.admin, "notes": user.notes}

        return None
Esempio n. 12
0
    def get_listener_for_socket(self, name):
        listener = Session().query(models.Listener).filter(models.Listener.name == name).first()

        return {'ID': listener.id, 'name': listener.name, 'module': listener.module,
                'listener_type': listener.listener_type,
                'listener_category': listener.listener_category, 'options': listener.options,
                'created_at': listener.created_at}
Esempio n. 13
0
def keyword_obfuscation(data):
    functions = Session().query(models.Function).all()

    for function in functions:
        data = data.replace(function.keyword, function.replacement)

    return data
Esempio n. 14
0
    def update_username(self, uid, username):
        """
        Update a user's username.
        Currently only when empire is start up with the username arg.
        """
        user = Session().query(models.User).filter(models.User.id == uid).first()
        user.username = username
        Session.commit()

        # dispatch the event
        signal = json.dumps({
            'print': True,
            'message': "Username updated"
        })
        dispatcher.send(signal, sender="Users")

        return True
Esempio n. 15
0
 def user_exists(self, uid):
     """
     Return whether a user exists or not
     """
     user = Session().query(models.User).filter(models.User.id == uid).first()
     if user:
         return True
     else:
         return False
Esempio n. 16
0
    def update_password(self, uid, password):
        """
        Update the last logon timestamp for a user
        """
        if not self.user_exists(uid):
            return False

        user = Session().query(models.User).filter(models.User.id == uid).first()
        user.password = self.get_hashed_password(password)
        Session.commit()

        # dispatch the event
        signal = json.dumps({
            'print': True,
            'message': "Password updated"
        })
        dispatcher.send(signal, sender="Users")

        return True
Esempio n. 17
0
    def get_listener_module(self, listener_name):
        """
        Resolve a listener name to the module used to instantiate it.
        """
        results = Session().query(models.Listener.module).filter(models.Listener.name == listener_name).first()

        if results:
            return results[0]
        else:
            return None
Esempio n. 18
0
    def is_admin(self, uid):
        """
        Returns whether a user is an admin or not.
        """
        admin = Session().query(models.User.admin).filter(models.User.id == uid).first()

        if admin[0] == True:
            return True

        return False
Esempio n. 19
0
    def add_credential(self, credtype, domain, username, password, host, os='', sid='', notes=''):
        """
        Add a credential with the specified information to the database.
        """
        results = Session().query(models.Credential).filter(and_(models.Credential.credtype.like(credtype),
                                                                 models.Credential.domain.like(domain),
                                                                 models.Credential.username.like(username),
                                                                 models.Credential.password.like(password))).all()

        if results == []:
            Session().add(models.Credential(credtype=credtype,
                                            domain=domain,
                                            username=username,
                                            password=password,
                                            host=host,
                                            os=os,
                                            sid=sid,
                                            notes=notes))

            Session().commit()
Esempio n. 20
0
    def disable_listener(self, listener_name):
        """
        Wrapper for shutdown_listener(), also marks listener as 'disabled' so it won't autostart
        """
        active_listener_module_name = self.activeListeners[listener_name]['moduleName']

        listener = Session().query(models.Listener).filter(
            and_(models.Listener.name == listener_name.lower(), models.Listener.module != 'redirector')).first()
        listener.enabled = False

        self.shutdown_listener(listener_name)
        Session.commit()

        # dispatch this event
        message = "[*] Listener {} killed".format(listener_name)
        signal = json.dumps({
            'print': True,
            'message': message
        })
        dispatcher.send(signal, sender="listeners/{}/{}".format(active_listener_module_name, listener_name))
Esempio n. 21
0
    def get_listener_id(self, name):
        """
        Resolve a name to listener ID.
        """
        results = Session().query(models.Listener.id).filter(
            or_(models.Listener.name == name, models.Listener.id == name)).first()

        if results:
            return results[0]
        else:
            return None
Esempio n. 22
0
    def get_listener_name(self, listener_id):
        """
        Resolve a listener ID to a name.
        """
        results = Session().query(models.Listener.name).filter(
            or_(models.Listener.name == listener_id, models.Listener.id == listener_id)).first()

        if results:
            return results[0]
        else:
            return None
Esempio n. 23
0
    def start_existing_listeners(self):
        """
        Startup any listeners that are currently in the database.
        """
        listeners = Session().query(
            models.Listener).filter(models.Listener.enabled == True).all()

        for listener in listeners:
            listener_name = listener.name
            module_name = listener.module
            name_base = listener_name
            options = listener.options

            i = 1
            while listener_name in list(self.activeListeners.keys()):
                listener_name = "%s%s" % (name_base, i)

            try:
                listener_module = self.loadedListeners[module_name]

                for option, value in options.items():
                    listener_module.options[option] = value

                print(
                    helpers.color("[*] Starting listener '%s'" %
                                  listener_name))
                if module_name == 'redirector':
                    success = True
                else:
                    success = listener_module.start(name=listener_name)

                if success:
                    listener_options = copy.deepcopy(listener_module.options)
                    self.activeListeners[listener_name] = {
                        'moduleName': module_name,
                        'options': listener_options
                    }
                    # dispatch this event
                    message = "[+] Listener successfully started!"
                    signal = json.dumps({
                        'print': True,
                        'message': message,
                        'listener_options': listener_options
                    })
                    dispatcher.send(signal,
                                    sender="listeners/{}/{}".format(
                                        module_name, listener_name))
                else:
                    print(helpers.color('[!] Listener failed to start!'))

            except Exception as e:
                if listener_name in self.activeListeners:
                    del self.activeListeners[listener_name]
                print(helpers.color("[!] Error starting listener: %s" % e))
Esempio n. 24
0
def get_listener_options(listener_name):
    """
    Returns the options for a specified listenername from the database outside
    of the normal menu execution.
    """
    try:
        listener_options = Session().query(models.Listener.options).filter(
            models.Listener.name == listener_name).first()
        return listener_options

    except Exception:
        return None
Esempio n. 25
0
    def get_inactive_listeners(self):
        """
        Returns any listeners that are not currently running
        """
        db_listeners = Session().query(models.Listener).filter(models.Listener.enabled == False).all()

        inactive_listeners = {}
        for listener in db_listeners:
            inactive_listeners[listener['name']] = {'moduleName': listener['module'],
                                                    'options': listener['options']}

        return inactive_listeners
Esempio n. 26
0
def log_event(name, event_type, message, timestamp, task_id=None):
    """
    Log arbitrary events

    cur        - a database connection object (such as that returned from
                 `get_db_connection()`)
    name       - the sender string from the dispatched event
    event_type - the category of the event - agent_result, agent_task,
                 agent_rename, etc. Ideally a succinct description of what the
                 event actually is.
    message    - the body of the event, WHICH MUST BE JSON, describing any
                 pertinent details of the event
    timestamp  - when the event occurred
    task_id    - the ID of the task this event is in relation to. Enables quick
                 queries of an agent's task and its result together.
    """
    Session().add(models.Reporting(name=name,
                                   event_type=event_type,
                                   message=message,
                                   timestamp=timestamp,
                                   taskID=task_id))
    Session().commit()
Esempio n. 27
0
def get_config(fields):
    """
    Helper to pull common database config information outside of the
    normal menu execution.

    Fields should be comma separated.
        i.e. 'version,install_path'
    """
    results = []
    config = Session().query(models.Config).first()

    for field in fields.split(','):
        results.append(config[field.strip()])

    return results
Esempio n. 28
0
    def user_login(self, user_name, password):
        user = Session().query(models.User).filter(models.User.username == user_name).first()
            
        if user is None:
            return None

        if not self.check_password(password, user.password):
            return None

        user.api_token = user.api_token or self.refresh_api_token()
        user.last_logon_time = helpers.getutcnow()
        user.username = user_name
        Session.commit()

        # dispatch the event
        signal = json.dumps({
            'print': True,
            'message': "{} connected".format(user_name)
        })
        dispatcher.send(signal, sender="Users")
        return user.api_token
Esempio n. 29
0
    def get_credentials(self, filter_term=None, credtype=None, note=None, os=None):
        """
        Return credentials from the database.

        'credtype' can be specified to return creds of a specific type.
        Values are: hash, plaintext, and token.
        """

        # if we're returning a single credential by ID
        if self.is_credential_valid(filter_term):
            results = Session().query(models.Credential).filter(models.Credential.id == filter_term).first()

        # if we're filtering by host/username
        elif filter_term and filter_term != '':
            filter_term = filter_term.replace('*', '%')
            search = "%{}%".format(filter_term)
            results = Session().query(models.Credential).filter(or_(models.Credential.domain.like(search),
                                                                    models.Credential.username.like(search),
                                                                    models.Credential.host.like(search),
                                                                    models.Credential.password.like(search))).all()

        # if we're filtering by credential type (hash, plaintext, token)
        elif credtype and credtype != "":
            results = Session().query(models.Credential).filter(models.Credential.credtype.ilike(f'%credtype%')).all()

        # if we're filtering by content in the note field
        elif note and note != "":
            search = "%{}%".format(note)
            results = Session().query(models.Credential).filter(models.Credential.note.ilike(f'%search%')).all()

        # if we're filtering by content in the OS field
        elif os and os != "":
            search = "%{}%".format(os)
            results = Session().query(models.Credential).filter(models.Credential.os.ilike('%search%')).all()

        # otherwise return all credentials
        else:
            results = Session().query(models.Credential).all()

        return results
Esempio n. 30
0
 def is_credential_valid(self, credentialID):
     """
     Check if this credential ID is valid.
     """
     results = Session().query(models.Credential).filter(models.Credential.id == credentialID).all()
     return len(results) > 0