Esempio n. 1
0
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)
Esempio n. 2
0
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)
Esempio n. 3
0
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)
Esempio n. 4
0
    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)
Esempio n. 5
0
def set_engine(packer="/usr/local/bin/packer"):
    """
    packer binary -- full path, check perms, so on...

    :param packer: str
    :returns: :class:`packerpy`
    """
    return PackerExecutable(packer)
Esempio n. 6
0
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 __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')
Esempio n. 8
0
    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)
Esempio n. 9
0
 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))
Esempio n. 10
0
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
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)
Esempio n. 12
0
            str(int(current_box_version["version"].split('.')[2]) + 1)

print("Building new catosplace/ubuntu1804-desktop-base box version " + next_box_version)
version = UserVar("version", next_box_version)

post_processors = [
    post_processor.Vagrant(
        output = "builds/ubuntu1804-desktop-base.box",
        include = [
            "info.json"
        ]
    )
]

t = Template()
t.add_variable(desktop_user_variables)
t.add_variable(version)
t.add_builder(builders)
t.add_provisioner(provisioners)
# Move to new script user artifice
#t.add_post_processor(post_processors)

# View Packer Template
print(t.to_json())

(ret, out, err) = PackerExecutable(machine_readable=False).validate(t.to_json())
print(out.decode('unicode_escape'))

(ret, out, err) = PackerExecutable(machine_readable=False).build(t.to_json())
print(out.decode('unicode_escape'))
Esempio n. 13
0
    def test_specify_executable_path(self):
        p = PackerExecutable(executable_path="/usr/local/bin/packer")
        result = p.configuration

        assert result[PackerExecutable.PATH] == "/usr/local/bin/packer", result