use of javax.net.ssl.X509KeyManager in project iaf by ibissource.
the class ApiListenerServletTest method createJWT.
private String createJWT() throws Exception {
JWSHeader jwsHeader = new JWSHeader.Builder(JWSAlgorithm.RS256).build();
JWTClaimsSet.Builder builder = new JWTClaimsSet.Builder();
builder.issuer("JWTPipeTest");
builder.subject("UnitTest");
builder.audience("Framework");
builder.jwtID("1234");
SignedJWT signedJWT = new SignedJWT(jwsHeader, builder.build());
KeyStore keystore = PkiUtil.createKeyStore(TestFileUtils.getTestFileURL("/JWT/jwt_keystore.p12"), "geheim", KeystoreType.PKCS12, "Keys for signing");
KeyManager[] keymanagers = PkiUtil.createKeyManagers(keystore, "geheim", null);
X509KeyManager keyManager = (X509KeyManager) keymanagers[0];
PrivateKey privateKey = keyManager.getPrivateKey("1");
PublicKey publicKey = keystore.getCertificate("1").getPublicKey();
JWK jwk = new RSAKey.Builder((RSAPublicKey) publicKey).privateKey(privateKey).keyUse(KeyUse.SIGNATURE).keyOperations(Collections.singleton(KeyOperation.SIGN)).algorithm(JWSAlgorithm.RS256).keyStore(keystore).build();
DefaultJWSSignerFactory factory = new DefaultJWSSignerFactory();
JWSSigner jwsSigner = factory.createJWSSigner(jwk, JWSAlgorithm.RS256);
signedJWT.sign(jwsSigner);
return signedJWT.serialize();
}
use of javax.net.ssl.X509KeyManager in project qpid-broker-j by apache.
the class FileKeyStoreImpl method checkCertificateExpiry.
@Override
protected void checkCertificateExpiry() {
int expiryWarning = getCertificateExpiryWarnPeriod();
if (expiryWarning > 0) {
long currentTime = System.currentTimeMillis();
Date expiryTestDate = new Date(currentTime + (ONE_DAY * (long) expiryWarning));
try {
final java.security.KeyStore ks = getInitializedKeyStore(this);
char[] keyStoreCharPassword = getPassword() == null ? null : getPassword().toCharArray();
final KeyManagerFactory kmf = KeyManagerFactory.getInstance(_keyManagerFactoryAlgorithm);
kmf.init(ks, keyStoreCharPassword);
for (KeyManager km : kmf.getKeyManagers()) {
if (km instanceof X509KeyManager) {
X509KeyManager x509KeyManager = (X509KeyManager) km;
for (String alias : Collections.list(ks.aliases())) {
checkCertificatesExpiry(currentTime, expiryTestDate, x509KeyManager.getCertificateChain(alias));
}
}
}
} catch (GeneralSecurityException | IOException e) {
}
}
}
use of javax.net.ssl.X509KeyManager in project goodies by sonatype.
the class ClientSideCertTest method getFactory.
private static SSLSocketFactory getFactory(File pKeyFile, String pKeyPassword, String certAlias) throws Exception {
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
KeyStore keyStore = KeyStore.getInstance("JKS");
InputStream keyInput = new FileInputStream(pKeyFile);
keyStore.load(keyInput, pKeyPassword.toCharArray());
keyInput.close();
keyManagerFactory.init(keyStore, pKeyPassword.toCharArray());
// Replace the original KeyManagers with the AliasForcingKeyManager
KeyManager[] kms = keyManagerFactory.getKeyManagers();
for (int i = 0; i < kms.length; i++) {
if (kms[i] instanceof X509KeyManager) {
kms[i] = new AliasForcingKeyManager((X509KeyManager) kms[i], certAlias);
}
}
TrustManager[] _trustManagers = new TrustManager[] { new CustomTrustManager() };
SSLContext context;
try {
context = SSLContext.getInstance("TLS");
context.init(kms, _trustManagers, new SecureRandom());
} catch (GeneralSecurityException gse) {
throw new IllegalStateException(gse.getMessage());
}
HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
// context.init( kms, null, null );
return context.getSocketFactory();
}
use of javax.net.ssl.X509KeyManager in project tomcat by apache.
the class TesterSupport method getUser1KeyManagers.
protected static KeyManager[] getUser1KeyManagers() throws Exception {
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(getKeyStore(CLIENT_JKS), JKS_PASS.toCharArray());
KeyManager[] managers = kmf.getKeyManagers();
KeyManager manager;
for (int i = 0; i < managers.length; i++) {
manager = managers[i];
if (manager instanceof X509ExtendedKeyManager) {
managers[i] = new TrackingExtendedKeyManager((X509ExtendedKeyManager) manager);
} else if (manager instanceof X509KeyManager) {
managers[i] = new TrackingKeyManager((X509KeyManager) manager);
}
}
return managers;
}
use of javax.net.ssl.X509KeyManager in project tomcat by apache.
the class OpenSSLContext method addCertificate.
private void addCertificate(SSLHostConfigCertificate certificate) throws Exception {
var allocator = SegmentAllocator.ofScope(state.contextScope);
int index = getCertificateIndex(certificate);
// Load Server key and certificate
if (certificate.getCertificateFile() != null) {
// Set certificate
// SSLContext.setCertificate(state.ctx,
// SSLHostConfig.adjustRelativePath(certificate.getCertificateFile()),
// SSLHostConfig.adjustRelativePath(certificate.getCertificateKeyFile()),
// certificate.getCertificateKeyPassword(), getCertificateIndex(certificate));
var certificateFileNative = CLinker.toCString(SSLHostConfig.adjustRelativePath(certificate.getCertificateFile()), state.contextScope);
var certificateKeyFileNative = (certificate.getCertificateKeyFile() == null) ? certificateFileNative : CLinker.toCString(SSLHostConfig.adjustRelativePath(certificate.getCertificateKeyFile()), state.contextScope);
MemoryAddress bio;
MemoryAddress cert = MemoryAddress.NULL;
MemoryAddress key = MemoryAddress.NULL;
if (certificate.getCertificateFile().endsWith(".pkcs12")) {
// Load pkcs12
bio = BIO_new(BIO_s_file());
// (int)BIO_ctrl(b,BIO_C_SET_FILENAME, BIO_CLOSE|BIO_FP_READ,(char *)(name))
if (BIO_ctrl(bio, BIO_C_SET_FILENAME(), BIO_CLOSE() | BIO_FP_READ(), certificateFileNative) <= 0) {
BIO_free(bio);
log.error(sm.getString("openssl.errorLoadingCertificate", "[0]:" + certificate.getCertificateFile()));
return;
}
MemoryAddress p12 = d2i_PKCS12_bio(bio, MemoryAddress.NULL);
BIO_free(bio);
if (MemoryAddress.NULL.equals(p12)) {
log.error(sm.getString("openssl.errorLoadingCertificate", "[1]:" + certificate.getCertificateFile()));
return;
}
MemoryAddress passwordAddress = MemoryAddress.NULL;
int passwordLength = 0;
String callbackPassword = certificate.getCertificateKeyPassword();
if (callbackPassword != null && callbackPassword.length() > 0) {
MemorySegment password = CLinker.toCString(callbackPassword, state.contextScope);
passwordAddress = password.address();
passwordLength = (int) (password.byteSize() - 1);
}
if (PKCS12_verify_mac(p12, passwordAddress, passwordLength) <= 0) {
// Bad password
log.error(sm.getString("openssl.errorLoadingCertificate", "[2]:" + certificate.getCertificateFile()));
PKCS12_free(p12);
return;
}
MemorySegment certPointer = allocator.allocate(CLinker.C_POINTER);
MemorySegment keyPointer = allocator.allocate(CLinker.C_POINTER);
if (PKCS12_parse(p12, passwordAddress, keyPointer, certPointer, MemoryAddress.NULL) <= 0) {
log.error(sm.getString("openssl.errorLoadingCertificate", "[3]:" + certificate.getCertificateFile()));
PKCS12_free(p12);
return;
}
PKCS12_free(p12);
cert = MemoryAccess.getAddress(certPointer);
key = MemoryAccess.getAddress(keyPointer);
} else {
// Load key
bio = BIO_new(BIO_s_file());
// (int)BIO_ctrl(b,BIO_C_SET_FILENAME, BIO_CLOSE|BIO_FP_READ,(char *)(name))
if (BIO_ctrl(bio, BIO_C_SET_FILENAME(), BIO_CLOSE() | BIO_FP_READ(), certificateKeyFileNative) <= 0) {
BIO_free(bio);
log.error(sm.getString("openssl.errorLoadingCertificate", certificate.getCertificateKeyFile()));
return;
}
key = MemoryAddress.NULL;
for (int i = 0; i < 3; i++) {
try {
callbackPasswordTheadLocal.set(certificate.getCertificateKeyPassword());
key = PEM_read_bio_PrivateKey(bio, MemoryAddress.NULL, openSSLCallbackPassword, MemoryAddress.NULL);
} finally {
callbackPasswordTheadLocal.set(null);
}
if (!MemoryAddress.NULL.equals(key)) {
break;
}
BIO_ctrl(bio, BIO_CTRL_RESET(), 0, MemoryAddress.NULL);
}
BIO_free(bio);
if (MemoryAddress.NULL.equals(key)) {
if (!MemoryAddress.NULL.equals(OpenSSLLifecycleListener.enginePointer)) {
key = ENGINE_load_private_key(OpenSSLLifecycleListener.enginePointer, certificateKeyFileNative, MemoryAddress.NULL, MemoryAddress.NULL);
}
}
if (MemoryAddress.NULL.equals(key)) {
log.error(sm.getString("openssl.errorLoadingCertificate", certificate.getCertificateKeyFile()));
return;
}
// Load certificate
bio = BIO_new(BIO_s_file());
if (BIO_ctrl(bio, BIO_C_SET_FILENAME(), BIO_CLOSE() | BIO_FP_READ(), certificateFileNative) <= 0) {
BIO_free(bio);
log.error(sm.getString("openssl.errorLoadingCertificate", certificate.getCertificateFile()));
return;
}
try {
callbackPasswordTheadLocal.set(certificate.getCertificateKeyPassword());
cert = PEM_read_bio_X509_AUX(bio, MemoryAddress.NULL, openSSLCallbackPassword, MemoryAddress.NULL);
} finally {
callbackPasswordTheadLocal.set(null);
}
if (MemoryAddress.NULL.equals(cert) && /*int ERR_GET_REASON(unsigned long errcode) {
* if (ERR_SYSTEM_ERROR(errcode))
* return errcode & ERR_SYSTEM_MASK;
* return errcode & ERR_REASON_MASK;
*}
*# define ERR_SYSTEM_ERROR(errcode) (((errcode) & ERR_SYSTEM_FLAG) != 0)
*# define ERR_SYSTEM_FLAG ((unsigned int)INT_MAX + 1)
*# define ERR_SYSTEM_MASK ((unsigned int)INT_MAX)
*# define ERR_REASON_MASK 0X7FFFFF
*/
((ERR_peek_last_error() & 0X7FFFFF) == PEM_R_NO_START_LINE())) {
ERR_clear_error();
BIO_ctrl(bio, BIO_CTRL_RESET(), 0, MemoryAddress.NULL);
cert = d2i_X509_bio(bio, MemoryAddress.NULL);
}
BIO_free(bio);
if (MemoryAddress.NULL.equals(cert)) {
log.error(sm.getString("openssl.errorLoadingCertificate", certificate.getCertificateFile()));
return;
}
}
if (SSL_CTX_use_certificate(state.sslCtx, cert) <= 0) {
logLastError(allocator, "openssl.errorLoadingCertificate");
return;
}
if (SSL_CTX_use_PrivateKey(state.sslCtx, key) <= 0) {
logLastError(allocator, "openssl.errorLoadingPrivateKey");
return;
}
if (SSL_CTX_check_private_key(state.sslCtx) <= 0) {
logLastError(allocator, "openssl.errorPrivateKeyCheck");
return;
}
// Try to read DH parameters from the (first) SSLCertificateFile
if (index == SSL_AIDX_RSA) {
bio = BIO_new_file(certificateFileNative, CLinker.toCString("r", state.contextScope));
var dh = PEM_read_bio_DHparams(bio, MemoryAddress.NULL, MemoryAddress.NULL, MemoryAddress.NULL);
BIO_free(bio);
// SSL_CTX_ctrl(sslCtx,SSL_CTRL_SET_TMP_DH,0,(char *)(dh))
if (!MemoryAddress.NULL.equals(dh)) {
SSL_CTX_ctrl(state.sslCtx, SSL_CTRL_SET_TMP_DH(), 0, dh);
DH_free(dh);
}
}
// Similarly, try to read the ECDH curve name from SSLCertificateFile...
bio = BIO_new_file(certificateFileNative, CLinker.toCString("r", state.contextScope));
var ecparams = PEM_read_bio_ECPKParameters(bio, MemoryAddress.NULL, MemoryAddress.NULL, MemoryAddress.NULL);
BIO_free(bio);
if (!MemoryAddress.NULL.equals(ecparams)) {
int nid = EC_GROUP_get_curve_name(ecparams);
var eckey = EC_KEY_new_by_curve_name(nid);
// # define SSL_CTX_set_tmp_ecdh(sslCtx,ecdh) \
// SSL_CTX_ctrl(sslCtx,SSL_CTRL_SET_TMP_ECDH,0,(char *)(ecdh))
SSL_CTX_ctrl(state.sslCtx, SSL_CTRL_SET_TMP_ECDH(), 0, eckey);
EC_KEY_free(eckey);
EC_GROUP_free(ecparams);
}
// Set callback for DH parameters
MemoryAddress openSSLCallbackTmpDH = CLinker.getInstance().upcallStub(openSSLCallbackTmpDHHandle, openSSLCallbackTmpDHFunctionDescriptor, state.contextScope);
SSL_CTX_set_tmp_dh_callback(state.sslCtx, openSSLCallbackTmpDH);
// Set certificate chain file
if (certificate.getCertificateChainFile() != null) {
var certificateChainFileNative = CLinker.toCString(SSLHostConfig.adjustRelativePath(certificate.getCertificateChainFile()), state.contextScope);
// SSLHostConfig.adjustRelativePath(certificate.getCertificateChainFile()), false);
if (SSL_CTX_use_certificate_chain_file(state.sslCtx, certificateChainFileNative) <= 0) {
log.error(sm.getString("openssl.errorLoadingCertificate", certificate.getCertificateChainFile()));
}
}
// Set revocation
// SSLContext.setCARevocation(state.ctx,
// SSLHostConfig.adjustRelativePath(
// sslHostConfig.getCertificateRevocationListFile()),
// SSLHostConfig.adjustRelativePath(
// sslHostConfig.getCertificateRevocationListPath()));
MemoryAddress certificateStore = SSL_CTX_get_cert_store(state.sslCtx);
if (sslHostConfig.getCertificateRevocationListFile() != null) {
MemoryAddress x509Lookup = X509_STORE_add_lookup(certificateStore, X509_LOOKUP_file());
var certificateRevocationListFileNative = CLinker.toCString(SSLHostConfig.adjustRelativePath(sslHostConfig.getCertificateRevocationListFile()), state.contextScope);
// X509_LOOKUP_ctrl(lookup,X509_L_FILE_LOAD,file,type,NULL)
if (X509_LOOKUP_ctrl(x509Lookup, X509_L_FILE_LOAD(), certificateRevocationListFileNative, X509_FILETYPE_PEM(), MemoryAddress.NULL) <= 0) {
log.error(sm.getString("openssl.errorLoadingCertificateRevocationList", sslHostConfig.getCertificateRevocationListFile()));
}
}
if (sslHostConfig.getCertificateRevocationListPath() != null) {
MemoryAddress x509Lookup = X509_STORE_add_lookup(certificateStore, X509_LOOKUP_hash_dir());
var certificateRevocationListPathNative = CLinker.toCString(SSLHostConfig.adjustRelativePath(sslHostConfig.getCertificateRevocationListPath()), state.contextScope);
// X509_LOOKUP_ctrl(lookup,X509_L_ADD_DIR,path,type,NULL)
if (X509_LOOKUP_ctrl(x509Lookup, X509_L_ADD_DIR(), certificateRevocationListPathNative, X509_FILETYPE_PEM(), MemoryAddress.NULL) <= 0) {
log.error(sm.getString("openssl.errorLoadingCertificateRevocationList", sslHostConfig.getCertificateRevocationListPath()));
}
}
X509_STORE_set_flags(certificateStore, X509_V_FLAG_CRL_CHECK() | X509_V_FLAG_CRL_CHECK_ALL());
} else {
String alias = certificate.getCertificateKeyAlias();
X509KeyManager x509KeyManager = certificate.getCertificateKeyManager();
if (alias == null) {
alias = "tomcat";
}
X509Certificate[] chain = x509KeyManager.getCertificateChain(alias);
if (chain == null) {
alias = findAlias(x509KeyManager, certificate);
chain = x509KeyManager.getCertificateChain(alias);
}
PrivateKey key = x509KeyManager.getPrivateKey(alias);
StringBuilder sb = new StringBuilder(BEGIN_KEY);
sb.append(Base64.getMimeEncoder(64, new byte[] { '\n' }).encodeToString(key.getEncoded()));
sb.append(END_KEY);
// SSLContext.setCertificateRaw(state.ctx, chain[0].getEncoded(),
// sb.toString().getBytes(StandardCharsets.US_ASCII),
// getCertificateIndex(certificate));
var rawCertificate = allocator.allocateArray(CLinker.C_CHAR, chain[0].getEncoded());
var rawCertificatePointer = allocator.allocate(CLinker.C_POINTER, rawCertificate);
var rawKey = allocator.allocateArray(CLinker.C_CHAR, sb.toString().getBytes(StandardCharsets.US_ASCII));
var x509cert = d2i_X509(MemoryAddress.NULL, rawCertificatePointer, rawCertificate.byteSize());
if (MemoryAddress.NULL.equals(x509cert)) {
logLastError(allocator, "openssl.errorLoadingCertificate");
return;
}
var bio = BIO_new(BIO_s_mem());
BIO_write(bio, rawKey.address(), (int) rawKey.byteSize());
MemoryAddress privateKeyAddress = PEM_read_bio_PrivateKey(bio, MemoryAddress.NULL, MemoryAddress.NULL, MemoryAddress.NULL);
BIO_free(bio);
if (MemoryAddress.NULL.equals(privateKeyAddress)) {
logLastError(allocator, "openssl.errorLoadingPrivateKey");
return;
}
if (SSL_CTX_use_certificate(state.sslCtx, x509cert) <= 0) {
logLastError(allocator, "openssl.errorLoadingCertificate");
return;
}
if (SSL_CTX_use_PrivateKey(state.sslCtx, privateKeyAddress) <= 0) {
logLastError(allocator, "openssl.errorLoadingPrivateKey");
return;
}
if (SSL_CTX_check_private_key(state.sslCtx) <= 0) {
logLastError(allocator, "openssl.errorPrivateKeyCheck");
return;
}
// Set callback for DH parameters
MemoryAddress openSSLCallbackTmpDH = CLinker.getInstance().upcallStub(openSSLCallbackTmpDHHandle, openSSLCallbackTmpDHFunctionDescriptor, state.contextScope);
SSL_CTX_set_tmp_dh_callback(state.sslCtx, openSSLCallbackTmpDH);
for (int i = 1; i < chain.length; i++) {
// SSLContext.addChainCertificateRaw(state.ctx, chain[i].getEncoded());
var rawCertificateChain = allocator.allocateArray(CLinker.C_CHAR, chain[i].getEncoded());
var rawCertificateChainPointer = allocator.allocate(CLinker.C_POINTER, rawCertificateChain);
var x509certChain = d2i_X509(MemoryAddress.NULL, rawCertificateChainPointer, rawCertificateChain.byteSize());
if (MemoryAddress.NULL.equals(x509certChain)) {
logLastError(allocator, "openssl.errorLoadingCertificate");
return;
}
// # define SSL_CTX_add0_chain_cert(sslCtx,x509) SSL_CTX_ctrl(sslCtx,SSL_CTRL_CHAIN_CERT,0,(char *)(x509))
if (SSL_CTX_ctrl(state.sslCtx, SSL_CTRL_CHAIN_CERT(), 0, x509certChain) <= 0) {
logLastError(allocator, "openssl.errorAddingCertificate");
return;
}
}
}
}
Aggregations