def test_1_load_der_cert(self): """ Test loading a DER certificate. """ der = base64.b64decode(goodcert) # Load a good cert x509.load_der_x509_certificate(der)
def create_server_cert(self, nickname, hostname, subject=None): """ If we are using a dogtag CA then other_certdb contains the RA agent key that will issue our cert. You can override the certificate Subject by specifying a subject. Returns a certificate in DER format. """ if subject is None: subject=DN(('CN', hostname), self.subject_base) self.request_cert(subject, san_dnsnames=[hostname]) try: self.issue_server_cert(self.certreq_fname, self.certder_fname) self.import_cert(self.certder_fname, nickname) with open(self.certder_fname, "rb") as f: dercert = f.read() return x509.load_der_x509_certificate(dercert) finally: for fname in (self.certreq_fname, self.certder_fname): try: os.unlink(fname) except OSError: pass
def makecert(reqdir, subject, principal): """ Generate a certificate that can be used during unit testing. """ ra = rabase.rabase(api) if (not os.path.exists(ra.client_certfile) and api.env.xmlrpc_uri == 'http://localhost:8888/ipa/xml'): raise AssertionError('The self-signed CA is not configured, ' 'see ipatests/test_xmlrpc/test_cert.py') pwname = os.path.join(reqdir, "pwd") # Create an empty password file with open(pwname, "w") as fp: fp.write("\n") # Generate NSS cert database to store the private key for our CSR run_certutil(reqdir, ["-N", "-f", pwname]) csr = unicode(generate_csr(reqdir, pwname, str(subject))) res = api.Command['cert_request'](csr, principal=principal, add=True) cert = x509.load_der_x509_certificate( base64.b64decode(res['result']['certificate'])) return cert.public_bytes(x509.Encoding.PEM).decode('utf-8')
def forward(self, *keys, **options): filename = None if 'certificate_out' in options: filename = options.pop('certificate_out') try: util.check_writable_file(filename) except errors.FileError as e: raise errors.ValidationError(name='certificate-out', error=str(e)) result = super(WithCertOutArgs, self).forward(*keys, **options) if filename: # if result certificate / certificate_chain not present in result, # it means Dogtag did not provide it (probably due to LWCA key # replication lag or failure. The server transmits a warning # message in this case, which the client automatically prints. # So in this section we just ignore it and move on. certs = None if options.get('chain', False): if 'certificate_chain' in result['result']: certs = result['result']['certificate_chain'] else: if 'certificate' in result['result']: certs = [base64.b64decode(result['result']['certificate'])] if certs: x509.write_certificate_list( (x509.load_der_x509_certificate(cert) for cert in certs), filename) return result
def create_server_cert(self, nickname, hostname, subject=None): """ If we are using a dogtag CA then other_certdb contains the RA agent key that will issue our cert. You can override the certificate Subject by specifying a subject. Returns a certificate in DER format. """ if subject is None: subject = DN(('CN', hostname), self.subject_base) self.request_cert(subject, san_dnsnames=[hostname]) try: self.issue_server_cert(self.certreq_fname, self.certder_fname) self.import_cert(self.certder_fname, nickname) with open(self.certder_fname, "rb") as f: dercert = f.read() return x509.load_der_x509_certificate(dercert) finally: for fname in (self.certreq_fname, self.certder_fname): try: os.unlink(fname) except OSError: pass
def makecert(reqdir, subject, principal): """ Generate a certificate that can be used during unit testing. """ ra = rabase.rabase(api) if (not os.path.exists(ra.client_certfile) and api.env.xmlrpc_uri == 'http://localhost:8888/ipa/xml'): raise AssertionError('The self-signed CA is not configured, ' 'see ipatests/test_xmlrpc/test_cert.py') nssdb = certdb.NSSDatabase(nssdir=reqdir) with open(nssdb.pwd_file, "w") as f: # Create an empty password file f.write("\n") # create db nssdb.create_db() # create CSR csr_file = os.path.join(reqdir, 'req') nssdb.run_certutil([ "-R", "-s", str(subject), "-o", csr_file, "-z", paths.GROUP, "-a" ]) with open(csr_file, "rb") as f: csr = f.read().decode('ascii') res = api.Command['cert_request'](csr, principal=principal, add=True) cert = x509.load_der_x509_certificate( base64.b64decode(res['result']['certificate'])) return cert.public_bytes(x509.Encoding.PEM)
def _get_vaultconfig(self, force_refresh=False): config = None if not force_refresh: config = _kra_config_cache.load(self.api.env.domain) if config is None: # vaultconfig_show also caches data response = self.api.Command.vaultconfig_show() config = response['result'] transport_cert = x509.load_der_x509_certificate( config['transport_cert']) else: # cached JSON uses PEM-encoded ASCII string transport_cert = x509.load_pem_x509_certificate( config['transport_cert'].encode('ascii')) default_algo = config.get('wrapping_default_algorithm') if default_algo is None: # old server wrapping_algo = constants.VAULT_WRAPPING_AES128_CBC elif default_algo in constants.VAULT_WRAPPING_SUPPORTED_ALGOS: # try to use server default wrapping_algo = default_algo else: # prefer server's sorting order for algo in config['wrapping_supported_algorithms']: if algo in constants.VAULT_WRAPPING_SUPPORTED_ALGOS: wrapping_algo = algo break else: raise errors.ValidationError( "No overlapping wrapping algorithm between server and " "client.") return transport_cert, wrapping_algo
def makecert(reqdir, subject, principal): """ Generate a certificate that can be used during unit testing. """ ra = rabase.rabase(api) if (not os.path.exists(ra.client_certfile) and api.env.xmlrpc_uri == 'http://localhost:8888/ipa/xml'): raise AssertionError('The self-signed CA is not configured, ' 'see ipatests/test_xmlrpc/test_cert.py') nssdb = certdb.NSSDatabase(nssdir=reqdir) with open(nssdb.pwd_file, "w") as f: # Create an empty password file f.write("\n") # create db nssdb.create_db() # create CSR csr_file = os.path.join(reqdir, 'req') nssdb.run_certutil( ["-R", "-s", str(subject), "-o", csr_file, "-z", paths.GROUP, "-a"]) with open(csr_file, "rb") as f: csr = f.read().decode('ascii') res = api.Command['cert_request'](csr, principal=principal, add=True) cert = x509.load_der_x509_certificate( base64.b64decode(res['result']['certificate'])) return cert.public_bytes(x509.Encoding.PEM)
def list_users_by_cert(self, cert): """ Look for users matching the cert. Call Users.ListByCertificate interface and return a dict with key = domain, value = list of uids corresponding to the users matching the provided cert :param cert: DER cert, Certificate instances (IPACertificate) :raise RemoteRetrieveError: if DBus error occurs """ if isinstance(cert, crypto_x509.Certificate): cert_pem = cert.public_bytes(x509.Encoding.PEM) else: cert_obj = x509.load_der_x509_certificate(cert) cert_pem = cert_obj.public_bytes(x509.Encoding.PEM) try: # bug 3306 in sssd returns 0 entry when max_entries = 0 # Temp workaround is to use a non-null value, not too high # to avoid reserving unneeded memory max_entries = dbus.UInt32(100) user_paths = self._users_iface.ListByCertificate( cert_pem, max_entries) users = dict() for user_path in user_paths: user_obj = self._bus.get_object(DBUS_SSSD_NAME, user_path) user_iface = dbus.Interface(user_obj, DBUS_PROPERTY_IF) user_login = user_iface.Get(DBUS_SSSD_USER_IF, 'name') # Extract name@domain items = user_login.split('@') domain = api.env.realm if len(items) < 2 else items[1] name = items[0] # Retrieve the list of users for the given domain, # or initialize to an empty list # and add the name users_for_dom = users.setdefault(domain, list()) users_for_dom.append(name) return users except dbus.DBusException as e: err_name = e.get_dbus_name() # If there is no matching user, do not consider this as an # exception and return an empty list if err_name == 'org.freedesktop.sssd.Error.NotFound': return dict() logger.error( 'Failed to use interface %s. DBus ' 'exception is %s.', DBUS_SSSD_USERS_IF, e) raise errors.RemoteRetrieveError( reason=_('Failed to find users over SystemBus. ' ' See details in the error_log'))
def forward(self, *keys, **options): filename = None if 'certificate_out' in options: filename = options.pop('certificate_out') try: util.check_writable_file(filename) except errors.FileError as e: raise errors.ValidationError(name='certificate-out', error=str(e)) result = super(WithCertOutArgs, self).forward(*keys, **options) if filename: if options.get('chain', False): certs = (x509.load_der_x509_certificate(c) for c in result['result']['certificate_chain']) else: certs = [ x509.load_der_x509_certificate( result['result']['certificate']) ] x509.write_certificate_list(certs, filename) return result
def forward(self, *keys, **options): if 'out' in options: util.check_writable_file(options['out']) result = super(service_show, self).forward(*keys, **options) if 'usercertificate' in result['result']: certs = (x509.load_der_x509_certificate(c) for c in result['result']['usercertificate']) x509.write_certificate_list(certs, options['out']) result['summary'] = ( _('Certificate(s) stored in file \'%(file)s\'') % dict(file=options['out'])) return result else: raise errors.NoCertificateError(entry=keys[-1]) else: return super(service_show, self).forward(*keys, **options)
def forward(self, *keys, **options): if 'out' in options: util.check_writable_file(options['out']) result = super(service_show, self).forward(*keys, **options) if 'usercertificate' in result['result']: certs = (x509.load_der_x509_certificate(c) for c in result['result']['usercertificate']) x509.write_certificate_list(certs, options['out']) result['summary'] = ( _('Certificate(s) stored in file \'%(file)s\'') % dict(file=options['out']) ) return result else: raise errors.NoCertificateError(entry=keys[-1]) else: return super(service_show, self).forward(*keys, **options)
def internal(self, algo, *args, **options): """ Calls the internal counterpart of the command. """ domain = self.api.env.domain # try call with cached transport certificate transport_cert = _transport_cert_cache.load_cert(domain) if transport_cert is not None: result = self._do_internal(algo, transport_cert, False, *args, **options) if result is not None: return result # retrieve transport certificate (cached by vaultconfig_show) response = self.api.Command.vaultconfig_show() transport_cert = x509.load_der_x509_certificate( response['result']['transport_cert']) # call with the retrieved transport certificate return self._do_internal(algo, transport_cert, True, *args, **options)
def forward(self, *args, **options): file = options.get('transport_out') # don't send these parameters to server if 'transport_out' in options: del options['transport_out'] response = super(vaultconfig_show, self).forward(*args, **options) # cache transport certificate transport_cert = x509.load_der_x509_certificate( response['result']['transport_cert']) _transport_cert_cache.store_cert(self.api.env.domain, transport_cert) if file: with open(file, 'wb') as f: f.write(response['result']['transport_cert']) return response
def forward(self, *args, **options): if 'certificate_out' in options: certificate_out = options.pop('certificate_out') try: util.check_writable_file(certificate_out) except errors.FileError as e: raise errors.ValidationError(name='certificate-out', error=str(e)) else: certificate_out = None result = super(CertRetrieveOverride, self).forward(*args, **options) if certificate_out is not None: if options.get('chain', False): certs = result['result']['certificate_chain'] else: certs = [base64.b64decode(result['result']['certificate'])] certs = (x509.load_der_x509_certificate(cert) for cert in certs) x509.write_certificate_list(certs, certificate_out) return result
def forward(self, *args, **options): file = options.get('transport_out') # don't send these parameters to server if 'transport_out' in options: del options['transport_out'] response = super(vaultconfig_show, self).forward(*args, **options) # cache transport certificate transport_cert = x509.load_der_x509_certificate( response['result']['transport_cert']) _transport_cert_cache.store_cert( self.api.env.domain, transport_cert ) if file: with open(file, 'wb') as f: f.write(response['result']['transport_cert']) return response
def forward(self, *args, **options): if 'certificate_out' in options: certificate_out = options.pop('certificate_out') try: util.check_writable_file(certificate_out) except errors.FileError as e: raise errors.ValidationError(name='certificate-out', error=str(e)) else: certificate_out = None result = super(CertRetrieveOverride, self).forward(*args, **options) if certificate_out is not None: if options.get('chain', False): certs = result['result']['certificate_chain'] else: certs = [result['result']['certificate']] certs = (x509.load_der_x509_certificate(base64.b64decode(cert)) for cert in certs) x509.write_certificate_list(certs, certificate_out) return result
def load_der_certificate(cert): """Abstract load DER certificate by IPA version""" if version.NUM_VERSION < 40600: return x509.load_certificate(cert, x509.DER) else: return x509.load_der_x509_certificate(cert)