def main(): # Create a PKIConnection object that stores the details of the CA. connection = client.PKIConnection('https', 'localhost', '8453', 'ca') # Instantiate the FeatureClient feature_client = FeatureClient(connection) # List all features print("Listing all features") print("-----------------------") features = feature_client.list_features() for feature in features.feature_list: print(str(feature)) # Get authority feature print("Getting authority feature") print("-------------------------") feature = feature_client.get_feature("authority") print(str(feature)) # Get non-existent feature print("Get non-existent feature") print("------------------------") try: feature_client.get_feature("foobar") except pki.ResourceNotFoundException as e: print(e.message)
def setup_authentication(self, subsystem, c_nssdb_pass, c_nssdb_pass_file, c_cert, c_nssdb, tmpdir): temp_auth_p12 = os.path.join(tmpdir, 'auth.p12') temp_auth_cert = os.path.join(tmpdir, 'auth.pem') if not c_cert: print('ERROR: Client cert nickname is required.') self.usage() sys.exit(1) # Create a PKIConnection object that stores the details of subsystem. connection = client.PKIConnection('https', os.environ['HOSTNAME'], '8443', subsystem.name) # Create a p12 file using # pk12util -o <p12 file name> -n <cert nick name> -d <NSS db path> # -W <pkcs12 password> -K <NSS db pass> cmd_generate_pk12 = [ 'pk12util', '-o', temp_auth_p12, '-n', c_cert, '-d', c_nssdb ] # The pem file used for authentication. Created from a p12 file using the # command: # openssl pkcs12 -in <p12_file_path> -out /tmp/auth.pem -nodes cmd_generate_pem = [ 'openssl', 'pkcs12', '-in', temp_auth_p12, '-out', temp_auth_cert, '-nodes', ] if c_nssdb_pass_file: # Use the same password file for the generated pk12 file cmd_generate_pk12.extend( ['-k', c_nssdb_pass_file, '-w', c_nssdb_pass_file]) cmd_generate_pem.extend(['-passin', 'file:' + c_nssdb_pass_file]) else: # Use the same password for the generated pk12 file cmd_generate_pk12.extend(['-K', c_nssdb_pass, '-W', c_nssdb_pass]) cmd_generate_pem.extend(['-passin', 'pass:' + c_nssdb_pass]) res_pk12 = subprocess.check_output(cmd_generate_pk12, stderr=subprocess.STDOUT) if self.verbose: print(res_pk12) res_pem = subprocess.check_output(cmd_generate_pem, stderr=subprocess.STDOUT) if self.verbose: print(res_pem) # Bind the authentication with the connection object connection.set_authentication_cert(temp_auth_cert) return connection
def main(): # Create a PKIConnection object that stores the details of the CA. connection = client.PKIConnection('https', 'localhost', '8453') # The pem file used for authentication. Created from a p12 file using the # command - # openssl pkcs12 -in <p12_file_path> -out /tmp/auth.pem -nodes connection.set_authentication_cert("/tmp/auth.pem") # Instantiate the CertClient ca_client = AuthorityClient(connection) # Create a top level authority print("Creating a new top level CA") print("-----------------------------") subca_subject = ('cn=subca ' + str(uuid.uuid4()) + ' signing cert, o=example.com') sub_subca_subject = ('cn=subca2 ' + str(uuid.uuid4()) + ' signing cert, o=example.com') authority_data = { 'dn': subca_subject, 'description': 'Test Top-level subordinate CA', } data = AuthorityData(**authority_data) try: subca = ca_client.create_ca(data) except ValueError as e: print(e) # Get the host CA print("Getting the host CA") print("----------------------") authorities = ca_client.list_cas() for ca in authorities.ca_list: if ca.is_host_authority: host_ca = ca print(str(host_ca)) # Create a sub CA print("Creating a new subordinate CA") print("-----------------------------") authority_data = { 'dn': subca_subject, 'description': 'Test subordinate CA', 'parent_aid': host_ca.aid } data = AuthorityData(**authority_data) subca = ca_client.create_ca(data) print(ca_client.get_ca(subca.aid)) # Get the authority signing cert and pkcs7 chain pem_cert = ca_client.get_cert(subca.aid, "PEM") print("PEM CA Signing Cert:") print(pem_cert) pkcs7_chain = ca_client.get_chain(subca.aid, "PKCS7") print("PKCS7 Cert Chain:") print(pkcs7_chain) pem_chain = ca_client.get_chain(subca.aid, "PEM") print("PEM Cert Chain:") print(pem_chain) # List all authorities print("Listing all authorities") print("-----------------------") authorities = ca_client.list_cas() for ca in authorities.ca_list: print(str(ca)) # Issue a cert using the sub-CA cert_client = cert.CertClient(connection) issue_cert_using_authority(cert_client, subca.aid) # Create a sub-sub CA print('Create a sub-sub CA') print('-------------------') sub_subca_data = { 'dn': sub_subca_subject, 'description': 'Test sub-sub CA', 'parent_aid': subca.aid } data = AuthorityData(**sub_subca_data) sub_subca = ca_client.create_ca(data) print(ca_client.get_ca(sub_subca.aid)) # Get the authority signing cert and PKCS7 # Get the authority signing cert and pkcs7 chain pem_cert = ca_client.get_cert(sub_subca.aid, "PEM") print("PEM CA Signing Cert:") print(pem_cert) pkcs7_chain = ca_client.get_chain(sub_subca.aid, "PKCS7") print("PKCS7 Cert Chain:") print(pkcs7_chain) pem_chain = ca_client.get_chain(sub_subca.aid, "PEM") print("PEM Cert Chain:") print(pem_chain) # issue a cert using the sub-subca cert_client = cert.CertClient(connection) issue_cert_using_authority(cert_client, sub_subca.aid) # delete the sub-subca print("Delete sub CA") print("-------------") try: ca_client.delete_ca(sub_subca.aid) except pki.ConflictingOperationException as e: print(e) # disable the sub-subca print("Disable sub sub CA") print("------------------") ca_client.disable_ca(sub_subca.aid) # Get sub-subca sub_subca = ca_client.get_ca(sub_subca.aid) print(str(sub_subca)) # issue a cert using sub-subca print("Issuing a cert using disabled subca") print("-----------------------------------") try: issue_cert_using_authority(cert_client, sub_subca.aid) except pki.ConflictingOperationException as e: print(e) # delete the sub-subca print("Delete sub CA") print("-------------") ca_client.delete_ca(sub_subca.aid) # get the sub-subca print("Get deleted subca") print("-----------------") try: ca_client.get_ca(sub_subca.aid) except pki.ResourceNotFoundException as e: print(e) # issue a cert using the sub-subca print("Issue a cert using deleted subca") print("--------------------------------") try: issue_cert_using_authority(cert_client, sub_subca.aid) except pki.ResourceNotFoundException as e: print(e) # create a new subca with same subjectdn print("Create a new sub-subca re-using subject dn") print("------------------------------------------") data = AuthorityData(**sub_subca_data) sub_subca = ca_client.create_ca(data) print(ca_client.get_ca(sub_subca.aid)) print("Issuing a cert using sub-subca") print("-----------------------------------") issue_cert_using_authority(cert_client, sub_subca.aid)
def main(): # Create a PKIConnection object that stores the details of the CA. connection = client.PKIConnection('https', 'localhost', '8443', 'ca') # The pem file used for authentication. Created from a p12 file using the # command - # openssl pkcs12 -in <p12_file_path> -out /tmp/auth.pem -nodes connection.set_authentication_cert("/tmp/auth.pem") # Instantiate the CertClient cert_client = CertClient(connection) cert_client.get_enrollment_template('caUserCert') # Enrolling an user certificate print('Enrolling an user certificate') print('-----------------------------') inputs = dict() inputs['cert_request_type'] = 'crmf' inputs['cert_request'] = "MIIBpDCCAaAwggEGAgUA5n9VYTCBx4ABAqUOMAwxCjAIBgN" \ "VBAMTAXimgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAK" \ "/SmUVoUjBtqHNw/e3OoCSXw42pdQSR53/eYJWpf7nyTbZ9U" \ "uIhGfXOtxy5vRetmDHE9u0AopmuJbr1rL17/tSnDakpkE9u" \ "mQ2lMOReLloSdX32w2xOeulUwh5BGbFpq10S0SvW1H93Vn0" \ "eCy2aa4UtILNEsp7JJ3FnYJibfuMPAgMBAAGpEDAOBgNVHQ" \ "8BAf8EBAMCBeAwMzAVBgkrBgEFBQcFAQEMCHJlZ1Rva2VuM" \ "BoGCSsGAQUFBwUBAgwNYXV0aGVudGljYXRvcqGBkzANBgkq" \ "hkiG9w0BAQUFAAOBgQCuywnrDk/wGwfbguw9oVs9gzFQwM4" \ "zeFbk+z82G5CWoG/4mVOT5LPL5Q8iF+KfnaU9Qcu6zZPxW6" \ "ZmDd8WpPJ+MTPyQl3Q5BfiKa4l5ra1NeqxMOlMiiupwINmm" \ "7jd1KaA2eIjuyC8/gTaO4b14R6aRaOj+Scp9cNYbthA7REh" \ "Jw==" inputs['sn_uid'] = 'test12345' inputs['sn_e'] = '*****@*****.**' inputs['sn_cn'] = 'TestUser' enrollment_results = cert_client.enroll_cert('caUserCert', inputs) for enrollment_result in enrollment_results: request_data = enrollment_result.request cert_data = enrollment_result.cert print('Request ID: ' + request_data.request_id) print('Request Status:' + request_data.request_status) print('Serial Number: ' + cert_data.serial_number) print('Issuer: ' + cert_data.issuer_dn) print('Subject: ' + cert_data.subject_dn) print('Pretty Print:') print(cert_data.pretty_repr) print() # Enrolling a server certificate print("Enrolling a server certificate") print('------------------------------') inputs = dict() inputs['cert_request_type'] = 'pkcs10' inputs['cert_request'] = "MIIBmDCCAQECAQAwWDELMAkGA1UEBhMCVVMxCzAJBgNVBAg" \ "MAk5DMRAwDgYDVQQHDAdSYWxlaWdoMRUwEwYDVQQKDAxSZW" \ "QgSGF0IEluYy4xEzARBgNVBAMMClRlc3RTZXJ2ZXIwgZ8wD" \ "QYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMJpWz92dSYCvWxl" \ "lrQCY5atPKCswUwyppRNGPnKmJ77AdHBBI4dFyET+h/+69j" \ "QMTLZMa8FX7SbyHvgbgLBP4Q/RzCSE2S87qFNjriOqiQCqJ" \ "mcrzDzdncJQiP+O7T6MSpLo3smLP7dK1Vd7vK0Vy8yHwV0e" \ "Bx7DgYedv2slBPHAgMBAAGgADANBgkqhkiG9w0BAQUFAAOB" \ "gQBvkxAGKwkfK3TKwLc5Mg0IWp8zGRVwxdIlghAL8DugNoc" \ "CNNgmZazglJOOehLuk0/NkLX1ZM5RrVgM09W6kcfWZtIwr5" \ "Uje2K/+6tW2ZTGrbizs7CNOTMzA/9H8CkHb4H9P/qRT275z" \ "HIocYj4smUnXLwWGsBMeGs+OMMbGvSrHg==" inputs['requestor_name'] = 'Tester' inputs['requestor_email'] = '*****@*****.**' cert_id = None enrollment_results_2 = cert_client.enroll_cert('caServerCert', inputs) for enrollment_result in enrollment_results_2: request_data = enrollment_result.request cert_data = enrollment_result.cert print('Request ID: ' + request_data.request_id) print('Request Status:' + request_data.request_status) if cert_data is not None: # store cert_id for usage later cert_id = cert_data.serial_number print('Serial Number: ' + cert_id) print('Issuer: ' + cert_data.issuer_dn) print('Subject: ' + cert_data.subject_dn) print('Pretty Print:') print(cert_data.pretty_repr) print() # List all the VALID certs print('An example listing all VALID certs') print('----------------------------------') search_params = {'status': 'VALID'} cert_data_list = cert_client.list_certs(**search_params) for cert_data_info in cert_data_list: print("Serial Number: " + cert_data_info.serial_number) print("Subject DN: " + cert_data_info.subject_dn) print("Status: " + cert_data_info.status) print() # Trying to get a non-existing cert # Assuming that there is no certificate with serial number = 100 try: cert_data = cert_client.get_cert(100) print('Serial Number: ' + cert_data.serial_number) print('Issuer: ' + cert_data.issuer_dn) print('Subject: ' + cert_data.subject_dn) except pki.CertNotFoundException: print("Certificate with ID 100 does not exist") print() # Certificate Serial Number used for CertClient methods. # 7, 0x7 and '0x7' are also valid values # Following examples use the serial number of the user certificate enrolled # before. # Get certificate data print('Getting information of a certificate') print('------------------------------------') cert_data = cert_client.get_cert(cert_id) # Print the certificate information print('Serial Number: ' + cert_data.serial_number) print('Issuer: ' + cert_data.issuer_dn) print('Subject: ' + cert_data.subject_dn) print('Status: ' + cert_data.status) print('Not Before: ' + cert_data.not_before) print('Not After: ' + cert_data.not_after) print('Encoded: ') print(cert_data.encoded) print("Pretty print format: ") print(cert_data.pretty_repr) print() # Review a certificate - used to get a nonce for revoke request. print('Reviewing a certificate') print('-----------------------') cert_data = cert_client.review_cert(cert_id) print('Serial Number: ' + cert_data.serial_number) print('Issuer: ' + cert_data.issuer_dn) print('Subject: ' + cert_data.subject_dn) print('Status: ' + cert_data.status) print('Nonce: ' + str(cert_data.nonce)) print() # Revoke a certificate print('Revoking a certificate') print('----------------------') cert_request_info = cert_client.hold_cert(cert_data.serial_number, comments="Test revoking a cert") print('Request ID: ' + cert_request_info.request_id) print('Request Type: ' + cert_request_info.request_type) print('Request Status: ' + cert_request_info.request_status) print() # Un-revoke a certificate print('Un-revoking a certificate') print('-------------------------') cert_request_info = cert_client.unrevoke_cert(cert_data.serial_number) print('Request ID: ' + cert_request_info.request_id) print('Request Type: ' + cert_request_info.request_type) print('Request Status: ' + cert_request_info.request_status) print()
def main(): # Initialize a PKIConnection object for the CA connection = client.PKIConnection('https', 'localhost', '8443') # The pem file used for authentication. Created from a p12 file using the # command - # openssl pkcs12 -in <p12_file_path> -out /tmp/auth.pem -nodes connection.set_authentication_cert("/tmp/auth.pem") # Initialize the ProfileClient class profile_client = ProfileClient(connection) # Folder to store the files generated during test file_path = '/tmp/profile_client_test/' if not os.path.exists(file_path): os.makedirs(file_path) # Fetching a list of profiles profile_data_infos = profile_client.list_profiles() print('List of profiles:') print('-----------------') for profile_data_info in profile_data_infos: print(' Profile ID: ' + profile_data_info.profile_id) print(' Profile Name: ' + profile_data_info.profile_name) print(' Profile Description: ' + profile_data_info.profile_description) print() # Get a specific profile profile_data = profile_client.get_profile('caUserCert') print('Profile Data for caUserCert:') print('----------------------------') print(' Profile ID: ' + profile_data.profile_id) print(' Profile Name: ' + profile_data.name) print(' Profile Description: ' + profile_data.description) print(' Is profile enabled? ' + str(profile_data.enabled)) print(' Is profile visible? ' + str(profile_data.visible)) print() # Disabling a profile print('Disabling a profile:') print('--------------------') profile_client.disable_profile('caUserCert') profile = profile_client.get_profile('caUserCert') print(' Profile ID: ' + profile.profile_id) print(' Is profile enabled? ' + str(profile.enabled)) print() # Disabling a profile print('Enabling a profile:') print('-------------------') profile_client.enable_profile('caUserCert') profile = profile_client.get_profile('caUserCert') print(' Profile ID: ' + profile_data.profile_id) print(' Is profile enabled? ' + str(profile.enabled)) print() # profile_client.delete_profile('MySampleProfile') # Create a new sample profile print('Creating a new profile:') print('-----------------------') profile_data = Profile(name="My Sample User Cert Enrollment", profile_id="MySampleProfile", class_id="caEnrollImpl", description="Example User Cert Enroll Impl", enabled_by='admin', enabled=False, visible=False, renewal=False, xml_output=False, authorization_acl="") # Adding a profile input profile_input = ProfileInput("i1", "subjectNameInputImpl") profile_input.add_attribute(ProfileAttribute("sn_uid")) profile_input.add_attribute(ProfileAttribute("sn_e")) profile_input.add_attribute(ProfileAttribute("sn_c")) profile_input.add_attribute(ProfileAttribute("sn_ou")) profile_input.add_attribute(ProfileAttribute("sn_ou1")) profile_input.add_attribute(ProfileAttribute("sn_ou2")) profile_input.add_attribute(ProfileAttribute("sn_ou3")) profile_input.add_attribute(ProfileAttribute("sn_cn")) profile_input.add_attribute(ProfileAttribute("sn_o")) profile_data.add_input(profile_input) # Adding a profile output profile_output = ProfileOutput("o1", name="Certificate Output", class_id="certOutputImpl") profile_output.add_attribute(ProfileAttribute("pretty_cert")) profile_output.add_attribute(ProfileAttribute("b64_cert")) profile_data.add_output(profile_output) # Create a Policy set with a list of profile policies policy_list = [] # Creating profile policy policy_default = PolicyDefault( "Subject Name Default", "userSubjectNameDefaultImpl", "This default populates a User-Supplied " "Certificate Subject Name to the request.") attr_descriptor = Descriptor(syntax="string", description="Subject Name") policy_attribute = ProfileAttribute("name", descriptor=attr_descriptor) policy_default.add_attribute(policy_attribute) policy_constraint = PolicyConstraint( "Subject Name Constraint", "This constraint accepts the subject " "name that matches UID=.*", "subjectNameConstraintImpl") constraint_descriptor = Descriptor(syntax="string", description="Subject Name Pattern") policy_constraint_value = PolicyConstraintValue("pattern", "UID=.*", constraint_descriptor) policy_constraint.add_constraint_value(policy_constraint_value) policy_list.append(ProfilePolicy("1", policy_default, policy_constraint)) # Creating another profile policy # Defining the policy default policy_default = PolicyDefault( "Validity Default", "validityDefaultImpl", "This default populates a Certificate " "Validity to the request. The default " "values are Range=180 in days") attr_descriptor = Descriptor(syntax="string", description="Not Before") policy_attribute = ProfileAttribute("notBefore", descriptor=attr_descriptor) policy_default.add_attribute(policy_attribute) attr_descriptor = Descriptor(syntax="string", description="Not After") policy_attribute = ProfileAttribute("notAfter", descriptor=attr_descriptor) policy_default.add_attribute(policy_attribute) profile_param = ProfileParameter("range", 180) profile_param2 = ProfileParameter("startTime", 0) policy_default.add_parameter(profile_param) policy_default.add_parameter(profile_param2) # Defining the policy constraint policy_constraint = PolicyConstraint( "Validity Constraint", "This constraint rejects the validity " "that is not between 365 days.", "validityConstraintImpl") constraint_descriptor = Descriptor(syntax="integer", description="Validity Range (in days)", default_value=365) policy_constraint_value = PolicyConstraintValue("range", 365, constraint_descriptor) policy_constraint.add_constraint_value(policy_constraint_value) constraint_descriptor = Descriptor(syntax="boolean", default_value=False, description="Check Not Before against" " current time") policy_constraint_value = PolicyConstraintValue("notBeforeCheck", False, constraint_descriptor) policy_constraint.add_constraint_value(policy_constraint_value) constraint_descriptor = Descriptor(syntax="boolean", default_value=False, description="Check Not After against" " Not Before") policy_constraint_value = PolicyConstraintValue("notAfterCheck", False, constraint_descriptor) policy_constraint.add_constraint_value(policy_constraint_value) policy_list.append(ProfilePolicy("2", policy_default, policy_constraint)) policy_set = PolicySet("userCertSet", policy_list) profile_data.add_policy_set(policy_set) # Write the profile data object to a file for testing a file input with open(file_path + '/original.json', 'w') as output_file: output_file.write( json.dumps(profile_data, cls=encoder.CustomTypeEncoder, sort_keys=True, indent=4)) # Create a new profile created_profile = profile_client.create_profile(profile_data) print(created_profile) print() # Test creating a new profile with a duplicate profile id print("Create a profile with duplicate profile id.") print("-------------------------------------------") try: profile_data = Profile(name="My Sample User Cert Enrollment", profile_id="MySampleProfile", class_id="caEnrollImpl", description="Example User Cert Enroll Impl", enabled_by='admin', enabled=False, visible=False, renewal=False, xml_output=False, authorization_acl="") profile_input = ProfileInput("i1", "subjectNameInputImpl") profile_input.add_attribute(ProfileAttribute("sn_uid")) profile_input.add_attribute(ProfileAttribute("sn_e")) profile_input.add_attribute(ProfileAttribute("sn_c")) profile_input.add_attribute(ProfileAttribute("sn_ou")) profile_input.add_attribute(ProfileAttribute("sn_ou1")) profile_input.add_attribute(ProfileAttribute("sn_ou2")) profile_input.add_attribute(ProfileAttribute("sn_ou3")) profile_input.add_attribute(ProfileAttribute("sn_cn")) profile_input.add_attribute(ProfileAttribute("sn_o")) profile_data.add_input(profile_input) profile_client.create_profile(profile_data) # pylint: disable=W0703 except pki.BadRequestException as e: print('MySampleProfile ' + str(e)) print() # Modify the above created profile print('Modifying the profile MySampleProfile.') print('-----------------------------------') fetch = profile_client.get_profile('MySampleProfile') profile_input2 = ProfileInput("i2", "keyGenInputImpl") profile_input2.add_attribute(ProfileAttribute("cert_request_type")) profile_input2.add_attribute(ProfileAttribute("cert_request")) fetch.add_input(profile_input2) fetch.name += " (Modified)" modified_profile = profile_client.modify_profile(fetch) with open(file_path + 'modified.json', 'w') as output_file: output_file.write( json.dumps(fetch, cls=encoder.CustomTypeEncoder, sort_keys=True, indent=4)) print(modified_profile) print() # Delete a profile print("Deleting the profile MySampleProfile.") print("----------------------------------") profile_client.delete_profile('MySampleProfile') print("Deleted profile MySampleProfile.") print() # Testing deletion of a profile print('Test profile deletion.') print('----------------------') try: profile_client.get_profile('MySampleProfile') # pylint: disable=W0703 except pki.ProfileNotFoundException as e: print(str(e)) print() # Creating a profile from file print('Creating a profile using file input.') print('------------------------------------') original = profile_client.create_profile_from_file(file_path + 'original.json') print(original) print() # Modifying a profile from file print('Modifying a profile using file input.') print('------------------------------------') modified = profile_client.modify_profile_from_file(file_path + 'modified.json') print(modified) print() # Test clean up profile_client.delete_profile('MySampleProfile') os.remove(file_path + 'original.json') os.remove(file_path + 'modified.json') os.removedirs(file_path)