def test_client_chain_certificate(self): """ A certificate chain in the *client-certificate* section of in the kube configuration file is used to configure the TLS context used when connecting to the API server. """ def sign_ca_cert(key, requestObject, dn): from OpenSSL.crypto import X509, X509Extension from twisted.internet.ssl import Certificate req = requestObject.original cert = X509() dn._copyInto(cert.get_issuer()) cert.set_subject(req.get_subject()) cert.set_pubkey(req.get_pubkey()) cert.gmtime_adj_notBefore(0) cert.gmtime_adj_notAfter(60 * 60) cert.set_serial_number(1) cert.add_extensions([ X509Extension(b"basicConstraints", True, b"CA:TRUE"), # Not necessarily a good way to populate subjectAltName but it # quiets the deprecation warning we get from service_identity. X509Extension(b"subjectAltName", True, b"DNS:" + dn.commonName), ]) cert.sign(key.original, "sha256") return Certificate(cert) ca_key = KeyPair.generate() ca_req = ca_key.requestObject(DN(commonName="kubernetes")) ca_cert = sign_ca_cert(ca_key, ca_req, DN(commonName="kubernetes")) intermediate_key = KeyPair.generate() intermediate_req = intermediate_key.requestObject(DN(commonName="intermediate")) intermediate_cert = sign_ca_cert(ca_key, intermediate_req, DN(commonName="kubernetes")) client_key = KeyPair.generate() client_req = client_key.requestObject(DN(commonName="client")) client_cert = intermediate_key.signRequestObject(DN(commonName="intermediate"), client_req, 1) chain = b"".join([ client_cert.dumpPEM(), intermediate_cert.dumpPEM(), ]) FilePath("ca.key").setContent(ca_key.dump(FILETYPE_PEM)) FilePath("ca.crt").setContent(ca_cert.dump(FILETYPE_PEM)) FilePath("intermediate.crt").setContent(intermediate_cert.dump(FILETYPE_PEM)) FilePath("client.key").setContent(client_key.dump(FILETYPE_PEM)) FilePath("client.crt").setContent(client_cert.dump(FILETYPE_PEM)) FilePath("chain.crt").setContent(chain) config = self.write_config(ca_cert, chain, client_key) kubernetes = lambda reactor: network_kubernetes_from_context( reactor, "foo-ctx", path=config, ) return self.check_tls_config(ca_key, ca_cert, kubernetes)
def pems(): for i in count(): key = KeyPair.generate() cert = key.selfSignedCert(i, commonName=u"lae_automation testing") pem = PrivateCertificate.fromCertificateAndKeyPair(cert, key).dumpPEM() yield pem.decode("ascii")
def getServerContext(self): """ Generate a new L{OpenSSL.SSL.Context} object configured to use a certificate signed by C{self.ca} and only accept connections from peers which are also using a certificate signed by C{self.ca}. """ # Generate a new key for the server and have the CA sign a certificate # for it. key = KeyPair.generate(size=512) req = key.certificateRequest(DN(commonName='localhost')) certData = self.ca.signCertificateRequest(req, lambda dn: True, 1) cert = PrivateCertificate.load(certData, key) # Use the new key/certificate context = Context(TLSv1_METHOD) context.use_privatekey(key.original) context.use_certificate(cert.original) context.check_privatekey() # Allow peer certificates signed by the CA store = context.get_cert_store() store.add_cert(self.ca.original) # Verify the peer certificate and require that they have one. def verify(conn, cert, errno, depth, preverify_ok): return preverify_ok context.set_verify(VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT, verify) return context
def clientCertFor(name): signingCert = getCAPrivateCert() clientKey = KeyPair.generate(size=4096) csr = clientKey.requestObject(DN(CN=name), "sha1") clientCert = signingCert.signRequestObject( csr, serialNumber=1, digestAlgorithm="sha1") return PrivateCertificate.fromCertificateAndKeyPair(clientCert, clientKey)
def generate_keypair(): """ Create a new 4096-bit RSA key pair. """ return FlockerKeyPair( keypair=KeyPair.generate(crypto.TYPE_RSA, size=4096) )
def flocker_keypair(): """ Create a new 4096-bit RSA key pair. """ return ComparableKeyPair( keypair=KeyPair.generate(crypto.TYPE_RSA, size=4096) )
def testBadCertRequestSubject(self): kp = KeyPair.generate() subject = DistinguishedName(commonName='HACKERX', localityName='INTERNETANIA') reqobj = kp.requestObject(subject) fakereq = kp.requestObject(subject) ssigned = kp.signRequestObject(subject, fakereq, 1) certpair = PrivateCertificate.fromCertificateAndKeyPair fakecert = certpair(ssigned, kp) apc = self.serverService2.certificateStorage.addPrivateCertificate def _2(secured): D = secured.callRemote( q2q.Sign, certificate_request=reqobj, password='******') def _1(dcert): cert = dcert['certificate'] privcert = certpair(cert, kp) apc(str(self.fromAddress), privcert) return D.addCallback(_1) d = self.serverService2.getSecureConnection( self.fromAddress, self.fromAddress.domainAddress(), authorize=False, usePrivateCertificate=fakecert, ).addCallback(_2) def unexpectedSuccess(result): self.fail("Expected BadCertificateRequest, got %r" % (result,)) def expectedFailure(err): err.trap(q2q.BadCertificateRequest) d.addCallbacks(unexpectedSuccess, expectedFailure) return d
def clientCertFor(p_name): l_signingCert = getCAPrivateCert() l_clientKey = KeyPair.generate(size = 4096) l_csr = l_clientKey.requestObject(DN(CN = p_name), "sha1") l_clientCert = l_signingCert.signRequestObject( l_csr, serialNumber = 1, digestAlgorithm = "sha1") return PrivateCertificate.fromCertificateAndKeyPair(l_clientCert, l_clientKey)
def clientCertFor(name): signingCert = getCAPrivateCert() clientKey = KeyPair.generate(size=4096) csr = clientKey.requestObject(DN(CN=name), "sha1") clientCert = signingCert.signRequestObject(csr, serialNumber=1, digestAlgorithm="sha1") return PrivateCertificate.fromCertificateAndKeyPair(clientCert, clientKey)
def clientCertFor(p_name): l_signingCert = getCAPrivateCert() l_clientKey = KeyPair.generate(size=4096) l_csr = l_clientKey.requestObject(DN(CN=p_name), "sha1") l_clientCert = l_signingCert.signRequestObject(l_csr, serialNumber=1, digestAlgorithm="sha1") return PrivateCertificate.fromCertificateAndKeyPair( l_clientCert, l_clientKey)
def getCAPrivateCert(): l_privatePath = FilePath(b"ca-private-cert.pem") if l_privatePath.exists(): return PrivateCertificate.loadPEM(l_privatePath.getContent()) else: l_caKey = KeyPair.generate(size=4096) l_caCert = l_caKey.selfSignedCert(1, CN="the-authority") l_privatePath.setContent(l_caCert.dumpPEM()) return l_caCert
def getCAPrivateCert(): privatePath = FilePath(b"ca-private-cert.pem") if privatePath.exists(): return PrivateCertificate.loadPEM(privatePath.getContent()) else: caKey = KeyPair.generate(size=4096) caCert = caKey.selfSignedCert(1, CN="the-authority") privatePath.setContent(caCert.dumpPEM()) return caCert
def makeCert(cn): """ Create a self-signed cert. """ sharedDN = DN(CN=cn) key = KeyPair.generate() cr = key.certificateRequest(sharedDN) sscrd = key.signCertificateRequest(sharedDN, cr, lambda dn: True, 1) return key.newCertificate(sscrd)
def new_tahoe_configuration(deploy_config, bucketname, key_prefix, publichost, privatehost, introducer_port, storageserver_port): """ Create brand new secrets and configuration for use by an introducer/storage pair. """ base_name = dict( organizationName=b"Least Authority Enterprises", organizationalUnitName=b"S4", emailAddress=bucketname, ) keypair = KeyPair.generate(size=2048) introducer_certificate = keypair.selfSignedCert( serialNumber=1, commonName=b"introducer", **base_name ) storage_certificate = keypair.selfSignedCert( serialNumber=1, commonName=b"storage", **base_name ) def pem(key, cert): return b"\n".join((key.dump(FILETYPE_PEM), cert.dump(FILETYPE_PEM))) introducer_tub = Tub(certData=pem(keypair, introducer_certificate)) introducer_tub.setLocation("{}:{}".format(publichost, introducer_port)) storage_tub = Tub(certData=pem(keypair, storage_certificate)) return marshal_tahoe_configuration( introducer_pem=introducer_tub.getCertData().strip(), storage_pem=storage_tub.getCertData().strip(), storage_privkey=keyutil.make_keypair()[0] + b"\n", introducer_port=introducer_port, storageserver_port=storageserver_port, bucket_name=bucketname, key_prefix=key_prefix, publichost=publichost, privatehost=privatehost, # The object of the reference is irrelevant. The furl will # get hooked up to something else when Tahoe really runs. # Just need to pass something _weak referenceable_! Which # rules out a lot of things... introducer_furl=introducer_tub.registerReference(introducer_tub), s3_access_key_id=deploy_config.s3_access_key_id, s3_secret_key=deploy_config.s3_secret_key, log_gatherer_furl=deploy_config.log_gatherer_furl, stats_gatherer_furl=deploy_config.stats_gatherer_furl, )
def makeCertRequest(cn): """ Create a certificate request with the given common name. @param cn: Common Name to use in certificate request. @type cn: L{bytes} @return: Certificate request. @rtype: L{CertificateRequest} """ key = KeyPair.generate() return key.certificateRequest(DN(CN=cn))
def createSSLCertificate(opts): sslopt = {} for x, y in (('country', 'C'), ('state', 'ST'), ('city', 'L'), ('organization', 'O'), ('unit', 'OU'), ('hostname', 'CN'), ('email', 'emailAddress')): sslopt[y] = opts[x] serialNumber = int(opts['serial-number']) ssc = KeyPair.generate().selfSignedCert(serialNumber, **sslopt) file(opts['filename'], 'w').write(ssc.dumpPEM()) if not opts['quiet']: print 'Wrote SSL certificate:' print ssc.inspect() return ssc
def createCertificate(): # this is copied from test_sslverify.py dn = DistinguishedName(commonName="newpb_thingy") keypair = KeyPair.generate(size=2048) req = keypair.certificateRequest(dn, digestAlgorithm="sha256") certData = keypair.signCertificateRequest(dn, req, lambda dn: True, 1, # serial number digestAlgorithm="sha256", ) cert = keypair.newCertificate(certData) #opts = cert.options() # 'opts' can be given to reactor.listenSSL, or to transport.startTLS return cert
def makeCert(cn): """ Create a self-signed certificate with the given common name. @param cn: Common Name to use in certificate. @type cn: L{bytes} @return: Self-signed certificate. @rtype: L{Certificate<twisted.internet.ssl.Certificate>} """ sharedDN = DN(CN=cn) key = KeyPair.generate() cr = key.certificateRequest(sharedDN) sscrd = key.signCertificateRequest(sharedDN, cr, lambda dn: True, 1) return key.newCertificate(sscrd)
def createCertificate(): # this is copied from test_sslverify.py dn = DistinguishedName(commonName="newpb_thingy") keypair = KeyPair.generate(size=2048) req = keypair.certificateRequest(dn, digestAlgorithm="sha256") certData = keypair.signCertificateRequest( dn, req, lambda dn: True, 1, # serial number digestAlgorithm="sha256", ) cert = keypair.newCertificate(certData) #opts = cert.options() # 'opts' can be given to reactor.listenSSL, or to transport.startTLS return cert
def createSSLCertificate(opts): sslopt = {} for x, y in (('country','C'), ('state', 'ST'), ('city', 'L'), ('organization', 'O'), ('unit', 'OU'), ('hostname', 'CN'), ('email','emailAddress')): sslopt[y] = opts[x] serialNumber = int(opts['serial-number']) ssc = KeyPair.generate().selfSignedCert(serialNumber, **sslopt) file(opts['filename'], 'w').write(ssc.dumpPEM()) if not opts['quiet']: print 'Wrote SSL certificate:' print ssc.inspect() return ssc
def createDatabase(siteStore): """ Populate the given Store with a TCPPort and SSLPort. """ factory = WebSite(store=siteStore) installOn(factory, siteStore) installOn(TCPPort(store=siteStore, portNumber=TCP_PORT, factory=factory), siteStore) certificatePath = siteStore.newFilePath('certificate') key = KeyPair.generate() cert = key.selfSignedCert(1) certificatePath.setContent( cert.dump(FILETYPE_PEM) + key.dump(FILETYPE_PEM)) installOn( SSLPort(store=siteStore, portNumber=SSL_PORT, certificatePath=certificatePath, factory=factory), siteStore)
def createDatabase(siteStore): """ Populate the given Store with a TCPPort and SSLPort. """ factory = WebSite(store=siteStore) installOn(factory, siteStore) installOn( TCPPort(store=siteStore, portNumber=TCP_PORT, factory=factory), siteStore) certificatePath = siteStore.newFilePath('certificate') key = KeyPair.generate() cert = key.selfSignedCert(1) certificatePath.setContent( cert.dump(FILETYPE_PEM) + key.dump(FILETYPE_PEM)) installOn( SSLPort(store=siteStore, portNumber=SSL_PORT, certificatePath=certificatePath, factory=factory), siteStore)
def testBadCertRequestSubject(self): kp = KeyPair.generate() subject = DistinguishedName(commonName='HACKERX', localityName='INTERNETANIA') reqobj = kp.requestObject(subject) fakereq = kp.requestObject(subject) ssigned = kp.signRequestObject(subject, fakereq, 1) certpair = PrivateCertificate.fromCertificateAndKeyPair fakecert = certpair(ssigned, kp) apc = self.serverService2.certificateStorage.addPrivateCertificate def _2(secured): D = secured.callRemote(q2q.Sign, certificate_request=reqobj, password='******') def _1(dcert): cert = dcert['certificate'] privcert = certpair(cert, kp) apc(str(self.fromAddress), privcert) return D.addCallback(_1) d = self.serverService2.getSecureConnection( self.fromAddress, self.fromAddress.domainAddress(), authorize=False, usePrivateCertificate=fakecert, ).addCallback(_2) def unexpectedSuccess(result): self.fail("Expected BadCertificateRequest, got %r" % (result, )) def expectedFailure(err): err.trap(q2q.BadCertificateRequest) d.addCallbacks(unexpectedSuccess, expectedFailure) return d
def makeCertRequest(cn): """ Create a certificate request. """ key = KeyPair.generate() return key.certificateRequest(DN(CN=cn))
def generateKey(): return KeyPair.generate()
""" This benchmarks runs a trivial Twisted TLSv1 echo server using a certificate with a 2048 bit RSA key as well as a client which pumps as much data to that server as it can in a fixed period of time. """ from twisted.internet.protocol import ServerFactory from twisted.internet.endpoints import SSL4ClientEndpoint from twisted.internet.ssl import ( DN, KeyPair, PrivateCertificate, CertificateOptions) from twisted.protocols.wire import Echo from tcp_throughput import Client, driver # Generate a new self-signed certificate key = KeyPair.generate(size=2048) req = key.certificateRequest(DN(commonName='localhost'), digestAlgorithm='sha1') cert = PrivateCertificate.load( key.signCertificateRequest( DN(commonName='localhost'), req, lambda dn: True, 1, digestAlgorithm='sha1'), key) def main(reactor, duration): chunkSize = 16384 server = ServerFactory() server.protocol = Echo port = reactor.listenSSL(0, server, cert.options()) client = Client(