Exemple #1
0
    def __init__(self, protocol):
        try:
            self._protocol_name = _PROTOCOL_NAMES[protocol]
        except KeyError:
            raise ValueError("invalid protocol version")

        if protocol == PROTOCOL_SSLv23:  # darjus: at least my Java does not let me use v2
            self._protocol_name = 'SSL'

        self.protocol = protocol
        self._check_hostname = False

        # defaults from _ssl.c
        self.options = OP_ALL | OP_NO_SSLv2 | OP_NO_SSLv3
        self._verify_flags = VERIFY_DEFAULT
        self._verify_mode = CERT_NONE
        self._ciphers = None

        self._trust_store = KeyStore.getInstance(KeyStore.getDefaultType())
        self._trust_store.load(None, None)

        self._key_store = KeyStore.getInstance(KeyStore.getDefaultType())
        self._key_store.load(None, None)

        self._key_managers = None

        self._server_name_callback = None
Exemple #2
0
def _get_openssl_key_manager(cert_file, key_file=None):
    paths = [key_file] if key_file else []
    paths.append(cert_file)

    # Go from Bouncy Castle API to Java's; a bit heavyweight for the Python dev ;)
    key_converter = JcaPEMKeyConverter().setProvider("BC")
    cert_converter = JcaX509CertificateConverter().setProvider("BC")

    private_key = None
    certs = []
    for path in paths:
        for br in _extract_readers(path):
            while True:
                obj = PEMParser(br).readObject()
                if obj is None:
                    break
                if isinstance(obj, PEMKeyPair):
                    private_key = key_converter.getKeyPair(obj).getPrivate()
                elif isinstance(obj, PrivateKeyInfo):
                    private_key = key_converter.getPrivateKey(obj)
                elif isinstance(obj, X509CertificateHolder):
                    certs.append(cert_converter.getCertificate(obj))

    assert private_key, "No private key loaded"
    key_store = KeyStore.getInstance(KeyStore.getDefaultType())
    key_store.load(None, None)
    key_store.setKeyEntry(str(uuid.uuid4()), private_key, [], certs)
    kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm())
    kmf.init(key_store, [])
    return kmf
Exemple #3
0
def _get_ca_certs_trust_manager(ca_certs):
    trust_store = KeyStore.getInstance(KeyStore.getDefaultType())
    trust_store.load(None, None)
    with open(ca_certs) as f:
        cf = CertificateFactory.getInstance("X.509")
        for cert in cf.generateCertificates(BufferedInputStream(f)):
            trust_store.setCertificateEntry(str(uuid.uuid4()), cert)

    tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
    tmf.init(trust_store)
    return tmf
Exemple #4
0
def _get_ca_certs_trust_manager(ca_certs):
    trust_store = KeyStore.getInstance(KeyStore.getDefaultType())
    trust_store.load(None, None)
    num_certs_installed = 0
    with open(ca_certs) as f:
        cf = CertificateFactory.getInstance("X.509")
        for cert in cf.generateCertificates(BufferedInputStream(f)):
            trust_store.setCertificateEntry(str(uuid.uuid4()), cert)
            num_certs_installed += 1
    tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
    tmf.init(trust_store)
    log.debug("Installed %s certificates", num_certs_installed, extra={"sock": "*"})
    return tmf
    def getKeychain(self, sign_keyname):
        """Get key and chain from a Keystore"""

        if not 'PYJASPER_KEYSTORE_FILE' in os.environ:
            raise ValueError('No keychain defined')

        password = list(os.environ.get('PYJASPER_KEYSTORE_PASSWORD', ''))
        keystore = KeyStore.getInstance(KeyStore.getDefaultType())
        keystore.load(open(os.environ['PYJASPER_KEYSTORE_FILE']), password)
        if not keystore.containsAlias(sign_keyname):
            raise ValueError('No key named %s' % sign_keyname)

        key = keystore.getKey(sign_keyname, password)
        chain = keystore.getCertificateChain(sign_keyname)
        return key, chain
Exemple #6
0
def _extract_certs_from_keystore_file(f, password):
    keystore = KeyStore.getInstance(KeyStore.getDefaultType())
    if password is None:  # default java keystore password is changeit
        password = '******'
    elif not isinstance(password, str):
        password = []

    keystore.load(BufferedInputStream(f), password)
    certs = []

    alias_iter = keystore.aliases()
    while alias_iter.hasMoreElements():
        alias = alias_iter.nextElement()
        certs.append(keystore.getCertificate(alias))

    return certs
Exemple #7
0
 def trustSpecificCertificate(self, pemCertificateFile, pemCertificateAlias):
         from java.io import BufferedInputStream, FileInputStream
         from java.security import KeyStore
         from java.security.cert import CertificateFactory, X509Certificate
         from javax.net.ssl import SSLContext, TrustManagerFactory
         
         fis = FileInputStream(pemCertificateFile)
         bis = BufferedInputStream(fis)
         ca = CertificateFactory.getInstance("X.509").generateCertificate(bis)
         ks = KeyStore.getInstance(KeyStore.getDefaultType())
         ks.load(None, None)
         ks.setCertificateEntry(pemCertificateAlias, ca)
         tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
         tmf.init(ks)
         context = SSLContext.getInstance("SSL")
         context.init(None, tmf.getTrustManagers(), None)
         SSLContext.setDefault(context)
Exemple #8
0
def _get_openssl_key_manager(cert_file=None, key_file=None, password=None, _key_store=None):
    certs, private_key = [], None

    if _key_store is None:
        _key_store = KeyStore.getInstance(KeyStore.getDefaultType())
        _key_store.load(None, None)

    if key_file is not None:
        certs, private_key = _extract_certs_for_paths([key_file], password)
        if private_key is None:
            from _socket import SSLError, SSL_ERROR_SSL
            raise SSLError(SSL_ERROR_SSL, "PEM lib (No private key loaded)")

    if cert_file is not None:
        _certs, _private_key = _extract_certs_for_paths([cert_file], password)
        private_key = _private_key if _private_key else private_key
        certs.extend(_certs)

        if not private_key:
            from _socket import SSLError, SSL_ERROR_SSL
            raise SSLError(SSL_ERROR_SSL, "PEM lib (No private key loaded)")

        keys_match = False
        for cert in certs:
            # TODO works for RSA only for now
            if not isinstance(cert.publicKey, RSAPublicKey) and isinstance(private_key, RSAPrivateCrtKey):
                keys_match = True
                continue

            if cert.publicKey.getModulus() == private_key.getModulus() \
                    and cert.publicKey.getPublicExponent() == private_key.getPublicExponent():
                keys_match = True
            else:
                keys_match = False

        if key_file is not None and not keys_match:
            from _socket import SSLError, SSL_ERROR_SSL
            raise SSLError(SSL_ERROR_SSL, "key values mismatch")

        _key_store.setKeyEntry(_str_hash_key_entry(private_key, *certs), private_key, [], certs)

    kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm())
    kmf.init(_key_store, [])
    return kmf
Exemple #9
0
    def __init__(self, protocol):
        protocol_name = _PROTOCOL_NAMES[protocol]
        if protocol == PROTOCOL_SSLv23:  # darjus: at least my Java does not let me use v2
            protocol_name = 'SSL'

        self.protocol = protocol
        self.check_hostname = False
        self.options = OP_ALL
        self.verify_flags = None
        self.verify_mode = CERT_NONE
        self._ciphers = None

        self._trust_store = KeyStore.getInstance(KeyStore.getDefaultType())
        self._trust_store.load(None, None)

        self._key_store = KeyStore.getInstance(KeyStore.getDefaultType())
        self._key_store.load(None, None)

        self._context = _JavaSSLContext.getInstance(protocol_name)
        self._key_managers = None
Exemple #10
0
    def __init__(self, protocol):
        protocol_name = _PROTOCOL_NAMES[protocol]
        if protocol == PROTOCOL_SSLv23:  # darjus: at least my Java does not let me use v2
            protocol_name = 'SSL'

        self.protocol = protocol
        self.check_hostname = False
        self.options = OP_ALL
        self.verify_flags = None
        self.verify_mode = CERT_NONE
        self._ciphers = None

        self._trust_store = KeyStore.getInstance(KeyStore.getDefaultType())
        self._trust_store.load(None, None)

        self._key_store = KeyStore.getInstance(KeyStore.getDefaultType())
        self._key_store.load(None, None)

        self._context = _JavaSSLContext.getInstance(protocol_name)
        self._key_managers = None
Exemple #11
0
    def __get_cert_from_p12(self, file, password=None):
        ks = KeyStore.getInstance("PKCS12")
        io = FileInputStream(file)
        if password is None:
            ks.load(io, None)
        else:
            ks.load(io, String(password).toCharArray())
        io.close()

        for alias in ks.aliases():
            if ks.isKeyEntry(alias):
                return ks.getCertificate(alias)
        return None
Exemple #12
0
    def getCN_of_AS(self ) : 
               try:
	                keyStore = KeyStore.getInstance("PKCS12")
                        pwdArray = [x for x in self.transportKeyStorePassword]
                        keyStore.load( FileInputStream(self.transportKeyStore), pwdArray)
                        alias = String( keyStore.aliases().nextElement())
		        cert =  keyStore.getCertificate(alias)
		        softwareStatementId = CertUtils.getCN(cert)
		        print "CN of AS-%s" % softwareStatementId
		        return softwareStatementId
               except:
                        print "Client Registration. Failed to get CN of AS from the transport keystore. Exception: ", sys.exc_info()[1]
                        return None
Exemple #13
0
def _get_openssl_key_manager(cert_file, key_file=None):
    paths = [key_file] if key_file else []
    paths.append(cert_file)
    private_key = None
    certs = []
    for path in paths:
        with closing(FileReader(path)) as reader:
            br = BufferedReader(reader)
            while True:
                obj = PEMReader(br).readObject()
                if obj is None:
                    break
                if isinstance(obj, KeyPair):
                    private_key = obj.getPrivate()
                elif isinstance(obj, X509Certificate):
                    certs.append(obj)

    key_store = KeyStore.getInstance(KeyStore.getDefaultType())
    key_store.load(None, None)
    key_store.setKeyEntry(str(uuid.uuid4()), private_key, [], certs)
    kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm())
    kmf.init(key_store, [])
    return kmf
Exemple #14
0
def test(param):
    #param=dict(map(lambda x:(str(x[0]),x[1]),param.iteritems()))

    jks_path = SSH.cloneAndGetLocalPath(param['jks'])
    jks_password = param['jksPassword']
    key_alias = param['keyAlias']
    key_password = param['keyPassword']
    hash_mac = hnapay_mac(param['data'])

    fis = FileInputStream(jks_path)
    jks = KeyStore.getInstance('JKS')
    jks.load(fis, list(jks_password))
    fis.close()
    sign_util = Signature.getInstance('SHA1withRSA')
    sign_util.initSign(jks.getKey(key_alias, list(key_password)))
    sign_util.update(bytearray(map(ord, hash_mac.encode('utf-8'))))
    signature = ''.join(
        map(
            lambda c: '{:02x}'.format((c + 1) * -1 ^ 0xFF)
            if c < 0 else '{:02x}'.format(c), sign_util.sign()))

    # data=param['data']
    return {'data': param['data'], 'signature': signature}
Exemple #15
0
        }
    }

    private C1448a() {
    }

    /* renamed from: e */
    private static SSLSocketFactory m8521e() {
        KeyStore keyStore;
        KeyStoreException e;
        C1454c cVar;
        NoSuchAlgorithmException e2;
        UnrecoverableKeyException e3;
        KeyManagementException e4;
        try {
            keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            try {
                keyStore.load(null, null);
            } catch (Exception e5) {
                e = e5;
                e.printStackTrace();
                cVar = new C1454c(keyStore);
                cVar.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
                return cVar;
            }
        } catch (Exception e6) {
            e = e6;
            keyStore = null;
            e.printStackTrace();
            cVar = new C1454c(keyStore);
            cVar.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
from java.io import FileInputStream
from java.io import FileOutputStream
from java.io import ByteArrayInputStream
from java.security import KeyStore
from java.security import KeyFactory
from java.security import PrivateKey
from java.security.cert import CertificateFactory
from java.security.cert import X509Certificate
from java.security.spec import PKCS8EncodedKeySpec
from javax.xml.bind import DatatypeConverter

print 'Install certificate %s to target %s' % (deployed.name, deployed.container.name)

# Load the keystore
print 'Loading keystore %s' % (deployed.container.keystore)
ks = KeyStore.getInstance(deployed.container.keystoreType)
ksfi = FileInputStream(deployed.container.keystore)

try:
    ks.load(ksfi, deployed.container.passphrase)

     # Load certificates (base64 encoded DER/PEM-encoded certificates)
     # http://docs.oracle.com/javase/7/docs/api/java/security/cert/CertificateFactory.html#generateCertificates(java.io.InputStream)
    print 'Loading the certificate(chain)'
    inStream = ByteArrayInputStream(DatatypeConverter.parseBase64Binary(String(deployed.certificate)))
    cf = CertificateFactory.getInstance("X.509")
    chain = cf.generateCertificates(inStream).toArray(jarray.zeros(0, java.security.cert.Certificate))

    # Save the private key entry (base64 PKCS8 DER encoded)
    print 'Storing key/certificate %s (alias=%s) in keystore %s' % (deployed.name, deployed.alias, deployed.container.keystore)
    kf = KeyFactory.getInstance(deployed.keyAlgorithm)