def lambda_handler(event, context): s3 = boto3.resource('s3') s3Client = boto3.client('s3') try: my_bucket = s3.Bucket(BUCKET_NAME) for s3_object in my_bucket.objects.all(): filename = s3_object.key s3Client.download_file(BUCKET_NAME, filename, f'{download_dir}{filename}') except ClientError as e: return False amiBaseImage = read_ssm_parameter('baseimage') # Trigger packer from python + packer executable layer pkr = PackerExecutable( "/opt/python/lib/python3.8/site-packages/packerpy/packer") template = f'{download_dir}gold-ami.json' template_vars = {'baseimage': amiBaseImage} (ret, out, err) = pkr.build(template, var=template_vars) outDecoded = out.decode('ISO-8859-1') if ret == 0: ami = re.search((':ami-[0-9][a-zA-Z0-9_]{16}'), outDecoded) amivalue = ami.group(0) amivalue = amivalue[1:] update_ssm_parameter('ami-latest', amivalue)
def main(): """ main method. """ args = get_args() ami_config_file = args.var_file ami_config = get_config(ami_config_file) target_ami_name = generate_ami_name(ami_config['ami_name_prefix']) print(target_ami_name) template = Template() template.add_builder( builder.AmazonEbs( region=ami_config['region'], ami_name=target_ami_name, instance_type=ami_config['instance_type'], source_ami=ami_config['source_ami'], ssh_username=ami_config['ssh_username'], ami_description=ami_config['ami_description'], ami_virtualization_type=ami_config['ami_virtualization_type'], force_deregister=ami_config['force_deregister'], shutdown_behavior=ami_config['shutdown_behavior'], vpc_id=ami_config['vpc_id'], subnet_id=ami_config['subnet_id'], ssh_private_key_file=ami_config['ssh_private_key_file'], ssh_keypair_name=ami_config['ssh_keypair_name'], security_group_id=ami_config['security_group_id'], ) ) template.add_provisioner( provisioner.Ansible( playbook_file=ami_config['playbook_name'], command=ami_config['cmd_ansible'], user=ami_config['ssh_username'], ) ) PackerExecutable(machine_readable=False) p = PackerExecutable(executable_path=ami_config['cmd_packer']) (ret, out, err) = p.build( template.to_json(), ) print(out) print(err)
def BuildAMI (template, vars): print("\nBuilding AMI with Packer, this will take a minute...") p = PackerExecutable("/usr/local/bin/packer") (ret, out, err) = p.build( template, var=vars ) if ret == 0: print("ok") else: raise Exception("Packer AMI failed to build", err)
def create_attack_machine(self): """ Creates and fills in an attack template with the configuration varibles and builds the virtual machine from the template """ # Declare the packer executable print("Building the attack machine: " + self.attack_machine_path + "\n" "--------------------------------------------------------------") p = PackerExecutable(self.executable_path) # Build the attack template attack_template = """{{ "builders": [ {{ "type" : "virtualbox-ovf", "vboxmanage" : [ ["modifyvm", "{{{{.Name}}}}", "--bridgeadapter1", "{interface}"] ], "source_path" : "{machine}", "vm_name" : "attack", "boot_wait" : "30s", "ssh_host" : "{ip}", "ssh_port" : 22, "ssh_username" : "{username}", "ssh_timeout" : "20m", "ssh_password" : "{password}", "ssh_skip_nat_mapping" : "true" }} ], "provisioners": [ {{ "type": "shell", "script": "{attack}" }} ] }} """ # Build the template template = attack_template.format(attack=self.attack_path, machine=self.attack_machine_path, ip=self.attack_ip, username=self.attack_username, password=self.attack_password, interface=self.interface) (_, out, err) = p.build(template, force=True) # Print an output after packer exits print(out) if err: print(err)
class PackerController(): def __init__(self, config, log): self.config = config self.log = log self.p = PackerExecutable("/usr/local/bin/packer") self.packer_amis = [] self.packer_amis.append('splunk-server') if self.config['phantom_server'] == '1': self.packer_amis.append('phantom-server') if self.config['kali_machine'] == '1': self.packer_amis.append('kali_machine') if self.config['windows_domain_controller'] == '1': self.read_and_write_userdata_file() self.packer_amis.append('windows-domain-controller') if self.config['windows_server'] == '1': self.read_and_write_userdata_file() self.packer_amis.append('windows-server') if self.config['windows_client'] == '1': self.read_and_write_userdata_file() self.packer_amis.append('windows-client') def build_amis(self): self.log.info("[action] > build AMIs\n") for packer_ami in self.packer_amis: self.log.info("Generate new Packer AMI packer-" + packer_ami + "-" + self.config['key_name'] + ". This can take some time.") template = 'packer/' + packer_ami + '/packer.json' template_vars = self.config template_vars['splunk_indexer_ip'] = self.config[ 'splunk_server_private_ip'] (ret, out, err) = self.p.build(template, var=template_vars) if ret: self.log.error("ERROR: " + str(out)) sys.exit(1) self.log.info("successfully generated Packer AMI packer-" + packer_ami + "-" + self.config['key_name']) def read_and_write_userdata_file(self): j2_env = Environment(loader=FileSystemLoader('packer/script'), trim_blocks=True) template = j2_env.get_template('userdata.ps1.j2') userdata_file = template.render(self.config) with open('packer/script/userdata.ps1', 'w') as file: file.write(userdata_file) def destroy_amis(self): aws_service.deregister_images(self.packer_amis, self.config, self.log)
def lambda_handler(event, context): s3 = boto3.resource('s3') s3Client = boto3.client('s3') try: my_bucket = s3.Bucket(BUCKET_NAME) for s3_object in my_bucket.objects.all(): filename = s3_object.key s3Client.download_file(BUCKET_NAME, filename, f'{download_dir}{filename}') except ClientError as e: return False #subprocess.call("ls -lrt /opt/python/lib/python3.8/site-packages/packerpy", shell=True) p = PackerExecutable("/opt/python/lib/python3.8/site-packages/packerpy/packer") #p.validate(f'{download_dir}ami-packer.json') (ret, out, err)=p.build(f'{download_dir}ami-packer.json') print(out) subprocess.call("ls -lrt /tmp", shell=True)
def create_network_target(self): """ Creates and fills in a target template with the configuration varibles and builds the virtual machine from the template """ # Declare the packer executable print("Building the target machine: " + self.target_machine_path + "\n" "--------------------------------------------------------------") p = PackerExecutable(self.executable_path) # Add a minute to the self time to allow the attack time target_time = 130 + self.time template = """{{ "builders": [ {{ "type" : "virtualbox-ovf", "vboxmanage" : [ ["modifyvm", "{{{{.Name}}}}", "--bridgeadapter1", "{interface}"] ], "source_path" : "{machine}", "vm_name" : "target", "communicator" : "none", "guest_additions_mode" : "disable", "virtualbox_version_file": "", "boot_wait" : "{time}s" }} ] }} """ # Build the template template = template.format(machine=self.target_machine_path, time=target_time, interface=self.interface) (_, out, err) = p.build(template, force=True) # Print an output after packer exits print(out) if err: print(err)
def create_ami(self): """ Create an AMI using the packer package and template generated from config. """ logging.debug( "Validating Packer executable path {} ".format(PACKER_EXE_PATH)) packer_path = get_abs_file_path(PACKER_EXE_PATH) if not packer_path: exc_msg = "Packer executable not available : {}".format( PACKER_EXE_PATH) generate_exception(exc_msg) p = PackerExecutable(packer_path) json_file_name = get_abs_file_path(VARS_FILE_PATH) logging.debug( "Validating configuration path {} ".format(PACKER_EXE_PATH)) if not json_file_name: exc_msg = "Configuration not available under : {}".format( VARS_FILE_PATH) generate_exception(exc_msg) with open(json_file_name) as f: template_vars = json.load(f) self.access_id = template_vars["aws_access_key"] self.secret_access = template_vars["aws_secret_key"] logging.debug("Creating packer template from configuration") tag_configs = self.generate_tag_for_ami() ts = timegm(gmtime()) self.ami_name = "packer-auto{}".format(ts) template = self.create_template_from_config(tag_configs) logging.debug("Packer template generation successful {}".format( template.to_json())) logging.debug("Generating AMI using config : {}".format(template_vars)) (ret, out, err) = p.build(template.to_json(), var=template_vars) if ret == 1: msg = "AMI generation unsuccessful" logging.error("{} {}".format(msg, err)) generate_exception(msg) else: logging.debug("AMI generation successful {}".format(self.ami_name)) logging.debug("AMi Generation Details {}".format(out))
def invokePacker(region, packerFile, installScript, amiBaseImage, targetAmiName): amivalue = "" pkr = PackerExecutable( "/opt/python/lib/python3.8/site-packages/packerpy/packer") template = download_dir + packerFile installScriptFile = download_dir + installScript template_vars = { 'baseimage': amiBaseImage, 'installScript': installScriptFile, 'targetAmiName': targetAmiName, 'region': region } (ret, out, err) = pkr.build(template, var=template_vars) outDecoded = out.decode('ISO-8859-1') print(outDecoded) if ret == 0: ami = re.search((':ami-[0-9][a-zA-Z0-9_]{16}'), outDecoded) amivalue = ami.group(0) amivalue = amivalue[1:] return amivalue