def main(): # Get credentials from environment variables url = environ.get('TPP_URL') user = environ.get('TPP_USER') password = environ.get('TPP_PASSWORD') connector = venafi_connection(url=url, user=user, password=password, http_request_kwargs={'verify': False}) # If your TPP server certificate is signed with your own CA, or available only via proxy, # you can specify a trust bundle using requests vars: # connector = venafi_connection(url=url, api_key=api_key, access_token=access_token, # http_request_kwargs={"verify": "/path-to/bundle.pem"}) # Create an Authentication object to request a token with the proper scope to manage SSH certificates auth = Authentication(user=user, password=password, scope=SCOPE_SSH) # Additionally, you may change the default client id for a custom one # Make sure this id has been registered on the TPP instance beforehand # Also, the user (TTP_USER) should be allowed to use this application # And the application should have the ssh permissions enabled auth.client_id = 'vcert-ssh-demo' # Request access token # After the request is successful, subsequent api calls will use the same token connector.get_access_token(auth) # Generate an SSH key pair for use. The passphrase can be omitted if encryption is not required # IMPORTANT: Save the private key on a secure location and do not share it with anyone. # There is no way to decrypt the certificates generated with the public key # without the corresponding private key ssh_kp = SSHKeyPair() ssh_kp.generate(key_size=4096, passphrase="foobar") # The path to the SSH CA in the TPP instance # This is a placeholder. Make sure an SSH CA already exists on your TPP instance cadn = "\\VED\\Certificate Authority\\SSH\\Templates\\my-ca" # The id of the SSH certificate key_id = f"vcert-python-{random_word(12)}" # Create the request object request = SSHCertRequest(cadn=cadn, key_id=key_id) # Add any additional info for the certificate, like: request.validity_period = "4h" request.source_addresses = ["test.com"] request.extensions = {'permit-pty': ""} # Include the locally-generated public key. If not set, the server will generate one for the certificate request.set_public_key_data(ssh_kp.public_key()) # Request the certificate from TPP instance success = connector.request_ssh_cert(request) if success: # Retrieve the certificate from TPP instance response = connector.retrieve_ssh_cert(request) # Save the certificate to a file # The private and public key are optional values. write_ssh_files("/path/to/ssh/cert/folder", response.certificate_details.key_id, response.certificate_data, ssh_kp.private_key(), ssh_kp.public_key())
def get_connection(self): url = self.properties[self.VENAFI_URL] user = self.properties[self.TPP_USER] password = self.properties[self.TPP_PASSWORD] token = self.properties[self.API_KEY] fake = self.properties[self.FAKE] access_token = self.properties[self.ACCESS_TOKEN] if fake: LOG.info("Fake is %s. Will use fake connection", fake) trust_bundle = self.properties[self.TRUST_BUNDLE] if not trust_bundle: if access_token and access_token != "": return venafi_connection( url=url, user=None, password=None, access_token=access_token, refresh_token=None, http_request_kwargs=None, api_key=None, fake=fake) else: return Connection(url, token, user, password, fake=fake) try: decoded_bundle = base64.b64decode(trust_bundle) except: LOG.info("Trust bundle %s is not base64 encoded string. Considering it's a file", trust_bundle) if not path.isfile(trust_bundle): raise IOError(ENOENT, 'Not a file', trust_bundle) else: tmp_dir = tempfile.gettempdir() f = open(path.join(tmp_dir, 'venafi-temp-trust-bundle.pem'), "wb") LOG.info("Saving decoded trust bundle to temp file %s", f.name) f.write(decoded_bundle) f.close() trust_bundle = f.name if access_token and access_token != "": return venafi_connection( url=url, user=None, password=None, access_token=access_token, refresh_token=None, http_request_kwargs={"verify": trust_bundle}, api_key=None, fake=fake) else: return Connection(url, token, user, password, http_request_kwargs={"verify": trust_bundle}, fake=fake)
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 test_retrieve_ca_public_key(self): tpp_connector = venafi_connection( platform=VenafiPlatform.TPP, url=TPP_TOKEN_URL, http_request_kwargs={'verify': "/tmp/chain.pem"}) request = SSHCATemplateRequest(ca_template=TPP_SSH_CADN) ssh_config = tpp_connector.retrieve_ssh_config(ca_request=request) self.assertIsNotNone(ssh_config.ca_public_key, f"{TPP_SSH_CADN} Public Key data is empty") self.assertIsNone(ssh_config.ca_principals, f"{TPP_SSH_CADN} default principals is not empty") log.debug( f"{TPP_SSH_CADN} Public Key data:\n{ssh_config.ca_public_key}")
def main(): # Get credentials from environment variables url = environ.get('TPP_URL') user = environ.get('TPP_USER') password = environ.get('TPP_PASSWORD') connector = 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: # connector = venafi_connection(url=url, api_key=api_key, access_token=access_token, # http_request_kwargs={"verify": "/path-to/bundle.pem"}) # Create an Authentication object to request a token with the proper scope to manage SSH certificates auth = Authentication(user=user, password=password, scope=SCOPE_SSH) # Additionally, you may change the default client id for a custom one # Make sure this id has been registered on the TPP instance beforehand # Also, the user (TTP_USER) should be allowed to use this application # And the application should have the ssh permissions enabled auth.client_id = 'vcert-ssh-demo' # Request access token # After the request is successful, subsequent api calls will use the same token connector.get_access_token(auth) # The path to the SSH CA in the TPP instance cadn = "\\VED\\Certificate Authority\\SSH\\Templates\\my-ca" # The id of the SSH certificate key_id = f"vcert-python-{random_word(12)}" # Create the request object request = SSHCertRequest(cadn=cadn, key_id=key_id) # Add any additional info for the certificate, like: request.validity_period = "4h" request.source_addresses = ["test.com"] request.extensions = { 'permit-pty': "" } # Request the certificate from TPP instance success = connector.request_ssh_cert(request) if success: # Optional. Define a passphrase for encryption # The service generated private key will be encrypted using this passphrase # This step should happen after the request has been invoked request.private_key_passphrase = "foobar" # Retrieve the certificate from TPP instance response = connector.retrieve_ssh_cert(request) # Save the certificate, private and public key to files write_ssh_files("/path/to/ssh/cert/folder", response.certificate_details.key_id, response.certificate_data, response.private_key_data, response.public_key_data)
def main(): # Get credentials from environment variables. url = environ.get('TPP_URL') ca_dn = environ.get('TPP_SSH_CADN') ca_guid = environ.get('TPP_SSH_CA_GUID') # Authentication is required for retrieving the CA principals only. user = environ.get('TPP_USER') password = environ.get('TPP_PASSWORD') # A Connector can be instantiated with no values by using the platform argument. # url argument is always required for TPP. connector = venafi_connection( platform=VenafiPlatform.TPP, url=url, http_request_kwargs={'verify': "/tmp/chain.pem"}) # Optionally, the connector can be instantiated passing the specific arguments: # connector = venafi_connection(url=url, user=user, password=password, http_request_kwargs={"verify": False}) # If your TPP server certificate is signed with your own CA, or available only via proxy, # you can specify a trust bundle using requests vars: # connector = venafi_connection(url=url, api_key=api_key, access_token=access_token, # http_request_kwargs={"verify": "/path-to/bundle.pem"}) # Create an SSHCATemplateRequest to pass the identifier of the SSH Certificate Authority to retrieve. # Either CADN or Guid can be used as identifiers. request = SSHCATemplateRequest(ca_template=ca_dn) # request = SSHCATemplateRequest(ca_guid=ca_guid) # Retrieve the public key. # No Authentication is provided to the Connector so, only the public key is available. ssh_config = connector.retrieve_ssh_config(ca_request=request) pub_key_data = ssh_config.ca_public_key with open("./ca-pub.key", 'w') as ca_file: ca_file.write(pub_key_data) # To retrieve the CA principals create an Authentication object with the proper scope to manage SSH certificates. auth = Authentication(user=user, password=password, scope=SCOPE_SSH) # Additionally, you may change the default client id for a custom one. # Make sure this id has been registered on the TPP instance beforehand. # Also, the user (TTP_USER) should be allowed to use this application # and the application should have the ssh permissions enabled. auth.client_id = 'vcert-ssh-ca-pubkey-demo' # Request an access token. # After the request is successful, subsequent api calls will use the same token connector.get_access_token(auth) # Retrieve SSH Certificate Authority public key and principals ssh_config = connector.retrieve_ssh_config(ca_request=request) with open("./ca2-pub.key", 'w') as ca_file: ca_file.write(pub_key_data) print(f"Certificate Authority principals: {ssh_config.ca_principals}")
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') # Get connector object. # The default state of this connection only allows for certificate management. connector = venafi_connection( url=url, user=user, password=password, http_request_kwargs={'verify': server_trust_bundle}) # Create Authentication object with required scope for policy management. auth = Authentication(user=user, password=password, scope=SCOPE_PM) # Additionally, change the client id for a custom one. # Make sure this id has been registered on the TPP instance beforehand. auth.client_id = 'vcert-tpp-demo' # Request access token with values specified in auth object. # After the request is successful, subsequent api calls will use the same token. connector.get_access_token(auth) # Define policy specification object to create a new policy ps = PolicySpecification() # Alternatively, the parser utilities can be used to read a json/yaml file into a PolicySpecification object # ps = json_parser.parse_file('path/to/file.json') # ps = yaml_parser.parse_file('path/to/file.yaml') # All of the following values can be omitted to create a Policy with inherited (TPP) or recommended (Cloud) settings ps.policy = Policy(subject=Subject( orgs=['OSS Venafi, Inc.'], org_units=['Customer Support', 'Professional Services'], localities=['Salt Lake City'], states=['Utah'], countries=['US']), key_pair=KeyPair(key_types=['RSA'], rsa_key_sizes=[4096], elliptic_curves=['P521'], reuse_allowed=True), subject_alt_names=SubjectAltNames(dns_allowed=True, ip_allowed=False, email_allowed=False, uri_allowed=False, upn_allowed=False), cert_auth=None, domains=['vfidev.com', 'vfidev.net', 'venafi.example'], wildcard_allowed=True, auto_installed=False) ps.defaults = Defaults(d_subject=DefaultSubject( org='OSS Venafi, Inc.', org_units=['Customer Support', 'Professional Services'], locality='Salt Lake City', state='Utah', country='US'), d_key_pair=DefaultKeyPair(key_type='RSA', rsa_key_size=4096, elliptic_curve='P521'), auto_installed=False) # Create the new policy in the path specified by zone # If the policy already exists, it will be updated instead with the new settings connector.set_policy(zone, ps) # Retrieve the Policy from the Venafi Platform response = connector.get_policy(zone) # Transform the PolicySpecification object to a serializable form data = parse_policy_spec(response) # Print the transformed data pprint(data)
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 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()
def main(): # Get credentials from environment variables zone = environ.get('VAAS_ZONE') api_key = environ.get('VAAS_APIKEY') # Get connector object connector = venafi_connection(api_key=api_key) # Define policy specification object to create a new policy ps = PolicySpecification() # Alternatively, the parser utilities can be used to read a json/yaml file into a PolicySpecification object # ps = json_parser.parse_file('path/to/file.json') # ps = yaml_parser.parse_file('path/to/file.yaml') # All of the following values can be omitted to create a Policy with inherited (TPP) or recommended (Cloud) settings ps.policy = Policy( subject=Subject( orgs=['OSS Venafi, Inc.'], org_units=['Customer Support', 'Professional Services'], localities=['Salt Lake City'], states=['Utah'], countries=['US'] ), key_pair=KeyPair( key_types=['RSA'], rsa_key_sizes=[4096], elliptic_curves=['P521'], reuse_allowed=True ), subject_alt_names=SubjectAltNames( dns_allowed=True, ip_allowed=False, email_allowed=False, uri_allowed=False, upn_allowed=False ), cert_auth=None, domains=['vfidev.com', 'vfidev.net', 'venafi.example'], wildcard_allowed=True, auto_installed=False ) ps.defaults = Defaults( d_subject=DefaultSubject( org='OSS Venafi, Inc.', org_units=['Customer Support', 'Professional Services'], locality='Salt Lake City', state='Utah', country='US' ), d_key_pair=DefaultKeyPair( key_type='RSA', rsa_key_size=4096, elliptic_curve='P521' ), auto_installed=False ) # Create the new policy in the path specified by zone # If the policy already exists, it will be updated instead with the new settings connector.set_policy(zone, ps) # Retrieve the Policy from the Venafi Platform response = connector.get_policy(zone) # Transform the PolicySpecification object to a serializable form data = parse_policy_spec(response) # Print the transformed data pprint(data)
def __init__(self, module): """ :param AnsibleModule module: """ self.common_name = module.params['common_name'] self.test_mode = module.params['test_mode'] self.url = module.params['url'] self.password = module.params['password'] self.access_token = module.params['access_token'] self.token = module.params['token'] self.user = module.params['user'] self.zone = module.params['zone'] self.privatekey_filename = module.params['privatekey_path'] self.certificate_filename = module.params['cert_path'] self.privatekey_type = module.params['privatekey_type'] if self.user != "": module.warn("User is deprecated use access token instead") if self.password != "": module.warn("Password is deprecated use access token instead") if module.params['privatekey_curve']: if not module.params['privatekey_type']: module.fail_json(msg="privatekey_type should be " "set if privatekey_curve configured") self.privatekey_curve = module.params['privatekey_curve'] if module.params['privatekey_size']: if not module.params['privatekey_type']: module.fail_json(msg="privatekey_type should be set if " "privatekey_size configured") self.privatekey_size = module.params['privatekey_size'] self.privatekey_passphrase = module.params['privatekey_passphrase'] self.privatekey_reuse = module.params['privatekey_reuse'] self.chain_filename = module.params['chain_path'] self.csr_path = module.params['csr_path'] self.args = "" self.changed = False self.module = module self.ip_addresses = [] self.email_addresses = [] self.san_dns = [] self.changed_message = [] if module.params['alt_name']: for n in module.params['alt_name']: if n.startswith(("IP:", "IP Address:")): ip = n.split(":", 1)[1] self.ip_addresses.append(ip) elif n.startswith("DNS:"): ns = n.split(":", 1)[1] self.san_dns.append(ns) elif n.startswith("email:"): mail = n.split(":", 1)[1] self.email_addresses.append(mail) else: self.module.fail_json( msg="Failed to determine extension type: %s" % n) trust_bundle = module.params['trust_bundle'] if trust_bundle: if self.access_token and self.access_token != "": self.conn = venafi_connection( url=self.url, user=None, password=None, access_token=self.access_token, refresh_token=None, http_request_kwargs={"verify": trust_bundle}, api_key=None, fake=self.test_mode) else: self.conn = Connection( url=self.url, token=self.token, password=self.password, user=self.user, fake=self.test_mode, http_request_kwargs={"verify": trust_bundle}) else: if self.access_token and self.access_token != "": self.conn = venafi_connection(url=self.url, access_token=self.access_token, user=None, password=None, api_key=None, fake=self.test_mode) else: self.conn = Connection(url=self.url, token=self.token, fake=self.test_mode, user=self.user, password=self.password) self.before_expired_hours = module.params['before_expired_hours']