def enroll_with_zone_update(conn, zone, cn=None): request = CertificateRequest(common_name=cn, origin="Python-SDK ECDSA") zc = conn.read_zone_conf(zone) request.update_from_zone_config(zc) conn.request_cert(request, zone) cert = conn.retrieve_cert(request) return cert, request.cert_guid
def test_cloud_enroll_valid_hours(self): cn = f"{random_word(10)}.venafi.example.com" request = CertificateRequest(common_name=cn) request.san_dns = ["www.client.venafi.example.com", "ww1.client.venafi.example.com"] custom_fields = [ CustomField(name="custom", value="pythonTest"), CustomField(name="cfList", value="item2"), CustomField(name="cfListMulti", value="tier1"), CustomField(name="cfListMulti", value="tier4") ] request.custom_fields = custom_fields request.validity_hours = 144 expected_date = datetime.utcnow() + timedelta(hours=request.validity_hours) self.cloud_conn.request_cert(request, self.cloud_zone) cert = self.cloud_conn.retrieve_cert(request) cert = x509.load_pem_x509_certificate(cert.cert.encode(), default_backend()) assert isinstance(cert, x509.Certificate) expiration_date = cert.not_valid_after # Due to some roundings and delays in operations on the server side, the certificate expiration date # is not exactly the same as the one used in the request. A gap is allowed in this scenario to compensate # this delays and roundings. delta = timedelta(seconds=60) date_format = "%Y-%m-%d %H:%M:%S" self.assertAlmostEqual(expected_date, expiration_date, delta=delta, msg=f"Delta between expected and expiration date is too big." f"\nExpected: {expected_date.strftime(date_format)}" f"\nGot: {expiration_date.strftime(date_format)}\n" f"Expected_delta: {delta.total_seconds()} seconds.")
def test_cloud_enroll_service_generated_csr(self): cn = f"{random_word(10)}.venafi.example.com" password = '******' request = CertificateRequest( common_name=cn, key_password=password, country='US' ) request.san_dns = ["www.client.venafi.example.com", "ww1.client.venafi.example.com"] request.csr_origin = CSR_ORIGIN_SERVICE self.cloud_conn.request_cert(request, self.cloud_zone) cert_object = self.cloud_conn.retrieve_cert(request) cert = x509.load_pem_x509_certificate(cert_object.cert.encode(), default_backend()) assert isinstance(cert, x509.Certificate) t1 = cert.subject.get_attributes_for_oid(NameOID.COMMON_NAME) t2 = [ x509.NameAttribute( NameOID.COMMON_NAME, cn or RANDOM_DOMAIN ) ] assert t1 == t2 output = cert_object.as_pkcs12('FooBarPass123') log.info(f"PKCS12 created successfully for certificate with CN: {cn}")
def enroll(conn, ZONE, cn): print("Tring to ping url", URL) status = conn.ping() print("Server online:", status) if not status: print('Server offline') exit(1) if isinstance(conn, (FakeConnection or TPPConnection)): request = CertificateRequest( common_name=cn, dns_names=[ "www.client.venafi.example.com", "ww1.client.venafi.example.com" ], email_addresses="[email protected], [email protected]", ip_addresses=["127.0.0.1", "192.168.1.1"], chain_option="last") else: request = CertificateRequest(common_name=cn, chain_option="last") conn.request_cert(request, ZONE) while True: cert_pem = conn.retrieve_cert(request) if cert_pem: break else: time.sleep(5) # print("Certificate is:\n %s" % cert_pem) # print("Private key is:\n %s:" % request.private_key_pem) # and save into file f = open("./cert.pem", "w") f.write(cert_pem) f = open("./cert.key", "w") f.write(request.private_key_pem) f.close() cert = x509.load_pem_x509_certificate(cert_pem.encode(), default_backend()) assert isinstance(cert, x509.Certificate) assert cert.subject.get_attributes_for_oid( NameOID.COMMON_NAME) == [x509.NameAttribute(NameOID.COMMON_NAME, cn)] private_key = serialization.load_pem_private_key( request.private_key_pem.encode(), password=None, backend=default_backend()) private_key_public_key_pem = private_key.public_key().public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo) public_key_pem = cert.public_key().public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo) print(private_key_public_key_pem.decode()) print(public_key_pem.decode()) assert private_key_public_key_pem == public_key_pem return request.id, request.private_key_pem, cert.serial_number
def test_request_with_csr(self): req = CertificateRequest(common_name="test.example.com", csr=EXAMPLE_CSR) self.assertEqual(req.common_name, "test.example.com") with self.assertRaises(Exception): CertificateRequest(common_name="test2.example.com", csr=EXAMPLE_CSR) req = CertificateRequest(csr=EXAMPLE_CSR) self.assertEqual(req.common_name, None)
def main(): # Get credentials from environment variables url = environ.get( 'VAAS_URL' ) # Optional, only use when connecting to a specific VaaS server api_key = environ.get('VAAS_APIKEY') zone = environ.get('VAAS_ZONE') # Connection will be chosen automatically based on which arguments are passed. # If api_key is passed, Venafi Cloud connection will be used. # url attribute is no required when connecting to production VaaS platform conn = venafi_connection(url=url, api_key=api_key) # Build a Certificate request request = CertificateRequest( common_name=f"{random_word(10)}.venafi.example.com") # Set the request to use a service generated CSR request.csr_origin = CSR_ORIGIN_SERVICE # A password should be defined for the private key to be generated. request.key_password = '******' # Include some Subject Alternative Names request.san_dns = [ "www.dns.venafi.example.com", "ww1.dns.venafi.example.com" ] # Additional CSR attributes can be included: request.organization = "Venafi, Inc." request.organizational_unit = ["Product Management"] request.locality = "Salt Lake City" request.province = "Utah" # This is the same as state request.country = "US" # Specify ordering certificates in chain. Root can be CHAIN_OPTION_FIRST ("first") # or CHAIN_OPTION_LAST ("last"). By default it is CHAIN_OPTION_LAST. # request.chain_option = CHAIN_OPTION_FIRST # # 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") # ] # # Request the certificate. conn.request_cert(request, zone) # Wait for the certificate to be retrieved. # This operation may take some time to return, as it waits until the certificate is ISSUED or it timeout. # Timeout is 180s by default. Can be changed using: # request.timeout = 300 cert = conn.retrieve_cert(request) # Print the certificate print(cert.full_chain) # Save it into a file f = open("./cert.pem", "w") f.write(cert.full_chain) f.close()
def enroll_with_zone_update(conn, zone, cn=None): request = CertificateRequest(common_name=cn, origin="Python-SDK ECDSA") zc = conn.read_zone_conf(zone) request.update_from_zone_config(zc) conn.request_cert(request, zone) while True: cert = conn.retrieve_cert(request) if cert: break else: time.sleep(5) return cert
def test_return_pem_private_key(self): req = CertificateRequest(common_name="test.example.com", key_password="******") req.build_csr() self.assertIn("ENCRYPTED", req.private_key_pem) req = CertificateRequest(common_name="test.example.com") req.build_csr() self.assertNotIn("ENCRYPTED", req.private_key_pem)
def renew(conn, cert_id, pkey, sn, cn): print("Trying to renew certificate") new_request = CertificateRequest(cert_id=cert_id) # TODO change back to True when support for renew with csr use is deployed. conn.renew_cert(new_request, reuse_key=False) new_cert = conn.retrieve_cert(new_request) f = open("./renewed_cert.pem", "w") f.write(new_cert.full_chain) f.close() cert = x509.load_pem_x509_certificate(new_cert.cert.encode(), default_backend()) assert isinstance(cert, x509.Certificate) assert cert.subject.get_attributes_for_oid( NameOID.COMMON_NAME) == [x509.NameAttribute(NameOID.COMMON_NAME, cn)] assert cert.serial_number != sn private_key = serialization.load_pem_private_key(pkey.encode(), password=None, backend=default_backend()) private_key_public_key_pem = private_key.public_key().public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo) public_key_pem = cert.public_key().public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo) # TODO this assertion only works when the reuse key is set to true in the renew method # assert private_key_public_key_pem == public_key_pem return cert
def renew(conn, cert_id, pkey, sn, cn): print("Trying to renew certificate") new_request = CertificateRequest(id=cert_id, chain_option="last") conn.renew_cert(new_request) time.sleep(5) while True: new_cert_pem = conn.retrieve_cert(new_request) if new_cert_pem: break else: time.sleep(5) f = open("./renewed_cert.pem", "w") f.write(new_cert_pem) f.close() cert = x509.load_pem_x509_certificate(new_cert_pem.encode(), default_backend()) assert isinstance(cert, x509.Certificate) assert cert.subject.get_attributes_for_oid( NameOID.COMMON_NAME) == [x509.NameAttribute(NameOID.COMMON_NAME, cn)] assert cert.serial_number != sn private_key = serialization.load_pem_private_key(pkey.encode(), password=None, backend=default_backend()) private_key_public_key_pem = private_key.public_key().public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo) public_key_pem = cert.public_key().public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo) assert private_key_public_key_pem == public_key_pem
def main(): token = environ.get('TOKEN') user = environ.get('TPPUSER') password = environ.get('TPPPASSWORD') url = environ.get('TPPURL') zone = environ.get("ZONE") conn = Connection(url=url, token=token, user=user, password=password) print("Tring to ping url %s" % conn._base_url) status = conn.ping() print("Server online:", status) if not status: print('Server offline - exit') exit(1) request = CertificateRequest(common_name=randomword(10) + ".venafi.example.com") if not isinstance(conn, CloudConnection): # cloud connection doesn`t support dns, email and ip in CSR request.dns_names = [ "www.client.venafi.example.com", "ww1.client.venafi.example.com" ] request.email_addresses = "[email protected], [email protected]" request.ip_addresses = ["127.0.0.1", "192.168.1.1"] request.chain_option = "last" # make certificate request conn.request_cert(request, zone) # and wait for signing while True: cert = conn.retrieve_cert(request) if cert: break else: time.sleep(5) # after that print cert and key print(cert, request.private_key_pem, sep="\n") # and save into file f = open("/tmp/cert.pem", "w") f.write(cert) 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(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) fn = open("/tmp/new_cert.pem", "w") fn.write(new_cert)
def simple_enroll(conn, zone): req = CertificateRequest(common_name=randomword(12) + ".venafi.example.com") conn.request_cert(req, zone) t = time.time() while time.time() - t < 300: cert = conn.retrieve_cert(req) if cert: break else: time.sleep(5) return req, cert
def renew_without_key_reuse(unittest_object, conn, zone): cn = f"{random_word(10)}.venafi.example.com" cert_id, pkey, _, public_key, _ = enroll(conn, zone, cn) time.sleep(5) req = CertificateRequest(cert_id=cert_id) conn.renew_cert(req, reuse_key=False) cert = conn.retrieve_cert(req) cert = x509.load_pem_x509_certificate(cert.cert.encode(), default_backend()) public_key_new = cert.public_key().public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo).decode() unittest_object.assertNotEqual(public_key_new, public_key)
def test_update_request_with_zone_config(self): r = CertificateRequest() z = ZoneConfig(organization=CertField("Venafi"), organizational_unit=CertField(""), country=CertField(""), province=CertField(""), locality=CertField(""), policy=None, key_type=None) r.update_from_zone_config(z) self.assertEqual(r.organization, "Venafi") r = CertificateRequest(organization="Test") r.update_from_zone_config(z) self.assertEqual(r.organization, "Test") z = ZoneConfig(organization=CertField("Venafi", locked=True), organizational_unit=CertField(""), country=CertField(""), province=CertField(""), locality=CertField(""), policy=None, key_type=None) r.update_from_zone_config(z) self.assertEqual(r.organization, "Venafi")
def renew_by_thumbprint(conn, prev_cert): print("Trying to renew by thumbprint") thumbprint = binascii.hexlify(prev_cert.fingerprint( hashes.SHA1())).decode() new_request = CertificateRequest(thumbprint=thumbprint) # TODO change back to True when support for renew with csr use is deployed. conn.renew_cert(new_request, reuse_key=False) new_cert = conn.retrieve_cert(new_request) cert = x509.load_pem_x509_certificate(new_cert.cert.encode(), default_backend()) assert isinstance(cert, x509.Certificate) print(cert.subject.get_attributes_for_oid(NameOID.COMMON_NAME)) print(prev_cert.subject.get_attributes_for_oid(NameOID.COMMON_NAME)) assert cert.subject.get_attributes_for_oid( NameOID.COMMON_NAME) == prev_cert.subject.get_attributes_for_oid( NameOID.COMMON_NAME)
def renew_by_thumbprint(conn, prev_cert): print("Trying to renew by thumbprint") thumbprint = binascii.hexlify(prev_cert.fingerprint( hashes.SHA1())).decode() new_request = CertificateRequest(thumbprint=thumbprint) conn.renew_cert(new_request) while True: new_cert = conn.retrieve_cert(new_request) if new_cert: break else: time.sleep(5) cert = x509.load_pem_x509_certificate(new_cert.cert.encode(), default_backend()) assert isinstance(cert, x509.Certificate) print(cert.subject.get_attributes_for_oid(NameOID.COMMON_NAME)) print(prev_cert.subject.get_attributes_for_oid(NameOID.COMMON_NAME)) assert cert.subject.get_attributes_for_oid( NameOID.COMMON_NAME) == prev_cert.subject.get_attributes_for_oid( NameOID.COMMON_NAME)
def _check_private_key_correct(self): if not self.privatekey_filename: return None if not os.path.exists(self.privatekey_filename): return False private_key = to_text(open(self.privatekey_filename, "rb").read()) r = CertificateRequest(private_key=private_key, key_password=self.privatekey_passphrase) key_type = {"RSA": "rsa", "ECDSA": "ec", "EC": "ec"}. \ get(self.privatekey_type) if key_type and key_type != r.key_type: return False if key_type == "rsa" and self.privatekey_size: if self.privatekey_size != r.key_length: return False if key_type == "ec" and self.privatekey_curve: if self.privatekey_curve != r.key_curve: return False return True
def main(): # Get credentials from environment variables url = environ.get('TPP_TOKEN_URL') user = environ.get('TPP_USER') password = environ.get('TPP_PASSWORD') zone = environ.get('TPP_ZONE') server_trust_bundle = environ.get('TPP_TRUST_BUNDLE') # 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. # If your TPP server certificate signed with your own CA, or available only via proxy, you can specify # a trust bundle using http_request_kwargs. conn = venafi_connection( url=url, user=user, password=password, http_request_kwargs={'verify': server_trust_bundle}) # Build a Certificate request request = CertificateRequest( common_name=f"{random_word(10)}.venafi.example.com") # Set the request to use a service generated CSR request.csr_origin = CSR_ORIGIN_SERVICE # Include some Subject Alternative Names request.san_dns = [ "www.dns.venafi.example.com", "ww1.dns.venafi.example.com" ] request.email_addresses = [ "*****@*****.**", "*****@*****.**" ] request.ip_addresses = ["127.0.0.1", "192.168.1.1"] request.uniform_resource_identifiers = [ "http://wgtest.uri.com", "https://ragnartest.uri.com" ] request.user_principal_names = [ "*****@*****.**", "*****@*****.**" ] # Specify whether or not to return the private key. It is False by default. # A password should be defined for the private key if include_private_key is True. request.include_private_key = True request.key_password = '******' # Specify ordering certificates in chain. Root can be CHAIN_OPTION_FIRST ("first") # or CHAIN_OPTION_LAST ("last"). By default it is CHAIN_OPTION_LAST. # You can also specify CHAIN_OPTION_IGNORE ("ignore") to ignore chain (supported only for TPP). # request.chain_option = CHAIN_OPTION_FIRST # 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") # ] # # Update certificate request from zone. zone_config = conn.read_zone_conf(zone) request.update_from_zone_config(zone_config) # Request the certificate. conn.request_cert(request, zone) # Wait for the certificate to be retrieved. # This operation may take some time to return, as it waits until the certificate is ISSUED or it timeout. # Timeout is 180s by default. Can be changed using: # request.timeout = 300 cert = conn.retrieve_cert(request) # Print the certificate print(cert.full_chain) # Save it into a file f = open("./cert.pem", "w") f.write(cert.full_chain) f.close() print("Trying to renew certificate") new_request = CertificateRequest(cert_id=request.id) # The renewal request should use a service generated CSR as well # This may not be necessary and depends entirely on the settings of your Policy/Zone new_request.csr_origin = CSR_ORIGIN_SERVICE conn.renew_cert(new_request) new_cert = conn.retrieve_cert(new_request) print(new_cert.cert) fn = open("./new_cert.pem", "w") fn.write(new_cert.cert) fn.close()
def enroll(conn, zone, cn=None, private_key=None, public_key=None, password=None, csr=None, custom_fields=None, service_generated_csr=False): request = CertificateRequest(common_name=cn, private_key=private_key, key_password=password) if custom_fields: request.custom_fields = custom_fields request.san_dns = [ "www.client.venafi.example.com", "ww1.client.venafi.example.com" ] if isinstance(conn, (FakeConnection, TPPConnection, TPPTokenConnection)): request.email_addresses = [ "*****@*****.**", "*****@*****.**" ] request.ip_addresses = ["127.0.0.1", "192.168.1.1"] request.user_principal_names = [ "*****@*****.**", "*****@*****.**" ] request.uniform_resource_identifiers = [ "https://www.venafi.com", "https://venafi.cloud" ] if csr: request.csr = csr elif service_generated_csr: request.csr_origin = CSR_ORIGIN_SERVICE request.include_private_key = True conn.request_cert(request, zone) cert = conn.retrieve_cert(request) with open("./cert.pem", "w") as f: f.write(cert.full_chain) with open("./cert.key", "w") as f2: if request.include_private_key: assert cert.key is not None f2.write(cert.key) else: f2.write(request.private_key_pem) cert = x509.load_pem_x509_certificate(cert.cert.encode(), default_backend()) assert isinstance(cert, x509.Certificate) t1 = cert.subject.get_attributes_for_oid(NameOID.COMMON_NAME) t2 = [x509.NameAttribute(NameOID.COMMON_NAME, cn or RANDOM_DOMAIN)] assert t1 == t2 cert_public_key_pem = cert.public_key().public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo).decode() if isinstance(public_key, string_types): public_key = public_key.encode() if public_key: source_public_key_pem = serialization.load_pem_public_key( public_key, default_backend()).public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo).decode( ) else: source_public_key_pem = request.public_key_pem if not service_generated_csr else None print(source_public_key_pem) print(cert_public_key_pem) if not service_generated_csr: assert source_public_key_pem == cert_public_key_pem private_key_pem = request.private_key_pem if not service_generated_csr else None return request.id, private_key_pem, cert, cert_public_key_pem, request.cert_guid
def simple_enroll(conn, zone): req = CertificateRequest( common_name=f"{random_word(12)}.venafi.example.com") conn.request_cert(req, zone) cert = conn.retrieve_cert(req) return req, cert
def test_generate_ecdsa_key(self): req = CertificateRequest(common_name="test.exampe.com", key_type=KeyType("ecdsa", "p384")) req._gen_key() self.assertEqual(req.public_key.curve.name, "secp384r1")
def test_cloud_retrieve_non_issued(self): req = CertificateRequest(cert_id="4d806fbc-06bb-4a2a-b224-9e58a7e996f5") with self.assertRaises(Exception): self.cloud_conn.retrieve_cert(req)
def test_return_pem_cert(self): conn = FakeConnection() req = CertificateRequest(common_name="test.example.com") conn.request_cert(req, "") cert = conn.retrieve_cert(req) self.assertIn("BEGIN CERTIFICATE", cert.cert)
def test_return_pem_csr(self): req = CertificateRequest(common_name="test.example.com") req.build_csr() self.assertIn("CERTIFICATE REQUEST", req.csr)
def test_generate_rsa_key(self): req = CertificateRequest(common_name="test.example.com", key_type=KeyType("rsa", 2048)) req._gen_key() self.assertEqual(req.public_key.key_size, 2048)
def test_pass_invalid_key_type_to_request(self): with self.assertRaises(Exception): req = CertificateRequest(common_name="test.example.com", key_type="rsa")
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: %s." "Must be RSA or ECDSA" % 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)
def test_generate_ecdsa_csr(self): req = CertificateRequest(common_name="test.exampe.com", key_type=KeyType("ecdsa", "p384")) req.build_csr() req = x509.load_pem_x509_csr(req.csr.encode(), default_backend()) self.assertEqual(req.public_key().curve.name, "secp384r1")
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()
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()