Exemple #1
0
 def _run_ldclt(self, cmd):
     result = None
     self.log.debug("ldclt loadtest ...")
     self.log.debug(format_cmd_list(cmd))
     try:
         result = ensure_str(subprocess.check_output(cmd))
     # If verbose, capture / log the output.
     except subprocess.CalledProcessError as e:
         print(format_cmd_list(cmd))
         print(result)
         raise (e)
     self.log.debug(result)
     # The output looks like:
     # ldclt[44308]: Average rate: 4017.60/thr  (4017.60/sec), total:  40176
     # ldclt[44308]: Number of samples achieved. Bye-bye...
     # ldclt[44308]: All threads are dead - exit.
     # ldclt[44308]: Global average rate: 40604.00/thr  (4060.40/sec), total: 406040
     # ldclt[44308]: Global number times "no activity" reports: never
     # ldclt[44308]: Global no error occurs during this session.
     # So we want the "global avg rate" per second.
     section = None
     for line in result.splitlines():
         if 'Global average rate' in line:
             section = line.split('(')[1].split(')')[0].split('/')[0]
     return section
Exemple #2
0
    def create_rsa_ca(self, months=VALID):
        """
        Create a self signed CA.
        """

        # Wait a second to avoid an NSS bug with serial ids based on time.
        time.sleep(1)
        # Create noise.
        self._generate_noise('%s/noise.txt' % self._certdb)
        # Now run the command. Can we do this with NSS native?
        cmd = [
            '/usr/bin/certutil',
            '-S',
            '-n',
            CA_NAME,
            '-s',
            ISSUER,
            '-x',
            '-g',
            '%s' % KEYBITS,
            '-t',
            'CT,,',
            '-v',
            '%s' % months,
            '-2',
            '--keyUsage',
            'certSigning',
            '-d',
            self._certdb,
            '-z',
            '%s/noise.txt' % self._certdb,
            '-f',
            '%s/%s' % (self._certdb, PWD_TXT),
        ]
        cmd_input = b'y\n\n'  # responses to certutil questions
        self.log.debug("nss cmd: %s", format_cmd_list(cmd))
        result = ensure_str(
            run(cmd, check=True, stderr=PIPE, stdout=PIPE,
                input=cmd_input).stdout)
        self.log.debug("nss output: %s", result)
        # Now extract the CAcert to a well know place.
        # This allows us to point the cacert dir here and it "just works"
        cmd = [
            '/usr/bin/certutil',
            '-L',
            '-n',
            CA_NAME,
            '-d',
            self._certdb,
            '-a',
        ]
        self.log.debug("nss cmd: %s", format_cmd_list(cmd))
        try:
            certdetails = check_output(cmd, stderr=subprocess.STDOUT)
        except subprocess.CalledProcessError as e:
            raise ValueError(e.output.decode('utf-8').rstrip())
        with open('%s/ca.crt' % self._certdb, 'w') as f:
            f.write(ensure_str(certdetails))
        self.openssl_rehash(self._certdb)
        return True
Exemple #3
0
 def bind_loadtest(self, subtree, min=1000, max=9999, rounds=3):
     # The bind users will be uid=userXXXX
     digits = len('%s' % max)
     cmd = [
         '%s/bin/ldclt' % self.ds.prefix,
         '-h',
         self.ds.host,
         '-p',
         '%s' % self.ds.port,
         '-N',
         '%s' % rounds,
         '-D',
         'uid=user%s,%s' % ('X' * digits, subtree),
         '-w',
         'user%s' % ('X' * digits),
         '-e',
         "randombinddn,randombinddnlow=%s,randombinddnhigh=%s" % (min, max),
         '-e',
         'bindonly',
     ]
     result = None
     self.log.debug("ldclt loadtest ...")
     self.log.debug(format_cmd_list(cmd))
     try:
         result = subprocess.check_output(cmd)
     # If verbose, capture / log the output.
     except subprocess.CalledProcessError as e:
         print(format_cmd_list(cmd))
         print(result)
         raise (e)
     self.log.debug(result)
Exemple #4
0
    def add_server_key_and_cert(self, input_key, input_cert):
        if not os.path.exists(input_key):
            raise ValueError(
                "The key file ({}) does not exist".format(input_key))
        if not os.path.exists(input_cert):
            raise ValueError(
                "The cert file ({}) does not exist".format(input_cert))

        self._assert_not_chain(input_key)
        self._assert_not_chain(input_cert)

        self.log.debug(f"Importing key and cert -> {input_key}, {input_cert}")

        p12_bundle = "%s/temp_server_key_cert.p12" % self._certdb

        # Remove the p12 if it exists
        if os.path.exists(p12_bundle):
            os.remove(p12_bundle)

        # Transform to p12
        cmd = [
            'openssl', 'pkcs12', '-export', '-in', input_cert, '-inkey',
            input_key, '-out', p12_bundle, '-name', CERT_NAME, '-passout',
            'pass:'******'-aes128'
        ]
        self.log.debug("nss cmd: %s", format_cmd_list(cmd))
        try:
            check_output(cmd, stderr=subprocess.STDOUT)
        except subprocess.CalledProcessError as e:
            raise ValueError(e.output.decode('utf-8').rstrip())
        # Remove the server-cert if it exists, because else the import name fails.
        try:
            self.del_cert(CERT_NAME)
        except:
            pass
        try:
            # Import it
            cmd = [
                'pk12util',
                '-v',
                '-i',
                p12_bundle,
                '-d',
                self._certdb,
                '-k',
                '%s/%s' % (self._certdb, PWD_TXT),
                '-W',
                "",
            ]
            self.log.debug("nss cmd: %s", format_cmd_list(cmd))
            try:
                check_output(cmd, stderr=subprocess.STDOUT)
            except subprocess.CalledProcessError as e:
                raise ValueError(e.output.decode('utf-8').rstrip())
        finally:
            # Remove the p12
            if os.path.exists(p12_bundle):
                os.remove(p12_bundle)
Exemple #5
0
    def create_rsa_ca(self, months=VALID):
        """
        Create a self signed CA.
        """

        # Wait a second to avoid an NSS bug with serial ids based on time.
        time.sleep(1)
        # Create noise.
        self._generate_noise('%s/noise.txt' % self._certdb)
        # Now run the command. Can we do this with NSS native?
        cmd = [
            '/usr/bin/certutil',
            '-S',
            '-n',
            CA_NAME,
            '-s',
            ISSUER,
            '-x',
            '-g',
            '%s' % KEYBITS,
            '-t',
            'CT,,',
            '-v',
            '%s' % months,
            '--keyUsage',
            'certSigning',
            '-d',
            self._certdb,
            '-z',
            '%s/noise.txt' % self._certdb,
            '-f',
            '%s/%s' % (self._certdb, PWD_TXT),
        ]
        self.log.debug("nss cmd: %s", format_cmd_list(cmd))
        result = ensure_str(check_output(cmd, stderr=subprocess.STDOUT))
        self.log.debug("nss output: %s", result)
        # Now extract the CAcert to a well know place.
        # This allows us to point the cacert dir here and it "just works"
        cmd = [
            '/usr/bin/certutil',
            '-L',
            '-n',
            CA_NAME,
            '-d',
            self._certdb,
            '-a',
        ]
        self.log.debug("nss cmd: %s", format_cmd_list(cmd))
        certdetails = check_output(cmd, stderr=subprocess.STDOUT)
        with open('%s/ca.crt' % self._certdb, 'w') as f:
            f.write(ensure_str(certdetails))
        cmd = ['/usr/bin/c_rehash', self._certdb]
        self.log.debug("nss cmd: %s", format_cmd_list(cmd))
        check_output(cmd, stderr=subprocess.STDOUT)
        return True
Exemple #6
0
    def import_rsa_crt(self, ca=None, crt=None):
        """Given a signed certificate from a ca, import the CA and certificate
        to our database.


        """

        assert ca is not None or crt is not None, "At least one parameter should be specified (ca or crt)"

        if ca is not None:
            shutil.copyfile(ca, '%s/ca.crt' % self._certdb)
            self.openssl_rehash(self._certdb)
            cmd = [
                '/usr/bin/certutil',
                '-A',
                '-n',
                CA_NAME,
                '-t',
                "CT,,",
                '-a',
                '-i',
                '%s/ca.crt' % self._certdb,
                '-d',
                self._certdb,
                '-f',
                '%s/%s' % (self._certdb, PWD_TXT),
            ]
            self.log.debug("nss cmd: %s", format_cmd_list(cmd))
            check_output(cmd, stderr=subprocess.STDOUT)

        if crt is not None:
            cmd = [
                '/usr/bin/certutil',
                '-A',
                '-n',
                CERT_NAME,
                '-t',
                ",,",
                '-a',
                '-i',
                crt,
                '-d',
                self._certdb,
                '-f',
                '%s/%s' % (self._certdb, PWD_TXT),
            ]
            self.log.debug("nss cmd: %s", format_cmd_list(cmd))
            check_output(cmd, stderr=subprocess.STDOUT)
            cmd = [
                '/usr/bin/certutil', '-V', '-d', self._certdb, '-n', CERT_NAME,
                '-u', 'YCV'
            ]
            self.log.debug("nss cmd: %s", format_cmd_list(cmd))
            check_output(cmd, stderr=subprocess.STDOUT)
Exemple #7
0
    def add_cert(self, nickname, input_file, ca=False):
        """Add server or CA cert
        """

        # Verify input_file exists
        if not os.path.exists(input_file):
            raise ValueError(
                "The certificate file ({}) does not exist".format(input_file))

        if ca:
            trust_flags = "CT,,"
        else:
            trust_flags = ",,"

        cmd = [
            '/usr/bin/certutil',
            '-A',
            '-d',
            self._certdb,
            '-n',
            nickname,
            '-t',
            trust_flags,
            '-i',
            input_file,
            '-a',
            '-f',
            '%s/%s' % (self._certdb, PWD_TXT),
        ]
        self.log.debug("add_cert cmd: %s", format_cmd_list(cmd))
        try:
            check_output(cmd, stderr=subprocess.STDOUT)
        except subprocess.CalledProcessError as e:
            raise ValueError(e.output.decode('utf-8').rstrip())
Exemple #8
0
    def edit_cert_trust(self, nickname, trust_flags):
        """Edit trust flags
        """

        # validate trust flags
        flag_sections = trust_flags.split(',')
        if len(flag_sections) != 3:
            raise ValueError("Invalid trust flag format")

        for section in flag_sections:
            if len(section) > 6:
                raise ValueError(
                    "Invalid trust flag format, too many flags in a section")

        for c in trust_flags:
            if c not in ['p', 'P', 'c', 'C', 'T', 'u', ',']:
                raise ValueError("Invalid trust flag {}".format(c))

        # Modify certificate flags
        cmd = [
            '/usr/bin/certutil',
            '-M',
            '-d',
            self._certdb,
            '-n',
            nickname,
            '-t',
            trust_flags,
            '-f',
            '%s/%s' % (self._certdb, PWD_TXT),
        ]
        self.log.debug("edit_cert_trust cmd: %s", format_cmd_list(cmd))
        check_output(cmd, stderr=subprocess.STDOUT)
Exemple #9
0
    def openssl_rehash(self, certdir):
        """
        Compatibly run c_rehash (on old openssl versions) or openssl rehash (on
        new ones). Prefers openssl rehash, because openssl on versions where
        the rehash command doesn't exist, also doesn't correctly set the return
        code. Instead, we parse the output of `openssl version` and try to
        figure out if we have a new enough version to unconditionally run rehash.
        """
        try:
            openssl_version = check_output(['/usr/bin/openssl', 'version'
                                            ]).decode('utf-8').strip()
        except subprocess.CalledProcessError as e:
            raise ValueError(e.output.decode('utf-8').rstrip())
        rehash_available = LegacyVersion(
            openssl_version.split(' ')[1]) >= LegacyVersion('1.1.0')

        if rehash_available:
            cmd = ['/usr/bin/openssl', 'rehash', certdir]
        else:
            cmd = ['/usr/bin/c_rehash', certdir]
        self.log.debug("nss cmd: %s", format_cmd_list(cmd))
        try:
            check_output(cmd, stderr=subprocess.STDOUT)
        except subprocess.CalledProcessError as e:
            raise ValueError(e.output.decode('utf-8').rstrip())
Exemple #10
0
    def rsa_ca_needs_renew(self):
        """Check is our self signed CA is expired or
        will expire less than a minimum period of time (VALID_MIN)
        """

        cmd = [
            '/usr/bin/certutil',
            '-L',
            '-n',
            CA_NAME,
            '-d',
            self._certdb,
        ]
        self.log.debug("nss cmd: %s", format_cmd_list(cmd))
        try:
            certdetails = check_output(cmd,
                                       stderr=subprocess.STDOUT,
                                       encoding='utf-8')
        except subprocess.CalledProcessError as e:
            raise ValueError(e.output.decode('utf-8').rstrip())
        end_date_str = certdetails.split("Not After : ")[1].split("\n")[0]
        date_format = '%a %b %d %H:%M:%S %Y'
        end_date = datetime.strptime(end_date_str, date_format)

        if end_date - datetime.now() < timedelta(days=VALID_MIN):
            return True
        else:
            return False
Exemple #11
0
    def rsa_ca_sign_csr(self, csr_path, months=VALID):
        """ Given a CSR, sign it with our CA certificate (if present). This
        emits a signed certificate which can be imported with import_rsa_crt.
        """
        crt_path = 'crt'.join(csr_path.rsplit('csr', 1))
        ca_path = '%s/ca.crt' % self._certdb

        cmd = [
            '/usr/bin/certutil',
            '-C',
            '-d',
            self._certdb,
            '-f',
            '%s/%s' % (self._certdb, PWD_TXT),
            '-v',
            '%s' % months,
            '-a',
            '-i', csr_path,
            '-o', crt_path,
            '-c', CA_NAME,
        ]
        self.log.debug("nss cmd: %s", format_cmd_list(cmd))
        check_output(cmd, stderr=subprocess.STDOUT)

        return (ca_path, crt_path)
Exemple #12
0
    def reinit(self):
        """
        Re-init (create) the nss db.
        """
        # 48886: The DB that DS ships with is .... well, broken. Purge it!
        assert self.remove_db()

        try:
            os.makedirs(self._certdb)
        except FileExistsError:
            pass

        if self.dirsrv is None:
            # Write a README to let people know what this is
            readme_file = '%s/%s' % (self._certdb, 'README.txt')
            if not os.path.exists(readme_file):
                with open(readme_file, 'w') as f:
                    f.write("""
SSCA - Simple Self-Signed Certificate Authority

This is part of the 389 Directory Server project's lib389 toolkit. It
creates a simple, standalone certificate authority for testing and
development purposes. It's suitable for evaluation and testing purposes
only.
                    """)

        # In the future we may add the needed option to avoid writing the pin
        # files.
        # Write the pin.txt, and the pwdfile.txt
        prv_mask = os.umask(0o177)
        try:
            pin_file = '%s/%s' % (self._certdb, PIN_TXT)
            if not os.path.exists(pin_file):
                with open(pin_file, 'w') as f:
                    f.write('Internal (Software) Token:%s' % self.dbpassword)

            pwd_text_file = '%s/%s' % (self._certdb, PWD_TXT)
            if not os.path.exists(pwd_text_file):
                with open(pwd_text_file, 'w') as f:
                    f.write('%s' % self.dbpassword)
        finally:
            prv_mask = os.umask(prv_mask)

        # Init the db.
        # 48886; This needs to be sql format ...
        cmd = [
            '/usr/bin/certutil', '-N', '-d', self._certdb, '-f',
            '%s/%s' % (self._certdb, PWD_TXT), '-@',
            '%s/%s' % (self._certdb, PWD_TXT)
        ]
        self._generate_noise('%s/noise.txt' % self._certdb)
        self.log.debug("nss cmd: %s", format_cmd_list(cmd))
        try:
            result = ensure_str(check_output(cmd, stderr=subprocess.STDOUT))
        except subprocess.CalledProcessError as e:
            raise ValueError(e.output.decode('utf-8').rstrip())
        self.log.debug("nss output: %s", result)
        return True
Exemple #13
0
    def create_rsa_key_and_csr(self, alt_names=[], subject=None):
        """Create a new RSA key and the certificate signing request. This
        request can be submitted to a CA for signing. The returned certificate
        can be added with import_rsa_crt.
        """
        csr_path = os.path.join(self._certdb, '%s.csr' % CERT_NAME)

        if len(alt_names) == 0:
            alt_names = self.detect_alt_names(alt_names)
        if subject is None:
            subject = self.generate_cert_subject(alt_names)

        self.log.debug(f"CSR subject -> {subject}")
        self.log.debug(f"CSR alt_names -> {alt_names}")

        # Wait a second to avoid an NSS bug with serial ids based on time.
        time.sleep(1)
        # Create noise.
        self._generate_noise('%s/noise.txt' % self._certdb)

        cmd = [
            '/usr/bin/certutil',
            '-R',
            # We want a dual purposes client and server cert
            '--keyUsage',
            'digitalSignature,nonRepudiation,keyEncipherment,dataEncipherment',
            '--nsCertType',
            'sslClient,sslServer',
            '--extKeyUsage',
            'clientAuth,serverAuth',
            '-s',
            subject,
            # We MUST issue with SANs else ldap wont verify the name.
            '-8',
            ','.join(alt_names),
            '-g',
            '%s' % KEYBITS,
            '-d',
            self._certdb,
            '-z',
            '%s/noise.txt' % self._certdb,
            '-f',
            '%s/%s' % (self._certdb, PWD_TXT),
            '-a',
            '-o',
            csr_path,
        ]
        self.log.debug("nss cmd: %s", format_cmd_list(cmd))
        try:
            check_output(cmd, stderr=subprocess.STDOUT)
        except subprocess.CalledProcessError as e:
            raise ValueError(e.output.decode('utf-8').rstrip())

        return csr_path
Exemple #14
0
 def display_cert_details(self, nickname):
     cmd = [
         '/usr/bin/certutil',
         '-d',
         self._certdb,
         '-n',
         nickname,
         '-L',
         '-f',
         '%s/%s' % (self._certdb, PWD_TXT),
     ]
     self.log.debug("display_cert_details cmd: %s", format_cmd_list(cmd))
     return check_output(cmd, stderr=subprocess.STDOUT, encoding='utf-8')
Exemple #15
0
 def del_cert(self, nickname):
     """Delete this certificate
     """
     cmd = [
         '/usr/bin/certutil',
         '-D',
         '-d',
         self._certdb,
         '-n',
         nickname,
         '-f',
         '%s/%s' % (self._certdb, PWD_TXT),
     ]
     self.log.debug("del_cert cmd: %s", format_cmd_list(cmd))
     check_output(cmd, stderr=subprocess.STDOUT)
Exemple #16
0
    def create_rsa_key_and_cert(self, alt_names=[], months=VALID):
        """
        Create a key and a cert that is signed by the self signed ca

        This will use the hostname from the DS instance, and takes a list of
        extra names to take.
        """

        alt_names = self.detect_alt_names(alt_names)
        subject = self.generate_cert_subject(alt_names)

        # Wait a second to avoid an NSS bug with serial ids based on time.
        time.sleep(1)
        # Create noise.
        self._generate_noise('%s/noise.txt' % self._certdb)
        cmd = [
            '/usr/bin/certutil',
            '-S',
            '-n',
            CERT_NAME,
            '-s',
            subject,
            # We MUST issue with SANs else ldap wont verify the name.
            '-8',
            ','.join(alt_names),
            '-c',
            CA_NAME,
            '-g',
            '%s' % KEYBITS,
            '-t',
            ',,',
            '-v',
            '%s' % months,
            '-d',
            self._certdb,
            '-z',
            '%s/noise.txt' % self._certdb,
            '-f',
            '%s/%s' % (self._certdb, PWD_TXT),
        ]
        self.log.debug("nss cmd: %s", format_cmd_list(cmd))
        try:
            result = ensure_str(check_output(cmd, stderr=subprocess.STDOUT))
        except subprocess.CalledProcessError as e:
            raise ValueError(e.output.decode('utf-8').rstrip())
        self.log.debug("nss output: %s", result)
        return True
Exemple #17
0
    def display_cert_details(self, nickname):
        cmd = [
            '/usr/bin/certutil',
            '-d',
            self._certdb,
            '-n',
            nickname,
            '-L',
            '-f',
            '%s/%s' % (self._certdb, PWD_TXT),
        ]
        self.log.debug("display_cert_details cmd: %s", format_cmd_list(cmd))
        try:
            result = check_output(cmd, stderr=subprocess.STDOUT)
        except subprocess.CalledProcessError as e:
            raise ValueError(e.output.decode('utf-8').rstrip())

        return ensure_str(result)
Exemple #18
0
 def del_cert(self, nickname):
     """Delete this certificate
     """
     cmd = [
         '/usr/bin/certutil',
         '-D',
         '-d',
         self._certdb,
         '-n',
         nickname,
         '-f',
         '%s/%s' % (self._certdb, PWD_TXT),
     ]
     self.log.debug("del_cert cmd: %s", format_cmd_list(cmd))
     try:
         check_output(cmd, stderr=subprocess.STDOUT)
     except subprocess.CalledProcessError as e:
         raise ValueError(e.output.decode('utf-8').rstrip())
Exemple #19
0
    def _rsa_cert_key_exists(self, cert_tuple):
        name = cert_tuple[0]
        cmd = [
            '/usr/bin/certutil',
            '-K',
            '-d',
            self._certdb,
            '-f',
            '%s/%s' % (self._certdb, PWD_TXT),
        ]
        self.log.debug("nss cmd: %s", format_cmd_list(cmd))
        result = ensure_str(check_output(cmd, stderr=subprocess.STDOUT))

        lines = result.split('\n')[1:-1]
        key_list = []
        for line in lines:
            m = re.match('\<(?P<id>.*)\> (?P<type>\w+)\s+(?P<hash>\w+).*:(?P<name>.+)', line)
            if name == m.group('name'):
                return True
        return False
Exemple #20
0
    def create_rsa_user(self, name, months=VALID):
        """
        Create a key and cert for a user to authenticate to the directory.

        Name is the uid of the account, and will become the CN of the cert.
        """
        subject = USER_ISSUER.format(HOSTNAME=name)
        if self._rsa_user_exists(name):
            return subject

        # Wait a second to avoid an NSS bug with serial ids based on time.
        time.sleep(1)
        cmd = [
            '/usr/bin/certutil',
            '-S',
            '-n',
            '%s%s' % (USER_PREFIX, name),
            '-s',
            subject,
            '--keyUsage',
            'digitalSignature,nonRepudiation,keyEncipherment,dataEncipherment',
            '--nsCertType',
            'sslClient',
            '--extKeyUsage',
            'clientAuth',
            '-c',
            CA_NAME,
            '-g',
            '%s' % KEYBITS,
            '-t',
            ',,',
            '-v',
            '%s' % months,
            '-d',
            self._certdb,
            '-z',
            '%s/noise.txt' % self._certdb,
            '-f',
            '%s/%s' % (self._certdb, PWD_TXT),
        ]
        self.log.debug("nss cmd: %s", format_cmd_list(cmd))

        result = ensure_str(check_output(cmd, stderr=subprocess.STDOUT))
        self.log.debug("nss output: %s", result)
        # Now extract this into PEM files that we can use.
        # pk12util -o user-william.p12 -d . -k pwdfile.txt -n user-william -W ''
        cmd = [
            'pk12util',
            '-d', self._certdb,
            '-o', '%s/%s%s.p12' % (self._certdb, USER_PREFIX, name),
            '-k', '%s/%s' % (self._certdb, PWD_TXT),
            '-n', '%s%s' % (USER_PREFIX, name),
            '-W', '""'
        ]
        self.log.debug("nss cmd: %s", format_cmd_list(cmd))
        check_output(cmd, stderr=subprocess.STDOUT)
        # openssl pkcs12 -in user-william.p12 -passin pass:'' -out file.pem -nocerts -nodes
        # Extract the key
        cmd = [
            'openssl',
            'pkcs12',
            '-in', '%s/%s%s.p12' % (self._certdb, USER_PREFIX, name),
            '-passin', 'pass:""',
            '-out', '%s/%s%s.key' % (self._certdb, USER_PREFIX, name),
            '-nocerts',
            '-nodes'
        ]
        self.log.debug("nss cmd: %s", format_cmd_list(cmd))
        check_output(cmd, stderr=subprocess.STDOUT)
        # Extract the cert
        cmd = [
            'openssl',
            'pkcs12',
            '-in', '%s/%s%s.p12' % (self._certdb, USER_PREFIX, name),
            '-passin', 'pass:""',
            '-out', '%s/%s%s.crt' % (self._certdb, USER_PREFIX, name),
            '-nokeys',
            '-clcerts',
            '-nodes'
        ]
        self.log.debug("nss cmd: %s", format_cmd_list(cmd))
        check_output(cmd, stderr=subprocess.STDOUT)
        # Convert the cert for userCertificate attr
        cmd = [
            'openssl',
            'x509',
            '-inform', 'PEM',
            '-outform', 'DER',
            '-in', '%s/%s%s.crt' % (self._certdb, USER_PREFIX, name),
            '-out', '%s/%s%s.der' % (self._certdb, USER_PREFIX, name),
        ]
        self.log.debug("nss cmd: %s", format_cmd_list(cmd))
        check_output(cmd, stderr=subprocess.STDOUT)

        return subject
Exemple #21
0
    def renew_rsa_ca(self, months=VALID):
        """Renew the self signed CA."""

        csr_path = os.path.join(self._certdb, 'CA_renew.csr')
        crt_path = '%s/ca.crt' % self._certdb

        # Create noise.
        self._generate_noise('%s/noise.txt' % self._certdb)

        # Generate a CSR for a new CA cert
        cmd = [
            '/usr/bin/certutil',
            '-R',
            '-s',
            ISSUER,
            '-g',
            '%s' % KEYBITS,
            '-k',
            'NSS Certificate DB:%s' % CA_NAME,
            '-d',
            self._certdb,
            '-z',
            '%s/noise.txt' % self._certdb,
            '-f',
            '%s/%s' % (self._certdb, PWD_TXT),
            '-a',
            '-o', csr_path,
            ]
        self.log.debug("nss cmd: %s", format_cmd_list(cmd))
        check_output(cmd, stderr=subprocess.STDOUT)

        # Sign the CSR with our old CA
        cmd = [
            '/usr/bin/certutil',
            '-C',
            '-d',
            self._certdb,
            '-f',
            '%s/%s' % (self._certdb, PWD_TXT),
            '-a',
            '-i', csr_path,
            '-o', crt_path,
            '-c', CA_NAME,
            '--keyUsage',
            'certSigning',
            '-t',
            'CT,,',
            '-v',
            '%s' % months,
            ]
        self.log.debug("nss cmd: %s", format_cmd_list(cmd))
        check_output(cmd, stderr=subprocess.STDOUT)

        cmd = ['/usr/bin/c_rehash', self._certdb]
        self.log.debug("nss cmd: %s", format_cmd_list(cmd))
        check_output(cmd, stderr=subprocess.STDOUT)

        # Import the new CA to our DB instead of the old CA
        cmd = [
            '/usr/bin/certutil',
            '-A',
            '-n', CA_NAME,
            '-t', "CT,,",
            '-a',
            '-i', crt_path,
            '-d', self._certdb,
            '-f', '%s/%s' % (self._certdb, PWD_TXT),
            ]
        self.log.debug("nss cmd: %s", format_cmd_list(cmd))
        check_output(cmd, stderr=subprocess.STDOUT)

        return crt_path
Exemple #22
0
    def import_rsa_crt(self, ca=None, crt=None):
        """Given a signed certificate from a ca, import the CA and certificate
        to our database.


        """

        assert ca is not None or crt is not None, "At least one parameter should be specified (ca or crt)"

        if ca is not None:
            if not os.path.exists(ca):
                raise ValueError(
                    "The certificate file ({}) does not exist".format(ca))
            self._assert_not_chain(ca)

            shutil.copyfile(ca, '%s/ca.crt' % self._certdb)
            self.openssl_rehash(self._certdb)
            cmd = [
                '/usr/bin/certutil',
                '-A',
                '-n',
                CA_NAME,
                '-t',
                "CT,,",
                '-a',
                '-i',
                '%s/ca.crt' % self._certdb,
                '-d',
                self._certdb,
                '-f',
                '%s/%s' % (self._certdb, PWD_TXT),
            ]
            self.log.debug("nss cmd: %s", format_cmd_list(cmd))
            try:
                check_output(cmd, stderr=subprocess.STDOUT)
            except subprocess.CalledProcessError as e:
                raise ValueError(e.output.decode('utf-8').rstrip())

        if crt is not None:
            if not os.path.exists(crt):
                raise ValueError(
                    "The certificate file ({}) does not exist".format(crt))
            self._assert_not_chain(crt)
            cmd = [
                '/usr/bin/certutil',
                '-A',
                '-n',
                CERT_NAME,
                '-t',
                ",,",
                '-a',
                '-i',
                crt,
                '-d',
                self._certdb,
                '-f',
                '%s/%s' % (self._certdb, PWD_TXT),
            ]
            self.log.debug("nss cmd: %s", format_cmd_list(cmd))
            try:
                check_output(cmd, stderr=subprocess.STDOUT)
            except subprocess.CalledProcessError as e:
                raise ValueError(e.output.decode('utf-8').rstrip())
            cmd = [
                '/usr/bin/certutil', '-V', '-d', self._certdb, '-n', CERT_NAME,
                '-u', 'YCV'
            ]
            self.log.debug("nss cmd: %s", format_cmd_list(cmd))
            try:
                check_output(cmd, stderr=subprocess.STDOUT)
            except subprocess.CalledProcessError as e:
                raise ValueError(e.output.decode('utf-8').rstrip())
Exemple #23
0
    def create_users(self, subtree, min=1000, max=9999, template=None):
        """
        Creates users as user<min through max>. Password will be set to

        password<number>

        This will automatically work with the bind loadtest.
        """
        # Should we check max > min?
        # Create the template file given the data.
        if template is None:
            template = """
objectClass: top
objectclass: person
objectClass: organizationalPerson
objectClass: inetorgperson
objectClass: posixAccount
objectClass: shadowAccount
sn: user[A]
cn: user[A]
givenName: user[A]
description: description [A]
userPassword: user[A]
mail: user[A]@example.com
uidNumber: 1[A]
gidNumber: 2[A]
shadowMin: 0
shadowMax: 99999
shadowInactive: 30
shadowWarning: 7
homeDirectory: /home/user[A]
loginShell: /bin/false
"""
        with open('/tmp/ldclt_template_lib389.ldif', 'wb') as f:
            f.write(template)
        # call ldclt with the current rootdn and rootpass
        digits = len('%s' % max)

        cmd = [
            '%s/ldclt' % self.ds.get_bin_dir(),
            '-h',
            self.ds.host,
            '-p',
            '%s' % self.ds.port,
            '-D',
            self.ds.binddn,
            '-w',
            self.ds.bindpw,
            '-b',
            subtree,
            '-e',
            'add,commoncounter',
            '-e',
            "object=/tmp/ldclt_template_lib389.ldif,rdn=uid:user[A=INCRNNOLOOP(%s;%s;%s)]"
            % (min, max, digits),
        ]
        result = None
        self.log.debug("ldclt begining user create ...")
        self.log.debug(format_cmd_list(cmd))
        try:
            result = subprocess.check_output(cmd)
        # If verbose, capture / log the output.
        except subprocess.CalledProcessError as e:
            print(format_cmd_list(cmd))
            print(result)
            raise (e)
        self.log.debug(result)