use of java.security.cert.X509Certificate in project hbase by apache.
the class KeyStoreTestUtil method setupSSLConfig.
/**
* Performs complete setup of SSL configuration in preparation for testing an
* SSLFactory. This includes keys, certs, keystores, truststores, the server
* SSL configuration file, the client SSL configuration file, and the master
* configuration file read by the SSLFactory.
*
* @param keystoresDir String directory to save keystores
* @param sslConfDir String directory to save SSL configuration files
* @param conf Configuration master configuration to be used by an SSLFactory,
* which will be mutated by this method
* @param useClientCert boolean true to make the client present a cert in the
* SSL handshake
*/
public static void setupSSLConfig(String keystoresDir, String sslConfDir, Configuration conf, boolean useClientCert) throws Exception {
String clientKS = keystoresDir + "/clientKS.jks";
String clientPassword = "clientP";
String serverKS = keystoresDir + "/serverKS.jks";
String serverPassword = "serverP";
String trustKS = keystoresDir + "/trustKS.jks";
String trustPassword = "trustP";
File sslClientConfFile = new File(sslConfDir + "/ssl-client.xml");
File sslServerConfFile = new File(sslConfDir + "/ssl-server.xml");
Map<String, X509Certificate> certs = new HashMap<>();
if (useClientCert) {
KeyPair cKP = KeyStoreTestUtil.generateKeyPair("RSA");
X509Certificate cCert = KeyStoreTestUtil.generateCertificate("CN=localhost, O=client", cKP, 30, "SHA1withRSA");
KeyStoreTestUtil.createKeyStore(clientKS, clientPassword, "client", cKP.getPrivate(), cCert);
certs.put("client", cCert);
}
KeyPair sKP = KeyStoreTestUtil.generateKeyPair("RSA");
X509Certificate sCert = KeyStoreTestUtil.generateCertificate("CN=localhost, O=server", sKP, 30, "SHA1withRSA");
KeyStoreTestUtil.createKeyStore(serverKS, serverPassword, "server", sKP.getPrivate(), sCert);
certs.put("server", sCert);
KeyStoreTestUtil.createTrustStore(trustKS, trustPassword, certs);
Configuration clientSSLConf = createClientSSLConfig(clientKS, clientPassword, clientPassword, trustKS);
Configuration serverSSLConf = createServerSSLConfig(serverKS, serverPassword, serverPassword, trustKS);
saveConfig(sslClientConfFile, clientSSLConf);
saveConfig(sslServerConfFile, serverSSLConf);
conf.set(SSLFactory.SSL_HOSTNAME_VERIFIER_KEY, "ALLOW_ALL");
conf.set(SSLFactory.SSL_CLIENT_CONF_KEY, sslClientConfFile.getName());
conf.set(SSLFactory.SSL_SERVER_CONF_KEY, sslServerConfFile.getName());
conf.setBoolean(SSLFactory.SSL_REQUIRE_CLIENT_CERT_KEY, useClientCert);
}
use of java.security.cert.X509Certificate in project tomcat by apache.
the class SSLAuthenticator method doAuthenticate.
// --------------------------------------------------------- Public Methods
/**
* Authenticate the user by checking for the existence of a certificate
* chain, validating it against the trust manager for the connector and then
* validating the user's identity against the configured Realm.
*
* @param request Request we are processing
* @param response Response we are creating
*
* @exception IOException if an input/output error occurs
*/
@Override
protected boolean doAuthenticate(Request request, HttpServletResponse response) throws IOException {
// TODO make this a configurable attribute (in SingleSignOn??)
if (checkForCachedAuthentication(request, response, false)) {
return true;
}
// Retrieve the certificate chain for this client
if (containerLog.isDebugEnabled()) {
containerLog.debug(" Looking up certificates");
}
X509Certificate[] certs = getRequestCertificates(request);
if ((certs == null) || (certs.length < 1)) {
if (containerLog.isDebugEnabled()) {
containerLog.debug(" No certificates included with this request");
}
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, sm.getString("authenticator.certificates"));
return false;
}
// Authenticate the specified certificate chain
Principal principal = context.getRealm().authenticate(certs);
if (principal == null) {
if (containerLog.isDebugEnabled()) {
containerLog.debug(" Realm.authenticate() returned false");
}
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, sm.getString("authenticator.unauthorized"));
return false;
}
// Cache the principal (if requested) and record this authentication
register(request, response, principal, HttpServletRequest.CLIENT_CERT_AUTH, null, null);
return true;
}
use of java.security.cert.X509Certificate in project tomcat by apache.
the class AuthenticatorBase method invoke.
// --------------------------------------------------------- Public Methods
/**
* Enforce the security restrictions in the web application deployment
* descriptor of our associated Context.
*
* @param request
* Request to be processed
* @param response
* Response to be processed
*
* @exception IOException
* if an input/output error occurs
* @exception ServletException
* if thrown by a processing element
*/
@Override
public void invoke(Request request, Response response) throws IOException, ServletException {
if (log.isDebugEnabled()) {
log.debug("Security checking request " + request.getMethod() + " " + request.getRequestURI());
}
// Have we got a cached authenticated Principal to record?
if (cache) {
Principal principal = request.getUserPrincipal();
if (principal == null) {
Session session = request.getSessionInternal(false);
if (session != null) {
principal = session.getPrincipal();
if (principal != null) {
if (log.isDebugEnabled()) {
log.debug("We have cached auth type " + session.getAuthType() + " for principal " + principal);
}
request.setAuthType(session.getAuthType());
request.setUserPrincipal(principal);
}
}
}
}
boolean authRequired = isContinuationRequired(request);
// The Servlet may specify security constraints through annotations.
// Ensure that they have been processed before constraints are checked
Wrapper wrapper = request.getWrapper();
if (wrapper != null) {
wrapper.servletSecurityAnnotationScan();
}
Realm realm = this.context.getRealm();
// Is this request URI subject to a security constraint?
SecurityConstraint[] constraints = realm.findSecurityConstraints(request, this.context);
AuthConfigProvider jaspicProvider = getJaspicProvider();
if (jaspicProvider != null) {
authRequired = true;
}
if (constraints == null && !context.getPreemptiveAuthentication() && !authRequired) {
if (log.isDebugEnabled()) {
log.debug(" Not subject to any constraint");
}
getNext().invoke(request, response);
return;
}
// or browsers as caching can provide a security hole
if (constraints != null && disableProxyCaching && !"POST".equalsIgnoreCase(request.getMethod())) {
if (securePagesWithPragma) {
// Note: These can cause problems with downloading files with IE
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
} else {
response.setHeader("Cache-Control", "private");
}
response.setHeader("Expires", DATE_ONE);
}
if (constraints != null) {
// Enforce any user data constraint for this security constraint
if (log.isDebugEnabled()) {
log.debug(" Calling hasUserDataPermission()");
}
if (!realm.hasUserDataPermission(request, response, constraints)) {
if (log.isDebugEnabled()) {
log.debug(" Failed hasUserDataPermission() test");
}
/*
* ASSERT: Authenticator already set the appropriate HTTP status
* code, so we do not have to do anything special
*/
return;
}
}
// Since authenticate modifies the response on failure,
// we have to check for allow-from-all first.
boolean hasAuthConstraint = false;
if (constraints != null) {
hasAuthConstraint = true;
for (int i = 0; i < constraints.length && hasAuthConstraint; i++) {
if (!constraints[i].getAuthConstraint()) {
hasAuthConstraint = false;
} else if (!constraints[i].getAllRoles() && !constraints[i].getAuthenticatedUsers()) {
String[] roles = constraints[i].findAuthRoles();
if (roles == null || roles.length == 0) {
hasAuthConstraint = false;
}
}
}
}
if (!authRequired && hasAuthConstraint) {
authRequired = true;
}
if (!authRequired && context.getPreemptiveAuthentication()) {
authRequired = request.getCoyoteRequest().getMimeHeaders().getValue("authorization") != null;
}
if (!authRequired && context.getPreemptiveAuthentication() && HttpServletRequest.CLIENT_CERT_AUTH.equals(getAuthMethod())) {
X509Certificate[] certs = getRequestCertificates(request);
authRequired = certs != null && certs.length > 0;
}
JaspicState jaspicState = null;
if (authRequired) {
if (log.isDebugEnabled()) {
log.debug(" Calling authenticate()");
}
if (jaspicProvider != null) {
jaspicState = getJaspicState(jaspicProvider, request, response, hasAuthConstraint);
if (jaspicState == null) {
return;
}
}
if (jaspicProvider == null && !doAuthenticate(request, response) || jaspicProvider != null && !authenticateJaspic(request, response, jaspicState, false)) {
if (log.isDebugEnabled()) {
log.debug(" Failed authenticate() test");
}
/*
* ASSERT: Authenticator already set the appropriate HTTP status
* code, so we do not have to do anything special
*/
return;
}
}
if (constraints != null) {
if (log.isDebugEnabled()) {
log.debug(" Calling accessControl()");
}
if (!realm.hasResourcePermission(request, response, constraints, this.context)) {
if (log.isDebugEnabled()) {
log.debug(" Failed accessControl() test");
}
/*
* ASSERT: AccessControl method has already set the appropriate
* HTTP status code, so we do not have to do anything special
*/
return;
}
}
// Any and all specified constraints have been satisfied
if (log.isDebugEnabled()) {
log.debug(" Successfully passed all security constraints");
}
getNext().invoke(request, response);
if (jaspicProvider != null) {
secureResponseJspic(request, response, jaspicState);
}
}
use of java.security.cert.X509Certificate in project tomcat by apache.
the class AjpProcessor method populateSslRequestAttributes.
@Override
protected final void populateSslRequestAttributes() {
if (!certificates.isNull()) {
ByteChunk certData = certificates.getByteChunk();
X509Certificate[] jsseCerts = null;
ByteArrayInputStream bais = new ByteArrayInputStream(certData.getBytes(), certData.getStart(), certData.getLength());
// Fill the elements.
try {
CertificateFactory cf;
String clientCertProvider = protocol.getClientCertProvider();
if (clientCertProvider == null) {
cf = CertificateFactory.getInstance("X.509");
} else {
cf = CertificateFactory.getInstance("X.509", clientCertProvider);
}
while (bais.available() > 0) {
X509Certificate cert = (X509Certificate) cf.generateCertificate(bais);
if (jsseCerts == null) {
jsseCerts = new X509Certificate[1];
jsseCerts[0] = cert;
} else {
X509Certificate[] temp = new X509Certificate[jsseCerts.length + 1];
System.arraycopy(jsseCerts, 0, temp, 0, jsseCerts.length);
temp[jsseCerts.length] = cert;
jsseCerts = temp;
}
}
} catch (java.security.cert.CertificateException e) {
getLog().error(sm.getString("ajpprocessor.certs.fail"), e);
return;
} catch (NoSuchProviderException e) {
getLog().error(sm.getString("ajpprocessor.certs.fail"), e);
return;
}
request.setAttribute(SSLSupport.CERTIFICATE_KEY, jsseCerts);
}
}
use of java.security.cert.X509Certificate in project tomcat by apache.
the class OpenSSLContext method init.
/**
* Setup the SSL_CTX.
*
* @param kms Must contain a KeyManager of the type
* {@code OpenSSLKeyManager}
* @param tms Must contain a TrustManager of the type
* {@code X509TrustManager}
* @param sr Is not used for this implementation.
*/
@Override
public synchronized void init(KeyManager[] kms, TrustManager[] tms, SecureRandom sr) {
if (initialized) {
log.warn(sm.getString("openssl.doubleInit"));
return;
}
try {
if (sslHostConfig.getInsecureRenegotiation()) {
SSLContext.setOptions(ctx, SSL.SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
} else {
SSLContext.clearOptions(ctx, SSL.SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
}
// client's)
if (sslHostConfig.getHonorCipherOrder()) {
SSLContext.setOptions(ctx, SSL.SSL_OP_CIPHER_SERVER_PREFERENCE);
} else {
SSLContext.clearOptions(ctx, SSL.SSL_OP_CIPHER_SERVER_PREFERENCE);
}
// Disable compression if requested
if (sslHostConfig.getDisableCompression()) {
SSLContext.setOptions(ctx, SSL.SSL_OP_NO_COMPRESSION);
} else {
SSLContext.clearOptions(ctx, SSL.SSL_OP_NO_COMPRESSION);
}
// Disable TLS Session Tickets (RFC4507) to protect perfect forward secrecy
if (sslHostConfig.getDisableSessionTickets()) {
SSLContext.setOptions(ctx, SSL.SSL_OP_NO_TICKET);
} else {
SSLContext.clearOptions(ctx, SSL.SSL_OP_NO_TICKET);
}
// Set session cache size, if specified
if (sslHostConfig.getSessionCacheSize() > 0) {
SSLContext.setSessionCacheSize(ctx, sslHostConfig.getSessionCacheSize());
} else {
// Get the default session cache size using SSLContext.setSessionCacheSize()
long sessionCacheSize = SSLContext.setSessionCacheSize(ctx, 20480);
// Revert the session cache size to the default value.
SSLContext.setSessionCacheSize(ctx, sessionCacheSize);
}
// Set session timeout, if specified
if (sslHostConfig.getSessionTimeout() > 0) {
SSLContext.setSessionCacheTimeout(ctx, sslHostConfig.getSessionTimeout());
} else {
// Get the default session timeout using SSLContext.setSessionCacheTimeout()
long sessionTimeout = SSLContext.setSessionCacheTimeout(ctx, 300);
// Revert the session timeout to the default value.
SSLContext.setSessionCacheTimeout(ctx, sessionTimeout);
}
// List the ciphers that the client is permitted to negotiate
String opensslCipherConfig = sslHostConfig.getCiphers();
this.jsseCipherNames = OpenSSLCipherConfigurationParser.parseExpression(opensslCipherConfig);
SSLContext.setCipherSuite(ctx, opensslCipherConfig);
// Load Server key and certificate
if (certificate.getCertificateFile() != null) {
// Set certificate
SSLContext.setCertificate(ctx, SSLHostConfig.adjustRelativePath(certificate.getCertificateFile()), SSLHostConfig.adjustRelativePath(certificate.getCertificateKeyFile()), certificate.getCertificateKeyPassword(), SSL.SSL_AIDX_RSA);
// Set certificate chain file
SSLContext.setCertificateChainFile(ctx, SSLHostConfig.adjustRelativePath(certificate.getCertificateChainFile()), false);
// Support Client Certificates
SSLContext.setCACertificate(ctx, SSLHostConfig.adjustRelativePath(sslHostConfig.getCaCertificateFile()), SSLHostConfig.adjustRelativePath(sslHostConfig.getCaCertificatePath()));
// Set revocation
SSLContext.setCARevocation(ctx, SSLHostConfig.adjustRelativePath(sslHostConfig.getCertificateRevocationListFile()), SSLHostConfig.adjustRelativePath(sslHostConfig.getCertificateRevocationListPath()));
} else {
X509KeyManager keyManager = chooseKeyManager(kms);
String alias = certificate.getCertificateKeyAlias();
if (alias == null) {
alias = "tomcat";
}
X509Certificate[] chain = keyManager.getCertificateChain(alias);
if (chain == null) {
alias = findAlias(keyManager, certificate);
chain = keyManager.getCertificateChain(alias);
}
PrivateKey key = keyManager.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(ctx, chain[0].getEncoded(), sb.toString().getBytes(StandardCharsets.US_ASCII), SSL.SSL_AIDX_RSA);
for (int i = 1; i < chain.length; i++) {
SSLContext.addChainCertificateRaw(ctx, chain[i].getEncoded());
}
}
// Client certificate verification
int value = 0;
switch(sslHostConfig.getCertificateVerification()) {
case NONE:
value = SSL.SSL_CVERIFY_NONE;
break;
case OPTIONAL:
value = SSL.SSL_CVERIFY_OPTIONAL;
break;
case OPTIONAL_NO_CA:
value = SSL.SSL_CVERIFY_OPTIONAL_NO_CA;
break;
case REQUIRED:
value = SSL.SSL_CVERIFY_REQUIRE;
break;
}
SSLContext.setVerify(ctx, value, sslHostConfig.getCertificateVerificationDepth());
if (tms != null) {
final X509TrustManager manager = chooseTrustManager(tms);
SSLContext.setCertVerifyCallback(ctx, new CertificateVerifier() {
@Override
public boolean verify(long ssl, byte[][] chain, String auth) {
X509Certificate[] peerCerts = certificates(chain);
try {
manager.checkClientTrusted(peerCerts, auth);
return true;
} catch (Exception e) {
log.debug(sm.getString("openssl.certificateVerificationFailed"), e);
}
return false;
}
});
}
if (negotiableProtocols != null && negotiableProtocols.size() > 0) {
ArrayList<String> protocols = new ArrayList<>();
protocols.addAll(negotiableProtocols);
protocols.add("http/1.1");
String[] protocolsArray = protocols.toArray(new String[0]);
SSLContext.setAlpnProtos(ctx, protocolsArray, SSL.SSL_SELECTOR_FAILURE_NO_ADVERTISE);
SSLContext.setNpnProtos(ctx, protocolsArray, SSL.SSL_SELECTOR_FAILURE_NO_ADVERTISE);
}
sessionContext = new OpenSSLSessionContext(ctx);
sslHostConfig.setOpenSslContext(Long.valueOf(ctx));
initialized = true;
} catch (Exception e) {
log.warn(sm.getString("openssl.errorSSLCtxInit"), e);
destroy();
}
}
Aggregations