Exemple #1
0
 def write(self, module, content, mode=None):
     """Write the PKCS#12 file."""
     if self.backup:
         self.backup_file = module.backup_local(self.path)
     write_file(module, content, mode)
     if self.return_content:
         self.pkcs12_bytes = content
    def generate(self, module):
        """Generate the public key."""

        if self.privatekey_content is None and not os.path.exists(
                self.privatekey_path):
            raise PublicKeyError('The private key %s does not exist' %
                                 self.privatekey_path)

        if not self.check(module, perms_required=False) or self.force:
            try:
                publickey_content = self._create_publickey(module)
                if self.return_content:
                    self.publickey_bytes = publickey_content

                if self.backup:
                    self.backup_file = module.backup_local(self.path)
                write_file(module, publickey_content)

                self.changed = True
            except OpenSSLBadPassphraseError as exc:
                raise PublicKeyError(exc)
            except (IOError, OSError) as exc:
                raise PublicKeyError(exc)

        self.fingerprint = get_fingerprint(
            path=self.privatekey_path,
            content=self.privatekey_content,
            passphrase=self.privatekey_passphrase,
            backend=self.backend,
        )
        file_args = module.load_file_common_arguments(module.params)
        if module.set_fs_attributes_if_different(file_args, False):
            self.changed = True
Exemple #3
0
    def generate(self, module):
        """Generate a keypair."""

        if self.module_backend.needs_regeneration():
            # Regenerate
            if not self.check_mode:
                if self.backup:
                    self.backup_file = module.backup_local(self.path)
                self.module_backend.generate_private_key()
                privatekey_data = self.module_backend.get_private_key_data()
                if self.return_content:
                    self.privatekey_bytes = privatekey_data
                write_file(module, privatekey_data, 0o600)
            self.changed = True
        elif self.module_backend.needs_conversion():
            # Convert
            if not self.check_mode:
                if self.backup:
                    self.backup_file = module.backup_local(self.path)
                self.module_backend.convert_private_key()
                privatekey_data = self.module_backend.get_private_key_data()
                if self.return_content:
                    self.privatekey_bytes = privatekey_data
                write_file(module, privatekey_data, 0o600)
            self.changed = True

        file_args = module.load_file_common_arguments(module.params)
        self.changed = module.set_fs_attributes_if_different(
            file_args, self.changed)
    def generate(self, module):
        """Generate a keypair."""

        if not self.check(module, perms_required=False, ignore_conversion=True) or self.force:
            # Regenerate
            if self.backup:
                self.backup_file = module.backup_local(self.path)
            self._generate_private_key()
            privatekey_data = self._get_private_key_data()
            if self.return_content:
                self.privatekey_bytes = privatekey_data
            write_file(module, privatekey_data, 0o600)
            self.changed = True
        elif not self.check(module, perms_required=False, ignore_conversion=False):
            # Convert
            if self.backup:
                self.backup_file = module.backup_local(self.path)
            self._ensure_private_key_loaded()
            privatekey_data = self._get_private_key_data()
            if self.return_content:
                self.privatekey_bytes = privatekey_data
            write_file(module, privatekey_data, 0o600)
            self.changed = True

        self.fingerprint = self._get_fingerprint()
        file_args = module.load_file_common_arguments(module.params)
        if module.set_fs_attributes_if_different(file_args, False):
            self.changed = True
    def generate(self):
        result = None
        if not self.check(perms_required=False,
                          ignore_conversion=True) or self.force:
            result = self._generate_crl()
        elif not self.check(perms_required=False,
                            ignore_conversion=False) and self.crl:
            if self.format == 'pem':
                result = self.crl.public_bytes(Encoding.PEM)
            else:
                result = self.crl.public_bytes(Encoding.DER)

        if result is not None:
            if self.return_content:
                if self.format == 'pem':
                    self.crl_content = result
                else:
                    self.crl_content = base64.b64encode(result)
            if self.backup:
                self.backup_file = self.module.backup_local(self.path)
            write_file(self.module, result)
            self.changed = True

        file_args = self.module.load_file_common_arguments(self.module.params)
        if self.module.set_fs_attributes_if_different(file_args, False):
            self.changed = True
Exemple #6
0
    def generate(self, module):
        if self.module_backend.needs_regeneration():
            if not self.check_mode:
                self.module_backend.generate_certificate()
                result = self.module_backend.get_certificate_data()
                if self.backup:
                    self.backup_file = module.backup_local(self.path)
                write_file(module, result)
            self.changed = True

        file_args = module.load_file_common_arguments(module.params)
        self.changed = module.set_fs_attributes_if_different(file_args, self.changed)
    def generate(self, module):
        '''Generate the certificate signing request.'''
        if self.force or self.module_backend.needs_regeneration():
            if not self.check_mode:
                self.module_backend.generate_csr()
                result = self.module_backend.get_csr_data()
                if self.backup:
                    self.backup_file = module.backup_local(self.path)
                write_file(module, result)
            self.changed = True

        file_args = module.load_file_common_arguments(module.params)
        if module.check_file_absent_if_check_mode(file_args['path']):
            self.changed = True
        else:
            self.changed = module.set_fs_attributes_if_different(
                file_args, self.changed)
Exemple #8
0
 def _do_generate(self, module):
     """Actually generate the DH params."""
     # Generate parameters
     params = cryptography.hazmat.primitives.asymmetric.dh.generate_parameters(
         generator=2,
         key_size=self.size,
         backend=self.crypto_backend,
     )
     # Serialize parameters
     result = params.parameter_bytes(
         encoding=cryptography.hazmat.primitives.serialization.Encoding.PEM,
         format=cryptography.hazmat.primitives.serialization.
         ParameterFormat.PKCS3,
     )
     # Write result
     if self.backup:
         self.backup_file = module.backup_local(self.path)
     write_file(module, result)
    def request_cert(self, module):
        if not self.check(module) or self.force:
            body = {}

            # Read the CSR contents
            if self.csr and os.path.exists(self.csr):
                with open(self.csr, 'r') as csr_file:
                    body['csr'] = csr_file.read()

            # Check if the path is already a cert
            # tracking_id may be set as a parameter or by get_cert_details if an entrust cert is in 'path'. If tracking ID is null
            # We will be performing a reissue operation.
            if self.request_type != 'new' and not self.tracking_id:
                module.warn(
                    'No existing Entrust certificate found in path={0} and no tracking_id was provided, setting request_type to "new" for this task'
                    'run. Future playbook runs that point to the pathination file in {1} will use request_type={2}'
                    .format(self.path, self.path, self.request_type))
                self.request_type = 'new'
            elif self.request_type == 'new' and self.tracking_id:
                module.warn(
                    'Existing certificate being acted upon, but request_type is "new", so will be a new certificate issuance rather than a'
                    'reissue or renew')
            # Use cases where request type is new and no existing certificate, or where request type is reissue/renew and a valid
            # existing certificate is found, do not need warnings.

            body.update(self.convert_tracking_params(module))
            body.update(self.convert_cert_subject_params(module))
            body.update(self.convert_general_params(module))
            body.update(self.convert_expiry_params(module))

            if not module.check_mode:
                try:
                    if self.request_type == 'validate_only':
                        body['validateOnly'] = 'true'
                        result = self.ecs_client.NewCertRequest(Body=body)
                    if self.request_type == 'new':
                        result = self.ecs_client.NewCertRequest(Body=body)
                    elif self.request_type == 'renew':
                        result = self.ecs_client.RenewCertRequest(
                            trackingId=self.tracking_id, Body=body)
                    elif self.request_type == 'reissue':
                        result = self.ecs_client.ReissueCertRequest(
                            trackingId=self.tracking_id, Body=body)
                    self.tracking_id = result.get('trackingId')
                    self.set_cert_details(module)
                except RestOperationException as e:
                    module.fail_json(
                        msg=
                        'Failed to request new certificate from Entrust (ECS) {0}'
                        .format(e.message))

                if self.request_type != 'validate_only':
                    if self.backup:
                        self.backup_file = module.backup_local(self.path)
                    write_file(
                        module,
                        to_bytes(self.cert_details.get('endEntityCert')))
                    if self.full_chain_path and self.cert_details.get(
                            'chainCerts'):
                        if self.backup:
                            self.backup_full_chain_file = module.backup_local(
                                self.full_chain_path)
                        chain_string = '\n'.join(
                            self.cert_details.get('chainCerts')) + '\n'
                        write_file(module,
                                   to_bytes(chain_string),
                                   path=self.full_chain_path)
                    self.changed = True
        # If there is no certificate present in path but a tracking ID was specified, save it to disk
        elif not os.path.exists(self.path) and self.tracking_id:
            if not module.check_mode:
                write_file(module,
                           to_bytes(self.cert_details.get('endEntityCert')))
                if self.full_chain_path and self.cert_details.get(
                        'chainCerts'):
                    chain_string = '\n'.join(
                        self.cert_details.get('chainCerts')) + '\n'
                    write_file(module,
                               to_bytes(chain_string),
                               path=self.full_chain_path)
            self.changed = True
    def request_cert(self, module):
        if self.force:
            body = {}

            # Read the CSR contents
            if self.csr and os.path.exists(self.csr):
                with open(self.csr, 'r') as csr_file:
                    body['certificate_request'] = csr_file.read()

            # Check if the path is already a cert
            # set details by get_cert_details if an ejbca cert is in 'path'.
            if self.request_type != 'new':
                module.warn('No existing certificate found in path={0}, setting request_type to "new" for this task'
                            'run. Future playbook runs that point to the pathination file in {1} will use request_type={2}'
                            .format(self.path, self.path, self.request_type))
                self.request_type = 'new'
            elif self.request_type == 'new':
                module.warn('Existing certificate being acted upon, but request_type is "new", so will be a new certificate issuance rather than a '
                            'reissue or renew')
            # Use cases where request type is new and no existing certificate, or where request type is reissue/renew and a valid
            # existing certificate is found, do not need warnings.

            #body['certificate_profile_name'] = 'Client';
            body['certificate_profile_name'] = self.certificate_profile;
            #body['end_entity_profile_name'] = 'User';
            body['end_entity_profile_name'] = self.end_entity_profile;
            #body['certificate_authority_name'] = 'ManagementCA';
            body['certificate_authority_name'] = self.certificate_authority;
            body['include_chain'] = 'true';
            # TODO: random username and password
            body['username'] = '******';
            body['password'] = '******';
            
            
            if not module.check_mode:
                try:
                    if self.request_type == 'validate_only':
                        body['validateOnly'] = 'true'
                        result = self.ejbca_client.NewCertRequest(Body=body) #TODO
                    if self.request_type == 'new':
                        result = self.ejbca_client.Pkcs10Enroll(Body=body)
                    elif self.request_type == 'renew':
                        result = self.ejbca_client.RenewCertRequest(trackingId=self.tracking_id, Body=body)#TODO
                    elif self.request_type == 'reissue':
                        result = self.ejbca_client.ReissueCertRequest(trackingId=self.tracking_id, Body=body)#TODO
                    self.serial_number = result.get('serial_number')
                except RestOperationException as e:
                    module.fail_json(msg='Failed to request new certificate from EJBCA {0}'.format(e.message))

                if self.request_type != 'validate_only':
                    if self.backup:
                        self.backup_file = module.backup_local(self.path)
                    # We get certbytes just base64 encoded, but without PEM headers
                    certbytes = base64.b64decode(result.get('certificate'))
                    cert_PEM = ssl.DER_cert_to_PEM_cert(certbytes);
                    write_file(module, to_bytes(cert_PEM))
                    if self.full_chain_path and result.get('certificate_chain'):
                        if self.backup:
                            self.backup_full_chain_file = module.backup_local(self.full_chain_path)
                        chain_string = '\n'.join(result.get('certificate_chain')) + '\n'
                        write_file(module, to_bytes(chain_string), path=self.full_chain_path)
                    self.changed = True