Programming WebLogic Security
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
The following topics are covered in this section:
The sections refer to sample code which is available online at BEA's dev2dev web site, and is also included in the WebLogic Server distribution at:
SAMPLES_HOME
\server\examples\src\examples\security\sslclient
The sslclient
directory contains an instructions.html
file, ant
build files, and the following Java and JavaServer Pages (.jsp
) files:
MyListener.java
NulledHostnameVerifier.java
NulledTrustManager.java
SSLClient.java
SSLClientServlet.java
SSLSocketClient.java
SnoopServlet.jsp
You will need to look at the examples when reading the information in the following sections.
The Java Secure Socket Extension (JSSE) is a set of packages that support and implement the SSL and TLS v1 protocols, making those capabilities programmatically available. BEA WebLogic Server provides Secure Sockets Layer (SSL) support for encrypting data transmitted between WebLogic Server clients and servers, Java clients, Web browsers, and other servers.
WebLogic Server's JSSE implementation can be used by WebLogic clients, but is not required. Other JSSE implementations can be used for their client-side code outside the server as well.
The following restrictions apply when using SSL in WebLogic server-side applications:
Other providers may work with WebLogic Server, but an untested provider is not likely to work out of the box. For more information on using the JCE providers supported by WebLogic Server, see Configuring SSL in Securing WebLogic Server.
WebLogic Server uses the HTTPS port for Secure Sockets Layer (SSL) encrypted communication; only SSL can be used on that port.
Note: In order to implement security in a WebLogic client, you must install the WebLogic Server software distribution kit on the Java client.
Java clients use the Java Naming and Directory Interface (JNDI) to pass credentials to WebLogic Server. A Java client establishes a connection with WebLogic Server by getting a JNDI InitialContext
. The Java client then uses the InitialContext
to look up the resources it needs in the WebLogic Server JNDI tree.
Note: JAAS is the preferred method of authentication; however, the Authentication provider's LoginModule supports only username and password authentication. Thus, for client certificate authentication (also referred to as two-way SSL authentication), you should use JNDI. To use JAAS for client certificate authentication, you must write a custom Authentication provider whose LoginModule does certificate authentication.
To specify a user and the user's credentials, set the JNDI properties listed in the Table 5-1.
Provides an entry point into the WebLogic Server environment. The class weblogic.jndi.WLInitialContextFactory is the JNDI SPI for WebLogic Server. |
|
Specifies the host and port of the WebLogic Server that provides the name service. For example: |
|
Specifies the identity of the user when that user authenticates to the default (active) security realm. |
|
Specifies the credentials of the user when that user authenticates to the default (active) security realm. |
These properties are stored in a hash table which is passed to the InitialContext
constructor.
Listing 5-1 demonstrates how to use one-way SSL certificate authentication in a Java client. For a two-SSL authentication code example, see Listing 5-4.
Listing 5-1 Example of One-Way SSL Authentication Using JNDI
...
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"weblogic.jndi.WLInitialContextFactory");
env.put(Context.PROVIDER_URL, "t3s://weblogic:7002");
env.put(Context.SECURITY_PRINCIPAL, "javaclient");
env.put(Context.SECURITY_CREDENTIALS, "javaclientpassword");
ctx = new InitialContext(env);
Note: For information on JNDI contexts and threads and how to avoid potential JNDI context problems, see JNDI Contexts and Threads and How to Avoid Potential JNDI Context Problems in Programming WebLogic JNDI.
The following topics are covered in this section:
To implement Java clients that use SSL authentication on WebLogic Server, use a combination of Java JDK 5.0 application programming interfaces (APIs) and WebLogic APIs.
Table 5-2 lists and describes the Java APIs packages used to implement certificate authentication. The information in Table 5-2 is taken from the Java API documentation and annotated to add WebLogic Server specific information. For more information on the Java APIs, see the Javadocs at http://java.sun.com/j2se/1.5.0/docs/api/index.html and http://java.sun.com/j2ee/1.4/docs/api/index.html.
Table 5-3 lists and describes the WebLogic APIs used to implement certificate authentication. For more information, see Javadocs for WebLogic Classes.
At a minimum, an SSL client application includes the following components:
SSLContext
with client identity, trust, a HostnameVerifier
, and a TrustManager
.The HandshakeCompletedListener implements the javax.net.ssl.HandshakeCompletedListener
interface. It is used by the SSL client to receive notifications about the completion of an SSL handshake on a given SSL connection.
For a complete working SSL authentication client that implements the components described here, see the SSLClient sample application in the SAMPLES_HOME\server\examples\src\examples\security\sslclient
directory provided with WebLogic Server. This example is also available online at BEA's dev2dev site
For more information on JSSE authentication, see Sun's Java Secure Socket Extension (JSSE) Reference Guide available at http://java.sun.com/j2se/1.5.0/docs/guide/security/jsse/JSSERefGuide.html.
This section covers the following topics:
You can use a URL object to make an outbound SSL connection from a WebLogic Server instance acting as a client to another WebLogic Server instance. The weblogic.net.http.HttpsURLConnection
class provides a way to specify the security context information for a client, including the digital certificate and private key of the client.
The weblogic.net.http.HttpsURLConnection
class provides methods for determining the negotiated cipher suite, getting/setting a hostname verifier, getting the server's certificate chain, and getting/setting an SSLSocketFactory
in order to create new SSL sockets.
The SSLClient code example uses the weblogic.net.http.HttpsURLConnection
class to make an outbound SSL connection. The SSLClient code example is available in the examples.security.sslclient
package in the SAMPLES_HOME\server\examples\src\examples\security\sslclient
directory.
This section uses examples to show how to write various types of SSL clients. Examples of the following types of SSL clients are provided:
SSL Client License Requirement: Any stand-alone Java client that uses WebLogic SSL classes (weblogic.security.SSL) to invoke an Enterprise JavaBean (EJB) must use the BEA license file. When you run your client application, set the following system properties:
bea.home
, add that directory to the WebLogic CLASSPATH.java.protocol.handler.pkgs=com.certicom.net.ssl
Here is an example of a run command that uses the default location of the license file (c:\bea
):
java -Dbea.home=c:\bea \
-Djava.protocol.handler.pkgs=weblogic.net my_app
The SSLClient sample demonstrates how to use the WebLogic SSL library to make outgoing SSL connections using URL
and URLConnection
objects. It shows both how to do this from a stand-alone application as well as from a servlet in WebLogic Server.
Note: WebLogic Server acting as an SSL client uses the server's identity certificate for outgoing SSL connections. Applications running on WebLogic Server and using the previously described SSL APIs do not share the server's identity certificates by default, only the trust.
Listing 5-2 shows code fragments from the SSLClient example; the complete example is located at SAMPLES_HOME\server\examples\src\examples\security\sslclient
directory in the SSLClient.java
file.
Listing 5-2 SSLClient Sample Code Fragments
package examples.security.sslclient;
import java.io.*;
import java.net.URL;
import java.security.Provider;
import javax.servlet.ServletOutputStream;
...
/*
* This method contains an example of how to use the URL and
* URLConnection objects to create a new SSL connection, using
* WebLogic SSL client classes.
*/
public void wlsURLConnect(String host, String port,
String sport, String query,
OutputStream out)
throws Exception {
...
URL wlsUrl = null;
try {
wlsUrl = new URL("http", host, Integer.valueOf(port).intValue(),
query);
weblogic.net.http.HttpURLConnection connection =
new weblogic.net.http.HttpURLConnection(wlsUrl);
tryConnection(connection, out);
}
...
wlsUrl = new URL("https", host, Integer.valueOf(sport).intValue(),
query);
weblogic.net.http.HttpsURLConnection sconnection =
new weblogic.net.http.HttpsURLConnection(wlsUrl);
...
The SSLSocketClient sample demonstrates how to use SSL sockets to go directly to the secure port to connect to a JSP served by an instance of WebLogic Server and display the results of that connection. It shows how to implement the following functions:
SSLContext
with client identity, a HostnameVerifier
, and a TrustManager
SSLSocketFactory
javax.net.ssl.HandshakeCompletedListener
interfaceweblogic.security.SSL.HostnameVerifier
class to verify that the server the example connects to is running on the desired host Listing 5-3 shows code fragments from the SSLSocketClient example; the complete example is located at SAMPLES_HOME\server\examples\src\examples\security\sslclient
directory in the SSLSocketClient.java
file. (The SSLClientServlet example in the sslclient
directory is a simple servlet wrapper of the SSLClient example.)
Listing 5-3 SSLSocketClient Sample Code Fragments
package examples.security.sslclient;
import java.io.*;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import javax.net.ssl.HandshakeCompletedListener;
import javax.net.ssl.SSLSocket;
import weblogic.security.SSL.HostnameVerifier;
import weblogic.security.SSL.SSLContext;
import weblogic.security.SSL.SSLSocketFactory;
import weblogic.security.SSL.TrustManager;
...
SSLContext sslCtx = SSLContext.getInstance("https");
File KeyStoreFile = new File ("mykeystore");
...
// Open the keystore, retrieve the private key, and certificate chain
KeyStore ks = KeyStore.getInstance("jks");
ks.load(new FileInputStream("mykeystore"), null);
PrivateKey key = (PrivateKey)ks.getKey("mykey",
"testkey".toCharArray());
Certificate [] certChain = ks.getCertificateChain("mykey");
sslCtx.loadLocalIdentity(certChain, key);
HostnameVerifier hVerifier = null;
if (argv.length < 3)
hVerifier = new NulledHostnameVerifier();
else
hVerifier = (HostnameVerifier)
Class.forName(argv[2]).newInstance();
sslCtx.setHostnameVerifier(hVerifier);
TrustManager tManager = new NulledTrustManager();
sslCtx.setTrustManager(tManager);
System.out.println(" Creating new SSLSocketFactory with SSLContext");
SSLSocketFactory sslSF = (SSLSocketFactory)
sslCtx.getSocketFactory();
System.out.println(" Creating and opening new SSLSocket with
SSLSocketFactory");
// using createSocket(String hostname, int port)
SSLSocket sslSock = (SSLSocket) sslSF.createSocket(argv[0],
new Integer(argv[1]).intValue());
System.out.println(" SSLSocket created");
HandshakeCompletedListener mListener = null;
mListener = new MyListener();
sslSock.addHandshakeCompletedListener(new MyListener());
...
When using certificate authentication, WebLogic Server sends a digital certificate to the requesting client. The client examines the digital certificate to ensure that it is authentic, has not expired, and matches the WebLogic Server instance that presented it.
With two-way SSL authentication (a form of mutual authentication), the requesting client also presents a digital certificate to WebLogic Server. When the instance of WebLogic Server is configured for two-way SSL authentication, requesting clients are required to present digital certificates from a specified set of certificate authorities. WebLogic Server accepts only digital certificates that are signed by trusted certificate authorities.
For information on how to configure WebLogic Server for two-way SSL authentication, see the Configuring SSL in Securing WebLogic Server.
The following sections describe the different ways two-way SSL authentication can be implemented in WebLogic Server.
When using JNDI for two-way SSL authentication in a Java client, use the setSSLClientCertificate()
method of the WebLogic JNDI Environment
class. This method sets a private key and chain of X.509 digital certificates for client authentication.
To pass digital certificates to JNDI, create an array of InputStreams
opened on files containing DER-encoded digital certificates and set the array in the JNDI hash table. The first element in the array must contain an InputStream
opened on the Java client's private key file. The second element must contain an InputStream
opened on the Java client's digital certificate file. (This file contains the public key for the Java client.) Additional elements may contain the digital certificates of the root certificate authority and the signer of any digital certificates in a certificate chain. A certificate chain allows WebLogic Server to authenticate the digital certificate of the Java client if that digital certificate was not directly issued by the server's trusted certificate authority.
You can use the weblogic.security.PEMInputStream class to read digital certificates stored in Privacy Enhanced Mail (PEM) files. This class provides a filter that decodes the base 64-encoded certificate from a PEM file.
Listing 5-4 demonstrates how to use two-way SSL authentication in a Java client.
Listing 5-4 Example of a Two-Way SSL Authentication Client That Uses JNDI
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import weblogic.jndi.Environment;
import weblogic.security.PEMInputStream;
import java.io.InputStream;
import java.io.FileInputStream;
public class SSLJNDIClient
{
public static void main(String[] args) throws Exception
{
Context context = null;
try {
Environment env = new Environment();
// set connection parameters
env.setProviderUrl("t3s://localhost:7002");
// The next two set methodes are optional if you are using
// a UserNameMapper interface.
env.setSecurityPrincipal("system");
env.setSecurityCredentials("weblogic");
InputStream key = new FileInputStream("certs/demokey.pem");
InputStream cert = new FileInputStream("certs/democert.pem");
// wrap input streams if key/cert are in pem files
key = new PEMInputStream(key);
cert = new PEMInputStream(cert);
env.setSSLClientCertificate(new InputStream[] { key, cert});
env.setInitialContextFactory(Environment.DEFAULT_INITIAL_CONTEXT_FACTORY);
context = env.getInitialContext();
Object myEJB = (Object) context.lookup("myEJB");
}
finally {
if (context != null) context.close();
}
}
}
When the JNDI getInitialContext()
method is called, the Java client and WebLogic Server execute mutual authentication in the same way that a Web browser performs mutual authentication to get a secure Web server connection. An exception is thrown if the digital certificates cannot be validated or if the Java client's digital certificate cannot be authenticated in the default (active) security realm. The authenticated user object is stored on the Java client's server thread and is used for checking the permissions governing the Java client's access to any protected WebLogic resources.
When you use the WebLogic JNDI Environment
class, you must create a new Environment
object for each call to the getInitialContext()
method. Once you specify a User
object and security credentials, both the user and their associated credentials remain set in the Environment
object. If you try to reset them and then call the JNDI getInitialContext()
method, the original user and credentials are used.
When you use two-way SSL authentication from a Java client, WebLogic Server gets a unique Java Virtual Machine (JVM) ID for each client JVM so that the connection between the Java client and WebLogic Server is constant. Unless the connection times out from lack of activity, it persists as long as the JVM for the Java client continues to execute. The only way a Java client can negotiate a new SSL connection reliably is by stopping its JVM and running another instance of the JVM.
The code in Listing 5-4 generates a call to the WebLogic Identity Assertion provider that implements the weblogic.security.providers.authentication.UserNameMapper
interface. The class that implements the UserNameMapper
interface returns a user object if the digital certificate is valid. WebLogic Server stores this authenticated user object on the Java client's thread in WebLogic Server and uses it for subsequent authorization requests when the thread attempts to use WebLogic resources protected by the default (active) security realm.
Note: Your CLASSPATH
must specify the implementation of the weblogic.security.providers.authentication.UserNameMapper
interface.
If you have not configured an Identity Assertion provider that performs certificate-based authentication, a Java client running in a JVM with an SSL connection can change the WebLogic Server user identity by creating a new JNDI InitialContext
and supplying a new user name and password in the JNDI SECURITY_PRINCIPAL
and SECURITY_CREDENTIALS
properties. Any digital certificates passed by the Java client after the SSL connection is made are not used. The new WebLogic Server user continues to use the SSL connection negotiated with the initial user's digital certificate.
If you have configured an Identity Assertion provider that performs certificate-based authentication, WebLogic Server passes the digital certificate from the Java client to the class that implements the UserNameMapper
interface and the UserNameMapper
class maps the digital certificate to a WebLogic Server user name. Therefore, if you want to set a new user identity when you use the certificate-based identity assertion, you cannot change the identity. This is because the digital certificate is processed only at the time of the first connection request from the JVM for each Environment
.
Caution: Restriction: Multiple, concurrent, user logins to WebLogic Server from a single client JVM when using two-way SSL and JNDI is not supported. If multiple logins are executed on different threads, the results are undeterminable and might result in one user's requests being executed on another user's login, thereby allowing one user to access another user's data. WebLogic Server does not support multiple, concurrent, certificate-based logins from a single client JVM. For information on JNDI contexts and threads and how to avoid potential JNDI context problems, see JNDI Contexts and Threads and How to Avoid JNDI Context Problems in Programming WebLogic JNDI.
When using two-way SSL, WebLogic Server verifies the digital certificate of the Web browser or Java client when establishing an SSL connection. However, the digital certificate does not identify the Web browser or Java client as a user in the WebLogic Server security realm. If the Web browser or Java client requests a WebLogic Server resource protected by a security policy, WebLogic Server requires the Web browser or Java client to have an identity. To handle this requirement, the WebLogic Identity Assertion provider allows you to enable a user name mapper that maps the digital certificate of a Web browser or Java client to a user in a WebLogic Server security realm. The user name mapper must be an implementation the weblogic.security.providers.authentication.UserNameMapper
interface.
You have the option of the using the default implementation of the weblogic.security.providers.authentication.UserNameMapper
interface, DefaultUserNameMapperImpl
, or developing your own implementation.
The WebLogic Identity Assertion provider can call the implementation of the UserNameMapper
interface for the following types of identity assertion token types:
If you need to map different types of certificates, write your own implementation of the UserNameMapper
interface.
To implement a UserNameMapper
interface that maps a digital certificate to a user name, write a UserNameMapper
class that performs the following operations:
You can use two-way SSL authentication in server-to-server communication in which one WebLogic Server instance is acting as the client of another WebLogic Server instance. Using two-way SSL authentication in server-to-server communication enables you to have dependable, highly-secure connections, even without the more common client/server environment.
Listing 5-5 shows an example of how to establish a secure connection from a servlet running in one instance of WebLogic Server to a second WebLogic Server instance called server2.weblogic.com
.
Listing 5-5 Establishing a Secure Connection to Another WebLogic Server Instance
FileInputStream [] f = new FileInputStream[3];
f[0]= new FileInputStream("demokey.pem");
f[1]= new FileInputStream("democert.pem");
f[2]= new FileInputStream("ca.pem");
Environment e = new Environment ();
e.setProviderURL("t3s://server2.weblogic.com:443");
e.setSSLClientCertificate(f);
e.setSSLServerName("server2.weblogic.com");
e.setSSLRootCAFingerprints("ac45e2d1ce492252acc27ee5c345ef26");
e.setInitialContextFactory
("weblogic.jndi.WLInitialContextFactory");
Context ctx = new InitialContext(e.getProperties())
In Listing 5-5, the WebLogic JNDI Environment
class creates a hash table to store the following parameters:
setProviderURL
—specifies the URL of the WebLogic Server instance acting as the SSL server. The WebLogic Server instance acting as SSL client calls this method. The URL specifies the t3s protocol which is a WebLogic Server proprietary protocol built on the SSL protocol. The SSL protocol protects the connection and communication between the two WebLogic Servers instances.setSSLClientCertificate
—specifies the private key and certificate chain to use for the SSL connection. You use this method to specify an input stream array that consists of a private key (which is the first input stream in the array) and a chain of X.509 certificates (which make up the remaining input streams in the array). Each certificate in the chain of certificates is the issuer of the certificate preceding it in the chain.setSSLServerName
—specifies the name of the WebLogic Server instance acting as the SSL server. When the SSL server presents its digital certificate to the WebLogic Server acting as the SSL client, the name specified using the setSSLServerName
method is compared to the common name field in the digital certificate. In order for hostname verification to succeed, the names must match. This parameter is used to prevent man-in-the-middle attacks.setSSLRootCAFingerprint
—specifies digital codes that represent a set of trusted certificate authorities, thus specifying trust based on a trusted certificate fingerprint. The root certificate in the certificate chain received from the WebLogic Server instance acting as the SSL server has to match one of the fingerprints specified with this method in order to be trusted. This parameter is used to prevent man-in-the-middle attacks. It provides an addition to the default level of trust, which for clients running on WebLogic Server is that specified by the WebLogic Server trust configuration. Note: For information on JNDI contexts and threads and how to avoid potential JNDI context problems, see JNDI Contexts and Threads and How to Avoid JNDI Context Problems in Programming WebLogic JNDI.
To authenticate Java clients in a servlet (or any other server-side Java class), you must check whether the client presented a digital certificate and if so, whether the certificate was issued by a trusted certificate authority. The servlet developer is responsible for asking whether the Java client has a valid digital certificate. When developing servlets with the WebLogic Servlet API, you must access information about the SSL connection through the getAttribute()
method of the HTTPServletRequest
object.
The following attributes are supported in WebLogic Server servlets:
javax.servlet.request.X509Certificate
java.security.cert.X509Certificate []
—returns an array of the X.509 certificate. javax.servlet.request.cipher_suite
—returns a string representing the cipher suite used by HTTPS.javax.servlet.request.key_size
— returns an integer (0, 40, 56, 128, 168) representing the bit size of the symmetric (bulk encryption) key algorithm. weblogic.servlet.request.SSLSession
javax.net.ssl.SSLSession
—returns the SSL session object that contains the cipher suite and the dates on which the object was created and last used.You have access to the user information defined in the digital certificates. When you get the javax.servlet.request.X509Certificate
attribute, it is an array of type java.security.cert.X509Certificate
. You simply cast the array to that type and examine the certificates.
A digital certificate includes information, such as the following:
A hostname verifier validates that the host to which an SSL connection is made is the intended or authorized party. A hostname verifier is useful when a WebLogic client or a WebLogic Server instance is acting as an SSL client to another application server. It helps prevent man-in-the-middle attacks.
Note: Demonstration digital certificates are generated during installation so they do contain the hostname of the system on which the WebLogic Server software installed. Therefore, you should leave hostname verification on when using the demonstration certificates for development or testing purposes.
By default, WebLogic Server, as a function of the SSL handshake, compares the CN field of the SSL server certificate Subject DN with the hostname in the URL used to connect to the server. If these names do not match, the SSL connection is dropped.
The dropping of the SSL connection is caused by the SSL client, which validates the hostname of the server against the digital certificate of the server. If anything but the default behavior is desired, you can either turn off hostname verification or register a custom hostname verifier. Turning off hostname verification leaves the SSL connections vulnerable to man-in-the-middle attacks.
You can turn off hostname verification in the following ways:
myserver
).You can write a custom hostname verifier. The weblogic.security.SSL.HostnameVerifier
interface provides a callback mechanism so that implementers of this interface can supply a policy on whether the connection to the URL's hostname should be allowed. The policy can be certificate-based or can depend on other authentication schemes.
To use a custom hostname verifier, create a class that implements the weblogic.security.SSL.HostnameVerifier
interface and define the methods that capture information about the server's security identity.
Note: This interface takes new style certificates and replaces the weblogic.security.SSL.HostnameVerifierJSSE
interface, which is deprecated.
Before you can use a custom hostname verifier, you need to specify the class for your implementation in the following ways:
Listing 5-6 shows code fragments from the NulledHostnameVerifier example; the complete example is located at SAMPLES_HOME\server\examples\src\examples\security\sslclient
directory in the NulledHostnameVerifier.java
file. This code example contains a NulledHostnameVerifier
class which always returns true for the comparison. The sample allows the WebLogic SSL client to connect to any SSL server regardless of the server's hostname and digital certificate SubjectDN comparison.
Listing 5-6 Hostname Verifier Sample Code Fragment
public class NulledHostnameVerifier implements
weblogic.security.SSL.HostnameVerifier {
public boolean verify(String urlHostname, javax.net.ssl.SSLSession session) {
return true;
}
}
The weblogic.security.SSL.TrustManager
interface provides the ability to:
Note: This interface takes new style certificates and replaces the weblogic.security.SSL.TrustManagerJSSE
interface, which is deprecated.
When an SSL client connects to an instance of WebLogic Server, the server presents its digital certificate chain to the client for authentication. That chain could contain an invalid digital certificate. The SSL specification says that the client should drop the SSL connection upon discovery of an invalid certificate. You can use a custom implementation of the TrustManager
interface to control when to continue or discontinue an SSL handshake. Using a trust manager, you can ignore certain validation errors, optionally perform custom validation checks, and then decide whether or not to continue the handshake.
Use the weblogic.security.SSL.TrustManager
interface to create a trust manager. The interface contains a set of error codes for certificate verification. You can also perform additional validation on the peer certificate and interrupt the SSL handshake if need be. After a digital certificate has been verified, the weblogic.security.SSL.TrustManager
interface uses a callback function to override the result of verifying the digital certificate. You can associate an instance of a trust manager with an SSL context through the setTrustManager()
method.
You can only set up a trust manger programmatically; its use cannot be defined through the Administration Console or on the command-line.
Note: Depending on the checks performed, use of a trust manager may potentially impact performance.
Listing 5-7 shows code fragments from the NulledTrustManager example; the complete example is located at SAMPLES_HOME\server\examples\src\examples\security\sslclient
directory in the NulledTrustManager.java
file. The SSLSocketClient example uses the custom trust manager. The SSLSocketClient shows how to set up a new SSL connection by using an SSL context with the trust manager.
Listing 5-7 NulledTrustManager Sample Code Fragments
package examples.security.sslclient;
import weblogic.security.SSL.TrustManager;
import java.security.cert.X509Certificate;
...
public class NulledTrustManager implements TrustManager{
public boolean certificateCallback(X509Certificate[] o, int validateErr) {
System.out.println(" --- Do Not Use In Production ---\n" +
" By using this NulledTrustManager, the trust in" +
" the server's identity is completely lost.\n" + " --------------------------------");
for (int i=0; i<o.length; i++)
System.out.println(" certificate " + i + " -- " + o[i].toString());
return true;
}
}
The CertPathTrustManager, weblogic.security.SSL.CertPathTrustManager
, makes use of the default security realm's configured CertPath validation providers to perform extra validation such as revocation checking.
By default, application code using outbound SSL in the server has access only to the built-in SSL certificate validation. However, application code can specify the CertPathTrustManager in order to access any additional certificate validation that the administrator has configured for the server. If you want your application code to also run the CertPath validators, the application code should use the CertPathTrustManager.
There are three ways to use this class:
setUseConfiguredSSLValidation()
method for this purpose. This is the default. setBuiltinSSLValidationAndCertPathValidators()
method for this purpose.setBuiltinSSLValidationOnly()
method for this purpose. The javax.net.ssl.HandshakeCompletedListener
interface defines how an SSL client receives notifications about the completion of an SSL protocol handshake on a given SSL connection. Listing 5-8 shows code fragments from the MyListener example; the complete example is located at SAMPLES_HOME\server\examples\src\examples\security\sslclient
directory in the MyListener.java
file.
Listing 5-8 MyListener (HandshakeCompletedListener) Sample Code Fragments
package examples.security.sslclient;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileInputStream;
import javax.net.ssl.HandshakeCompletedListener;
import java.util.Hashtable;
import javax.net.ssl.SSLSession;
...
public class MyListener implements HandshakeCompletedListener
{
public void handshakeCompleted(javax.net.ssl.HandshakeCompletedEvent
event)
{
SSLSession session = event.getSession();
System.out.println("Handshake Completed with peer " +
session.getPeerHost());
System.out.println(" cipher: " + session.getCipherSuite());
Certificate[] certs = null;
try
{
certs = session.getPeerCertificates();
}
catch (SSLPeerUnverifiedException puv)
{
certs = null;
}
if (certs != null)
{
System.out.println(" peer certificates:");
for (int z=0; z<certs.length; z++)
System.out.println(" certs["+z+"]: " + certs[z]);
}
else
{
System.out.println("No peer certificates presented");
}
}
}
The SSLContext
class is used to programmatically configure SSL and to retain SSL session information. Each instance can be configured with the keys, certificate chains, and trusted CA certificates that will be used to perform authentication. SSL sockets created with the same SSLContext and used to connect to the same SSL server could potentially reuse SSL session information. Whether the session information is actually reused depends on the SSL server.
For more information on session caching see SSL Session Behavior in Securing WebLogic Server. To associate an instance of a trust manager class with its SSL context, use the weblogic.security.SSL.SSLContext.setTrustManager()
method.
You can only set up an SSL context programmatically; not by using the Administration Console or the command line. A Java new
expression or the getInstance()
method of the SSLContext
class can create an SSLContext
object. The getInstance()
method is static and it generates a new SSLContext
object that implements the specified secure socket protocol. An example of using the SSLContext
class is provided in the SSLSocketClient.java
sample in the SAMPLES_HOME\server\examples\src\examples\security\sslclient
directory. The SSLSocketClient example shows how to create a new SSL socket factory that will create a new SSL socket using SSLContext
.
Listing 5-9 shows a sample instantiation using the getInstance()
method.
Listing 5-9 SSL Context Code Example
import weblogic.security.SSL.SSLContext;
SSLcontext sslctx = SSLContext.getInstance ("https")
You can use a URL
object to make an outbound SSL connection from a WebLogic Server instance acting as a client to another WebLogic Server instance. WebLogic Server supports both one-way and two-way SSL authentication for outbound SSL connections.
For one-way SSL authentication, you use the java.net.URL
, java.net.URLConnection
, and java.net.HTTPURLConnection
classes to make outbound SSL connections using URL
objects. Listing 5-10 shows a simpleURL
class that supports both HTTP and HTTPS URLs and that only uses these Java classes (that is, no WebLogic classes are required). To use the simpleURL
class for one-way SSL authentication (HTTPS) on WebLogic Server, all that is required is that "weblogic.net
" be defined in the system property for java.protocols.handler.pkgs
.
Note: Because the simpleURL
sample shown in Listing 5-10 defaults trust and hostname checking, this sample requires that you connect to a real Web server that is trusted and that passes hostname checking by default. Otherwise, you must override trust and hostname checking on the command line.
Listing 5-10 One-Way SSL Authentication URL Outbound SSL Connection Class That Uses Java Classes Only
import java.net.URL;
import java.net.URLConnection;
import java.net.HttpURLConnection;
import java.io.IOException;
public class simpleURL
{
public static void main (String [] argv)
{
if (argv.length != 1)
{
System.out.println("Please provide a URL to connect to");
System.exit(-1);
}
setupHandler();
connectToURL(argv[0]);
}
private static void setupHandler()
{
java.util.Properties p = System.getProperties();
String s = p.getProperty("java.protocol.handler.pkgs");
if (s == null)
s = "weblogic.net";
else if (s.indexOf("weblogic.net") == -1)
s += "|weblogic.net";
p.put("java.protocol.handler.pkgs", s);
System.setProperties(p);
}
private static void connectToURL(String theURLSpec)
{
try
{
URL theURL = new URL(theURLSpec);
URLConnection urlConnection = theURL.openConnection();
HttpURLConnection connection = null;
if (!(urlConnection instanceof HttpURLConnection))
{
System.out.println("The URL is not using HTTP/HTTPS: " +
theURLSpec);
return;
}
connection = (HttpURLConnection) urlConnection;
connection.connect();
String responseStr = "\t\t" +
connection.getResponseCode() + " -- " +
connection.getResponseMessage() + "\n\t\t" +
connection.getContent().getClass().getName() + "\n";
connection.disconnect();
System.out.println(responseStr);
}
catch (IOException ioe)
{
System.out.println("Failure processing URL: " + theURLSpec);
ioe.printStackTrace();
}
}
}
For two-way SSL authentication, the weblogic.net.http.HttpsURLConnection
class provides a way to specify the security context information for a client, including the digital certificate and private key of the client. Instances of this class represent an HTTPS connection to a remote object.
The SSLClient sample code demonstrates using the WebLogic URL
object to make an outbound SSL connection (see Listing 5-11). The code example shown in Listing 5-11 is excerpted from the SSLClient.java
file in the SAMPLES_HOME\server\examples\src\examples\security\sslclient
directory.
Listing 5-11 WebLogic Two-Way SSL Authentication URL Outbound SSL Connection Code Example
wlsUrl = new URL("https", host, Integer.valueOf(sport).intValue(),
query);
weblogic.net.http.HttpsURLConnection sconnection =
new weblogic.net.http.HttpsURLConnection(wlsUrl);
...
InputStream [] ins = new InputStream[2];
ins[0] = new FileInputStream("clientkey.pem");
ins[1] = new FileInputStream("client2certs.pem");
String pwd = "clientkey";
sconnection.loadLocalIdentity(ins[0], ins[1], pwd.toCharArray());
A complete working SSL authentication sample is provided with the WebLogic Server product. The sample is located in the SAMPLES_HOME\server\examples\src\examples\security\sslclient
directory. For a description of the sample and instructions on how to build, configure, and run this sample, see the package.html
file in the sample directory. You can modify this code example and reuse it.
![]() ![]() |
![]() |
![]() |