def remove_container(container): log.debug("Stopping container: {0}".format(container.attrs["Name"])) if isinstance(container, Container): if container.status == 'running': container.stop() else: log.debug("Container {0} is not running. No need to stop it") else: error_out("{0} is not a container object".format(container))
def drop_database(container_name='faction_core_1'): print_output("Dropping database..") core = get_container(container_name) result = execute_container_command(core, 'dotnet ef database drop --force') if result.exit_code != 0: error_out("Could not drop database. Output from command: \n{0}".format( result.output)) else: print_output("Database dropped.")
def get_user_id(username): faction_db = FactionDB() log.debug("Getting ID for User: {0}".format(username)) user = faction_db.session.query( faction_db.User).filter_by(Username=username.lower()).first() if user: log.debug("Got User ID: {0}".format(user.Id)) return user.Id else: error_out("Could not find user named: {0}".format(username))
def get_role_id(name): faction_db = FactionDB() log.debug("Getting ID for role: {0}".format(name)) role = faction_db.session.query( faction_db.UserRole).filter_by(Name=name.lower()).first() if role: log.debug("Got UserRole ID: {0}".format(role.Id)) return role.Id else: error_out("Could not find role named: {0}".format(name))
def create_database_migration(name, container_name='faction_core_1'): print_output("Creating database migration..") core = get_container(container_name) name = name + "_" + secrets.token_hex(8) result = execute_container_command( core, 'dotnet ef migrations add {0}'.format(name)) if result.exit_code != 0: error_out("Could create migration. Output from command: \n{0}".format( result.output)) else: print_output("Database dropped.")
def execute_container_command(container, command): log.debug("Executing {0} against container: {1}".format( command, container.attrs["Name"])) if isinstance(container, Container): if container.status == 'running': return container.exec_run(command) else: error_out( "Container {0} is not running. Can not execute commands against it" ) error_out("{0} is not a container object".format(container))
def create_direct_transport(name="DIRECT Transport", transport_type="DIRECT", guid="0000-0000-0000-0000-0000", api_key=None): config = get_config() if not api_key: error_out("No API Key included in request") configuration = '{"TransportId": 1, "ApiUrl":"' + config[ 'EXTERNAL_ADDRESS'] + '","ApiKeyName":"' + api_key[ 'Name'] + '","ApiSecret":"' + api_key['Token'] + '"}' create_transport(name, transport_type, guid, api_key["Id"], configuration)
def create_system_user(system_username=None, system_password=None): if not system_username: config = get_config() system_username = config['SYSTEM_USERNAME'] if not system_password: config = get_config() system_password = config['SYSTEM_PASSWORD'] if not len(system_username) > 0 or not len(system_password) > 0: error_out( "System Username and/or System Password not found in config. Run `setup` to initialize Faction or `new " "config` to create a new config") create_user(system_username, system_password, "system")
def _cleanup_build_artifacts(container_name='faction_core_1'): print_output("Cleaning build artifacts from Core..") core = get_container(container_name) bin_result = execute_container_command(core, 'rm -rf /app/bin') obj_result = execute_container_command(core, 'rm -rf /app/obj') if bin_result.exit_code != 0: error_out( "Could not clean up build artifacts. Output from rm -rf /app/bin: \n{0}" .format(bin_result.output)) if obj_result.exit_code != 0: error_out( "Could not clean up build artifacts. Output from rm -rf /app/obj: \n{0}" .format(obj_result.output))
def create_admin_user(admin_username=None, admin_password=None): if not admin_username: config = get_config() admin_username = config['ADMIN_USERNAME'] if not admin_password: config = get_config() admin_password = config['ADMIN_PASSWORD'] if not len(admin_username) > 0 or not len(admin_password) > 0: error_out( "Admin Username and/or Admin Password not found in config. Run `setup` to initialize faction or `new " "config` to create a new config") create_user(admin_username, admin_password, "admin")
def take_action(self, parsed_args): config = get_config() containers = config["CONTAINERS"] results = [] for container in containers: status = get_container_status(container) if status: results.append((status.name, status.status, status.ip_address, status.created)) else: error_out( "Container {0} not found. Faction won't work with out this." .format(container)) return (("Container Name", "Status", "IP Address", "Created"), results)
def build_faction(): print_output("Building Faction containers..") try: config = get_config() install_path = os.path.join(config["FACTION_PATH"], "install/") log.debug( "Running: 'docker-compose -p faction up -d --force-recreate --build' from {0}" .format(install_path)) ret = call("docker-compose -p faction up -d --force-recreate --build", cwd=install_path, shell=True) if ret == 0: print_output("Faction has been built") else: error_out("Failed to build Faction.") except Exception as e: error_out("Building Faction failed. Error: {0}".format(str(e)))
def take_action(self, parsed_args): print_output("Setup started..") generate_config_file( admin_username=parsed_args.admin_username, admin_password=parsed_args.admin_password, api_upload_dir=parsed_args.api_upload_dir, build=parsed_args.build, console_port=parsed_args.console_port, containers=parsed_args.container_names, docker_network_name=parsed_args.docker_network_name, external_address=parsed_args.external_address, faction_path=parsed_args.faction_path, flask_secret=parsed_args.flask_secret, postgres_host=parsed_args.postgres_host, postgres_database=parsed_args.postgres_database, postgres_username=parsed_args.postgres_username, postgres_password=parsed_args.postgres_password, rabbit_host=parsed_args.rabbit_host, rabbit_username=parsed_args.rabbit_username, rabbit_password=parsed_args.rabbit_password, system_username=parsed_args.system_username, system_password=parsed_args.system_password) if parsed_args.external_address: if not parsed_args.external_address.startswtih( 'http://') or not parsed_args.external_address.startswtih( 'https://'): error_out( 'Setup failed. --external-address argument must begin with http:// or https://' ) if parsed_args.build: for component in parsed_args.components: download_github_repo( "FactionC2/{0}".format(component), "{0}/source/{1}".format(parsed_args.faction_path, component), parsed_args.github_pat) write_build_compose_file() elif parsed_args.dev: write_dev_compose_file() else: write_hub_compose_file() clone_github_repo( "FactionC2/Modules-Dotnet", "{0}/modules/dotnet".format(parsed_args.faction_path)) clone_github_repo( "maraudershell/Marauder", "{0}/agents/Marauder".format(parsed_args.faction_path)) build_faction() if parsed_args.dev: print_output("Pausing setup, you need to do stuff.") print("Add the following to your hosts file: ") print("127.0.0.1 api") print("127.0.0.1 db") print("127.0.0.1 mq\n") print( "Run the following commands from the Faction Core directory: ") print( "1. dotnet ef migration add 'Initial' (You only have to do this once, unless you change the db schema)" ) print("2. dotnet ef database update\n") input("Press enter to continue setup..") else: print_output("Waiting 30 seconds for Core to come up..") core_down = True sleep(30) while core_down: status = get_container_status('faction_core_1') self.log.debug("Got status: {0}".format(status)) if status: if status.status.lower() == 'running': print_output("Core is up, continuing..") core_down = False else: print_output( "Core is not up yet. Waiting 15 more seconds..") sleep(15) create_database_migration("Initial") update_database() create_faction_roles() create_system_user() create_admin_user() system_id = get_user_id('system') api_key = create_api_key(user_id=system_id, owner_id=system_id, type="Transport") create_direct_transport(api_key=api_key) if parsed_args.dev == None or parsed_args.dev == False: print_output("Restarting Core for database changes..") core = get_container("faction_core_1") restart_container(core) config = get_config() print_output( "Setup complete! Get to hacking!!\n\nURL: {0}\nUsername: {1}\nPassword: {2}" .format(config["EXTERNAL_ADDRESS"], config["ADMIN_USERNAME"], config["ADMIN_PASSWORD"]))
def take_action(self, parsed_args): print_output("Setup started..") if parsed_args.external_address: if not (parsed_args.external_address.startswith("http://") or parsed_args.external_address.startswith("https://")): error_out( "Setup failed. --external-address argument must begin with http:// or https://" ) else: ip_options = get_ip_addresses() while True: print_output("Available NICs : IP Addresses") for key, value in ip_options.items(): print(key, " : ", value) selection = input( "Please select a NIC that corresponds to the ip address you wish to use: " ) if selection in ip_options: break parsed_args.external_address = "https://" + ip_options[selection] generate_config_file( admin_username=parsed_args.admin_username, admin_password=parsed_args.admin_password, api_upload_dir=parsed_args.api_upload_dir, build=parsed_args.build_from_source, console_port=parsed_args.console_port, containers=parsed_args.container_names, docker_network_name=parsed_args.docker_network_name, external_address=parsed_args.external_address, faction_path=parsed_args.faction_path, flask_secret=parsed_args.flask_secret, postgres_host=parsed_args.postgres_host, postgres_database=parsed_args.postgres_database, postgres_username=parsed_args.postgres_username, postgres_password=parsed_args.postgres_password, rabbit_host=parsed_args.rabbit_host, rabbit_username=parsed_args.rabbit_username, rabbit_password=parsed_args.rabbit_password, system_username=parsed_args.system_username, system_password=parsed_args.system_password, log_file_size=parsed_args.log_file_size, log_file_number=parsed_args.log_file_number) docker_tag = "latest" github_repo = "master" if parsed_args.release == "development": docker_tag = "dev" github_repo = "development" if parsed_args.build_from_source: for component in parsed_args.components: download_github_repo( "FactionC2/{0}".format(component), "{0}/source/{1}".format(parsed_args.faction_path, component), component, parsed_args.github_pat) write_build_compose_file() elif parsed_args.build_for_dev_environment: write_dev_compose_file() else: write_hub_compose_file(docker_tag) clone_github_repo( github_repo, "FactionC2/Modules-Dotnet", "{0}/modules/dotnet".format(parsed_args.faction_path)) clone_github_repo( github_repo, "maraudershell/Marauder", "{0}/agents/Marauder".format(parsed_args.faction_path)) build_faction() if parsed_args.build_for_dev_environment: print_output("Pausing setup, you need to do stuff.") print("Add the following to your hosts file: ") print("127.0.0.1 api") print("127.0.0.1 db") print("127.0.0.1 mq\n") print( "Run the following commands from the Faction Core directory: ") print( "1. dotnet ef migration add 'Initial' (You only have to do this once, unless you change the db schema)" ) print("2. dotnet ef database update\n") input("Press enter to continue setup..") else: print_output("Waiting 30 seconds for Core to come up..") core_down = True sleep(30) while core_down: status = get_container_status('faction_core_1') self.log.debug("Got status: {0}".format(status)) if status: if status.status.lower() == 'running': print_output("Core is up, continuing..") core_down = False else: print_output( "Core is not up yet. Waiting 15 more seconds..") sleep(15) create_database_migration("Initial") update_database() # Now that the environment is up, we can import common lib from factionpy.processing.user import get_user_id from factionpy.processing.api_key import new_api_key from factioncli.processing.setup.transport import create_direct_transport from factioncli.processing.setup.user_role import create_faction_roles from factioncli.processing.setup.user import create_admin_user, create_system_user create_faction_roles() create_system_user() create_admin_user() print_output("Creating API Key for Direct Transport") system_id = get_user_id('system') api_key = new_api_key(api_key_type="Transport", user_id=system_id, owner_id=system_id) create_direct_transport(api_key=api_key) if parsed_args.build_for_dev_environment is None or parsed_args.build_for_dev_environment is False: print_output("Restarting Core for database changes..") core = get_container("faction_core_1") restart_container(core) config = get_config() print_output( "Setup complete! Happy hacking!!\n\nURL: {0}\nUsername: {1}\nPassword: {2}" .format(config["EXTERNAL_ADDRESS"], config["ADMIN_USERNAME"], config["ADMIN_PASSWORD"]))