Beispiel #1
0
    def enroll(self):
        request = CertificateRequest(common_name=self.common_name,
                                     key_password=self.privatekey_passphrase,
                                     origin="Red Hat Ansible")
        zone_config = self.conn.read_zone_conf(self.zone)
        request.update_from_zone_config(zone_config)

        use_existed_key = False
        if self._check_private_key_correct() and not self.privatekey_reuse:
            private_key = to_text(open(self.privatekey_filename, "rb").read())
            request.private_key = private_key
            use_existed_key = True
        elif self.privatekey_type:
            key_type = {"RSA": "rsa", "ECDSA": "ec", "EC": "ec"}. \
                get(self.privatekey_type)
            if not key_type:
                self.module.fail_json(msg=("Failed to determine key type: %s."
                                           "Must be RSA or ECDSA" %
                                           self.privatekey_type))
            if key_type == "rsa":
                request.key_type = KeyType(KeyType.RSA, self.privatekey_size)
            elif key_type == "ecdsa" or "ec":
                request.key_type = KeyType(KeyType.ECDSA,
                                           self.privatekey_curve)
            else:
                self.module.fail_json(msg=("Failed to determine key type: %s."
                                           "Must be RSA or ECDSA" %
                                           self.privatekey_type))

        request.ip_addresses = self.ip_addresses
        request.san_dns = self.san_dns
        request.email_addresses = self.email_addresses

        request.chain_option = self.module.params['chain_option']
        try:
            csr = open(self.csr_path, "rb").read()
            request.csr = csr
        except Exception as e:
            self.module.log(msg=str(e))
            pass

        self.conn.request_cert(request, self.zone)
        print(request.csr)
        while True:
            cert = self.conn.retrieve_cert(request)  # vcert.Certificate
            if cert:
                break
            else:
                time.sleep(5)
        if self.chain_filename:
            self._atomic_write(self.chain_filename, "\n".join(cert.chain))
            self._atomic_write(self.certificate_filename, cert.cert)
        else:
            self._atomic_write(self.certificate_filename, cert.full_chain)
        if not use_existed_key:
            self._atomic_write(self.privatekey_filename,
                               request.private_key_pem)
Beispiel #2
0
    def enroll(self):
        request = CertificateRequest(
            common_name=self.common_name,
            key_password=self.privatekey_passphrase,
        )
        use_existed_key = False
        if self._check_private_key_correct():  # May be None
            private_key = to_text(open(self.privatekey_filename, "rb").read())
            request.private_key = private_key
            use_existed_key = True
        elif self.privatekey_type:
            key_type = {
                "RSA": "rsa",
                "ECDSA": "ec",
                "EC": "ec"
            }.get(self.privatekey_type)
            if not key_type:
                self.module.fail_json(
                    msg="Failed to determine key type: {0}. Must be RSA or ECDSA"
                    .format(self.privatekey_type))
            request.key_type = key_type
            request.key_curve = self.privatekey_curve
            request.key_length = self.privatekey_size

        request.ip_addresses = self.ip_addresses
        request.san_dns = self.san_dns
        request.email_addresses = self.email_addresses

        request.chain_option = self.module.params['chain_option']
        try:
            csr = open(self.csr_path, "rb").read()
            request.csr = csr
        except Exception as e:
            self.module.log(msg=str(e))
            pass

        self.conn.request_cert(request, self.zone)
        print(request.csr)
        while True:
            cert = self.conn.retrieve_cert(request)  # vcert.Certificate
            if cert:
                break
            else:
                time.sleep(5)
        if self.chain_filename:
            self._atomic_write(self.chain_filename, "\n".join(cert.chain))
            self._atomic_write(self.certificate_filename, cert.cert)
        else:
            self._atomic_write(self.certificate_filename, cert.full_chain)
        if not use_existed_key:
            self._atomic_write(self.privatekey_filename,
                               request.private_key_pem)
Beispiel #3
0
def main():
    # Get credentials from environment variables
    token = environ.get('CLOUD_APIKEY')
    user = environ.get('TPP_USER')
    password = environ.get('TPP_PASSWORD')
    url = environ.get('TPP_URL')
    zone = environ.get("ZONE")
    fake = environ.get('FAKE')

    if fake:
        # If fake is true, test connection will be used.
        conn = Connection(fake=True)
    else:
        # Connection will be chosen automatically based on which arguments are passed.
        # If token is passed Venafi Cloud connection will be used.
        # If user, password, and URL Venafi Platform (TPP) will be used.
        conn = Connection(url=url,
                          token=token,
                          user=user,
                          password=password,
                          http_request_kwargs={"verify": False})
        # If your TPP server certificate signed with your own CA, or available only via proxy, you can specify
        # a trust bundle using requests vars:
        #conn = Connection(url=url, token=token, user=user, password=password,
        #                  http_request_kwargs={"verify": "/path-to/bundle.pem"})

    request = CertificateRequest(common_name=randomword(10) +
                                 ".venafi.example.com")
    request.san_dns = [
        "www.client.venafi.example.com", "ww1.client.venafi.example.com"
    ]
    if not isinstance(conn, CloudConnection):
        # Venafi Cloud doesn't support email or IP SANs in CSR
        request.email_addresses = [
            "*****@*****.**", "*****@*****.**"
        ]
        request.ip_addresses = ["127.0.0.1", "192.168.1.1"]
        # Specify ordering certificates in chain. Root can be "first" or "last". By default it last. You also can
        # specify "ignore" to ignore chain (supported only for Platform).

    # configure key type, RSA example
    # request.key_type = KeyType(KeyType.RSA, 4096)
    # or set it to ECDSA
    request.key_type = KeyType(KeyType.ECDSA, "p521")
    # Update certificate request from zone
    zone_config = conn.read_zone_conf(zone)
    request.update_from_zone_config(zone_config)
    conn.request_cert(request, zone)

    # and wait for signing
    t = time.time() + 300
    while time.time() < t:
        cert = conn.retrieve_cert(request)
        if cert:
            break
        else:
            time.sleep(5)

    # after that print cert and key
    print(cert.full_chain, request.private_key_pem, sep="\n")
    # and save into file
    f = open("/tmp/cert.pem", "w")
    f.write(cert.full_chain)
    f = open("/tmp/cert.key", "w")
    f.write(request.private_key_pem)
    f.close()

    if not isinstance(conn, FakeConnection):
        # fake connection doesn`t support certificate renewing
        print("Trying to renew certificate")
        new_request = CertificateRequest(cert_id=request.id, )
        conn.renew_cert(new_request)
        while True:
            new_cert = conn.retrieve_cert(new_request)
            if new_cert:
                break
            else:
                time.sleep(5)
        print(new_cert.cert, new_request.private_key_pem, sep="\n")
        fn = open("/tmp/new_cert.pem", "w")
        fn.write(new_cert.cert)
        fn = open("/tmp/new_cert.key", "w")
        fn.write(new_request.private_key_pem)
        fn.close()
    if isinstance(conn, TPPConnection):
        revocation_req = RevocationRequest(req_id=request.id,
                                           comments="Just for test")
        print("Revoke", conn.revoke_cert(revocation_req))

    print("Trying to sign CSR")
    csr_pem = open("example-csr.pem", "rb").read()
    csr_request = CertificateRequest(csr=csr_pem.decode())
    # zone_config = conn.read_zone_conf(zone)
    # request.update_from_zone_config(zone_config)
    conn.request_cert(csr_request, zone)

    # and wait for signing
    while True:
        cert = conn.retrieve_cert(csr_request)
        if cert:
            break
        else:
            time.sleep(5)

    # after that print cert and key
    print(cert.full_chain)
    # and save into file
    f = open("/tmp/signed-cert.pem", "w")
    f.write(cert.full_chain)
    f.close()
Beispiel #4
0
def main():
    # Get credentials from environment variables
    user = environ.get('TPP_USER')
    password = environ.get('TPP_PASSWORD')
    url = environ.get('TPP_TOKEN_URL')
    zone = environ.get("ZONE")
    fake = environ.get('FAKE')

    if fake:
        # If fake is true, test connection will be used.
        conn = Connection(fake=True)
    else:
        # If user and password are passed, you can get a new token from them.
        # If access_token and refresh_token are passed, there is no need for the username and password.
        # If only access_token is passed, the Connection will fail when token expires, as there is no way to refresh it.
        conn = venafi_connection(url=url, user=user, password=password, http_request_kwargs={"verify": False})
        # If your TPP server certificate signed with your own CA, or available only via proxy, you can specify
        # a trust bundle using requests vars:
        # conn = token_connection(url=url, user=user, password=password,
        #                         http_request_kwargs={"verify": "/path-to/bundle.pem"})

    request = CertificateRequest(common_name=random_word(10) + ".venafi.example.com")
    request.san_dns = [u"www.client.venafi.example.com", u"ww1.client.venafi.example.com"]
    request.email_addresses = [u"*****@*****.**", u"*****@*****.**"]
    request.ip_addresses = [u"127.0.0.1", u"192.168.1.1"]
    request.uniform_resource_identifiers = [u"http://wgtest.com",u"https://ragnartest.com"]
    request.user_principal_names = [u"*****@*****.**", u"*****@*****.**"] 
    # Specify ordering certificates in chain. Root can be "first" or "last". By default its last. You also can
    # specify "ignore" to ignore chain (supported only for Platform).
    # To set Custom Fields for the certificate, specify an array of CustomField objects as name-value pairs
    #request.custom_fields = [
    #    CustomField(name="Cost Center", value="ABC123"),
    #    CustomField(name="Environment", value="Production"),
    #    CustomField(name="Environment", value="Staging")
    #]

    # configure key type, RSA example
    request.key_type = KeyType(KeyType.RSA, 2048)
    # or set it to ECDSA
    #request.key_type = KeyType(KeyType.ECDSA, "p521")
    # Update certificate request from zone
    zone_config = conn.read_zone_conf(zone)
    request.update_from_zone_config(zone_config)
    conn.request_cert(request, zone)

    # and wait for signing
    t = time.time() + 300
    while time.time() < t:
        cert = conn.retrieve_cert(request)
        if cert:
            break
        else:
            time.sleep(5)

    # after that print cert and key
    print(cert.full_chain, request.private_key_pem, sep="\n")
    # and save into file
    f = open("/tmp/cert.pem", "w")
    f.write(cert.full_chain)
    f = open("/tmp/cert.key", "w")
    f.write(request.private_key_pem)
    f.close()

    if not isinstance(conn, FakeConnection):
        # fake connection doesn`t support certificate renewing
        print("Trying to renew certificate")
        new_request = CertificateRequest(
            cert_id=request.id,
        )
        conn.renew_cert(new_request)
        while True:
            new_cert = conn.retrieve_cert(new_request)
            if new_cert:
                break
            else:
                time.sleep(5)
        print(new_cert.cert, new_request.private_key_pem, sep="\n")
        fn = open("/tmp/new_cert.pem", "w")
        fn.write(new_cert.cert)
        fn = open("/tmp/new_cert.key", "w")
        fn.write(new_request.private_key_pem)
        fn.close()
    if isinstance(conn, (TPPConnection or TPPTokenConnection)):
        revocation_req = RevocationRequest(req_id=request.id, comments="Just for test")
        print("Revoke", conn.revoke_cert(revocation_req))

    print("Trying to sign CSR")
    csr_pem = open("example-csr.pem", "rb").read()
    csr_request = CertificateRequest(csr=csr_pem.decode())
    # zone_config = conn.read_zone_conf(zone)
    # request.update_from_zone_config(zone_config)
    conn.request_cert(csr_request, zone)

    # and wait for signing
    while True:
        cert = conn.retrieve_cert(csr_request)
        if cert:
            break
        else:
            time.sleep(5)

    # after that print cert and key
    print(cert.full_chain)
    # and save into file
    f = open("/tmp/signed-cert.pem", "w")
    f.write(cert.full_chain)
    f.close()
Beispiel #5
0
    def enroll(self):
        LOG.info("Running enroll")
        common_name = self.properties[self.CN]
        sans = self.properties[self.SANs]
        privatekey_passphrase = self.properties[self.KEY_PASSWORD]
        privatekey_type = self.properties[self.KEY_TYPE]
        curve = self.properties[self.KEY_CURVE]
        key_size = self.properties[self.KEY_LENGTH]
        zone = self.properties[self.ZONE]

        LOG.info("Reading zone config from %s", zone)
        zone_config = self.conn.read_zone_conf(zone)
        request = CertificateRequest(
            common_name=common_name,
            origin="OpenStack"
        )
        request.update_from_zone_config(zone_config)
        ip_addresses = []
        email_addresses = []
        san_dns = []
        if len(sans) > 0:
            LOG.info("Configuring SANs from list %s", sans)
            for n in sans:
                if n.lower().startswith(("ip:", "ip address:")):
                    ip = n.split(":", 1)[1]
                    LOG.info("Adding ip %s to ip_addresses", ip)
                    ip_addresses.append(ip)
                elif n.lower().startswith("dns:"):
                    ns = n.split(":", 1)[1]
                    LOG.info("Adding domain name %s to san_dns", ns)
                    san_dns.append(ns)
                elif n.lower().startswith("email:"):
                    mail = n.split(":", 1)[1]
                    LOG.info("Adding mail %s to email_addresses", mail)
                    email_addresses.append(mail)
                else:
                    raise Exception("Failed to determine extension type: %s" % n)
            request.ip_addresses = ip_addresses
            request.san_dns = san_dns
            request.email_addresses = email_addresses
            LOG.info("Request is %s, %s, %s", request.ip_addresses, request.san_dns, request.email_addresses)

        if privatekey_passphrase is not None:
            request.key_password = privatekey_passphrase

        if privatekey_type:
            request.key_type = KeyType(privatekey_type, key_size or curve)

        self.conn.request_cert(request, zone)
        t = time.time()
        while True:
            LOG.info("Trying to retrieve certificate")
            cert = self.conn.retrieve_cert(request)  # type: vcert.Certificate
            if cert or time.time() > t + 600:
                break
            else:
                time.sleep(5)
        LOG.info("Got certificate: %s", cert.cert)
        LOG.info("Got chain: %s", cert.chain)
        return {self.CHAIN_ATTR: cert.chain, self.CERTIFICATE_ATTR: cert.cert,
                self.PRIVATE_KEY_ATTR: request.private_key_pem, self.CSR_ATTR: request.csr}