Results 1 to 1 of 1
  1. #1
    Java Exam is offline Member
    Join Date
    Dec 2011
    Posts
    64
    Rep Power
    0

    Default Tutorial:Review of Web Application Security for the Web Component Developer Exam I

    In the next two articles, we will look in depth at web application security. This article will cover declarative web security and the next one will cover programmatic web security. In the article, “Tutorial: Web Application Architecture and Deployment for the Component Developer Exam” we briefly touched on the security in terms of configuring a web application to use basic authentication security for authenticating users in the web application, but now we will go in depth to look at how all aspects of security are handled within a web application. This is part of a series of articles to help you prepare for the web component developer exam.

    Overview of Web Application Security

    The focus of application security is to use measures during the lifecycle of an application to prevent threat’s to the application, the application resources or the underlying platform in which the application resides. In terms of web application security, we are primarily focused on ensure users can only access resources consistent with their level of authorization. This is based on four key issues:
    • Authentication - the means which communicating entities (i.e. client and server) prove to one another that they are acting on behalf of specific identities that are authorized for access. Authentication is any process by which you verify that someone is who they claim they are. In most cases, this involves a username and a password, but can include other methods of demonstrating identity, such as a smart card, retina scan, voice recognition, or fingerprints.
    • Authorization - the means by which interactions with resources are limited to sets of users or programs for the purpose of enforcing integrity, confidentiality, or availability constraints. Authorization is about determining if the person, once identified, is permitted to have the resource.
    • Confidentiality - the means used to ensure that information is made available only to users who are authorized to access it
    • Data Integrity - the means used to prove that information has not been modified by a third party while in transit


    As a client you want to be sure that the site or application with which you are interacting is legitimate especially if you are making online purchases with your credit card. This involves a number of aspects of security. The first is authentication of the site and of the user. The second is authorization to access the resources or information that you are viewing. The third part is confidentiality. You want to ensure that no one is eavesdropping on a sales transaction where a credit card is being used. Finally both you as client and the server need to have integrity to make sure that whatever information they send gets to the other party unaltered.

    When looking at web application security, the key aspects are:
    • Authorization and Authorization or being able to prevent unauthorized users from accessing sensitive resources - this involves first identifying which resources need to be protected, the individuals or the type of user who should have access to them and then identifying the users in order to determine whether they can have access to the sensitive resources.
    • Encryption or being able to prevent attackers from stealing network data while it is in transit - this process involves the use of Transport Security Layer (TLS) to encrypt the traffic between the browser and the server. TLS tends to be used either in very sensitive applications for enterprises or for sensitive areas of a larger application. The most common TLS that is used in almost every client is Secure Sockets Layer (SSL). This makes it difficult for a hacker to attack your network unless they are already within the particular subnet where the application is located.

    Authentication, Authorization and Encryption are independent of each other for the most part. How you choose to authenticate and authorize access to resources is independent of whether we are using TSL. Only if we are using client certificates do the approaches to authentication and authorization overlap with encryption.

    There are two approaches that we use for securing a web application. They are basically the same as what is used to secure EJB applications. The approaches are:
    • Declarative security - using declarative security, we overlay the security on top of the individual servlets or JSP pages without them never needing to have any security-aware code. The two key aspects of security are handled by the server. The key to controlling access is the deployment descriptor (i.e. web.xml). You only need to make some declarations around securing certain URLs as well as the categories of users that can have access to them. You also specify the authentication method to be used by the server to identify users. The four that are commonly used are BASIC, DIGEST, FORM and CLIENT-CERT. The way in which all of them work is that when a request is made to access some resource, the server will automatically prompt the user for a username and password. It will check the username and password against a pre-defined set of usernames and passwords, and if successful, will automatically track each user that has been authenticated. For network data, the way to encrypt certain traffic over the network using TLS, then you specify in the deployment descriptor that certain URLs should only be accessible using TLS. All attempts by users to access one of the protected URLs via an HTTP connection will cause the server to automatically trigger a redirect to the HTTPS (SSL) equivalent of the URL.
    • Programmatic security - using programmatic security, servlets and JSP pages are protected by programmatically having these resources manage for the most part their security. Each servlet or JSP page has to authenticate the user or verify that the user has been authenticated in order to access protected resources. Similarly, each servlet or JSP page has to verify the network protocol used to access it in order to protect the network. In this case, an attempt to access the servlet or JSP page via HTTP will require that the servlet or JSP page manually redirect them to HTTPS (SSL) equivalents.


    Commonly Used Types of Authentication
    There are four commonly used types of authentication. We will go into more depth of each type below. A figure is shown below which maps out the interaction for authentication and authorization of access to application resources:
    Tutorial:Review of Web Application Security for the Web Component Developer Exam I-a17-containersecurity.jpg
    Figure: Container Authentication and Authorization

    Form-Based Authentication

    Of the four types mentioned, this is the most frequently used type of authentication using declarative security. This security uses the HTML forms. The advantage is that the developer has complete control over the look and feel of the login dialog and can easily setup the deployment descriptor to identify protected resources as well as designating the form to collect the user’s username and password. Anytime that a user attempts to access protected resources, they will be redirected to the page with the login form. After the user has entered their name and password and submitted the form, the server checks the username and password against a pre-populated list of usernames, passwords, and roles. If the login is successful and the user has the required role, they will be permitted access to the page that they originally requested. If the login is unsuccessful, the user will be sent sent to a designated error page. The web container uses a variation of session tracking to remember which users have already been validated.

    As shown in the figure above, the container handles all parts of the authentication process automatically and transparent to all resources. The only issue is that if you are doing session tracking via URL rewriting instead of cookies, then form-based authentication is not guaranteed to work. But it is still the most widely used form of authentication for web applications.

    Form based authentication and role based authorization is completely independent of the protection of the network traffic. So you can choose to add SSL for all or none of your application or even for certain parts of it. This has no impact on how you do authorization and authentication of users. It is also independent of the application’s servlets and JSP pages since they are completely decoupled from the security process since any redirect to a URL using SSL and the encryption/decryption of network traffic is done by the server transparent to the application resources.

    Let’s define the basic steps need to setup your system to use form-based security.
    1. Define Roles and Setup Users with Usernames, Passwords, and Roles
    In this step you define the roles and actions that your users are allowed to execute in the application as well as which resource users in a particular role can access. Then setup usernames, passwords, and roles for all of your users. As this is a server-specific process, you need to review the server documentation in order to complete this on your server. For example. if you want to setup users and passwords in Tomcat, you would do the following:
    2. Defining Passwords with Tomcat
    With Tomcat, you can configure custom username and password management schemes by using a database, a Windows User Account, a Directory System, a Unix file or a Kerberos call. An example of this using tomcat-users.xml file found in tomcat_dir/conf / directories is shown below:

    XML Code: Example of tomcat-users.xml
    <?xml version='1.0' encoding='utf-8'?> 
    <tomcat-users>
       <role rolename="reader" /> 
       <role rolename="writer" /> 
       <role rolename="economics" /> 
       <role rolename="science" />
    
       <user username="dougie" password="fresh234" roles="reader,economics" /> 
       <user username="ernesto" password="encomenda" roles="writer,science" /> 
       <user username="javier" password="bairro957" roles="reader,economics" /> 
       <user username="ramesh" password="nikhalem1" roles="writer,economics" />
    </tomcat-users>
    From the listing above, note that each role element must have a role name attribute and each user element must have three attributes: username, password (in plain text), and one or more roles that are comma separated. Of course storing unencrypted passwords in a text file is not considered a major security risk. Any intruder who can access the server’s file system will be able to obtain all the passwords. Also even the system administrators authorized to access server resources should never be able to obtain a user’s password. Passwords should always be encrypted using an algorithm that cannot easily be deciphered. Despite this, the default Tomcat approach allows you to easily set up and test secure Web applications. Once you are ready for production, it is recommended that you replace this Tomcat approach with a more robust system such as a database, Kerberos or a Directory based system.

    Activating Form-Based Authentication in the Server

    Authentication is controlled through the configuration of the login-config element in the deployment descriptor (i.e. web.xml). Form-based authentication is activated by supplying the value of FORM in the auth-method sub element. You then use the form-login-config sub element to provide the location of the login (form-login-page) and the login-failure (form-error-page) page. The pages can be either JSP or HTML files. An example of this is provided in the listing below:

    XML Code: Section of Deployment Descriptor, web.xml
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <web-app 	xmlns="http://java.sun.com/xml/ns/j2ee" 
    		xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    		xsi:schemaLocation= "http://java.sun.com/xml/ns/j2ee
    		http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">
    
    <security-constraint>...</security-constraint>
    <login-config> 
          <auth-method>FORM</auth-method>
          <form-login-config>
    	<form-login-page>/login.jsp</form-login-page>
    	<form-error-page>/login-error.html</form-error-page> 
          </form-login-config>
    </login-config>
    </web-app>
    This shows the part of the deployment descriptor file that determines the type of authentication to be used. In the listing above, is an example of how to configure the container for form-based authentication. Unauthenticated users who attempt to access protected resources will be redirected first to the http://host/appPrefix/login.jsp page.
    If the login is successful, the user will be forwarded to the resource it was originally attempting to access. If the login attempt was unsuccessful, the user will be redirected to http://host/appPrefix/login-error.html.

    Creating your Login Page

    The key for creating your login page is to provide an ACTION of j_security_check with text fields of j_username and j_password. This configuration along with the login-config element is all that is needed to setup form-based authentication and to redirect unauthenticated users to a designated page. The last thing to remember is to use a POST request since a GET would expose the password as clear text in the URL in the GET request. The j_security_check is a special name. You don’t need to preface it with anything for it to work correctly. An example of a form is shown below:

    XML Code: Example of Login Form
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    	pageEncoding="ISO-8859-1"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Login</title>
    </head>
    <body>
    	<form action="j_security_check" method="POST">
    		<table>
    			<tr><td>User name: <input type="TEXT" name="j_username">
    			<tr><td>Password: <input type="PASSWORD" name="j_password">
    			<tr><th><input type="SUBMIT" value="Log In">
    		</table>
    	</FORM>
    </body>
    </html>
    As for the situation of when a user does a logout or a session time out, the servlet specification requires that invalidating the HttpSession should force users to be logged out and that they be required to go through the authentication process again to access protected resources. If so desired, create a servlet or JSP page that invalidates the HttpSession. Note that if you decide to use BASIC authentication, logging out is not supported unless the browser is restarted after the user logs out.

    Restricting Direct Access to the Login Page

    There is an issue related to how servers use redirecting when a user tries to access a protected resource. This is because some servers choose to do this using the RequestDispatcher.forward method while other servers use the HttpServletResponse.sendRedirect method. If a server uses the later, they will be exposing the full URL of the login page to the client which can then be reused to attempt to log in to the application if they are not authenticated, login under another username while already logged in or hitting the browser’s back button. Also there is another issue of what happens when a server tries to access the login page directly. Since the servlet specification doesn’t indicate how this should be handled, each solution is unique to the particular server. Some servers might produce a HTTP 404 error, whereas other servers might produce unexpected results for the user. The solution in order to avoid this type of behaviour is to add some logic into the login page to protect both unauthenticated and authenticated users from directly accessing the login page. This is shown in the listing below:

    XML Code: Code to Avoid Login via Back Button
    <% response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); 
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", -1);
    // Check if user is already logged in 
    if (request.getRemoteUser() != null) {
       response.sendRedirect("logout-confirmation.jsp");
    }
    %>
    You can see in the listing we are setting the response header Cache-Control to “no-store, no-cache, must-revalidate”, in order to ensure that the user can never see a browser-cached version of the login page. This is HTTP 1.1 specific. We also set the Pragma and Expire Headers. Afterwards we use the getRemoteUser method, which returns the username of the currently authenticated user or null if the user is not authenticated. If getRemoteUser returns some value other than null, then we know that this user has already been logged in and is trying to invoke the login page directly. So now we simply redirect the user to a login-confirmation.jsp page which provides an option for logging out.
    As there is no clean and simple way to protect the unauthenticated user from accessing directly the login page, you need to decide what side effects you are willing to accept in order to implement this. In any case, with any approach to this problem, you will find yourself writing security-related code which defeats the purpose of using a declarative security model.

    Creating the Page to Report Failed Login Attempts

    In the case of a login being successful but the user not having the required credential to access a particular resource, the web container will reject the request with a HTTP error code 403 with a description of “Forbidden”. If you want to specify a custom page, you can do this in the deployment descriptor for any and all HTTP Error Codes. If the login is unsuccessful, the user will be redirected to a login-failure page specified in the form-error element by the container. As the login-failure page is completely arbitrary, you are free to design it as you wish.

    Specify the Restricted URLs

    The next step is to provide the set of restricted URLs which will require the proper authentication and authorization. To designate these URL and describe their protection, we use the security-constraint element. It has four possible subelements:
    • display name - optional element providing the name for IDEs to use
    • web-resource-collection - required element specifying the URLs to be protected
    • auth-constraint - optional element designating the abstract roles that have access to the URLs
    • user-data-constraint - optional element specifying whether SSL is required.

    You can configure multiple web-resource-collection entries within security-constraint.
    Below we provide a listing instructing the web container to require passwords for all URLs of the form http://host/appPrefix/restricted/myResource. Authenticated users who have administrator or director roles should be granted access; all others will be denied access:

    XML Code: Section of Deployment Descriptor for Restricting URLs
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <web-app xmlns="http://java.sun.com/xml/ns/j2ee" 
    	      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    	      xsi:schemaLocation= "http://java.sun.com/xml/ns/j2ee
    	      http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">
    
    <security-constraint>
       <web-resource-collection>
          <web-resource-name>restricted</web-resource-name>
          <url-pattern>/restricted/*</url-pattern> 
       </web-resource-collection> 
       <auth-constraint>
          <role-name>administrator</role-name>
          <role-name>director</role-name> 
       </auth-constraint>
    </security-constraint>
    <login-config>...</login-config> 
    </web-app>
    List All Possible User Roles

    Once you have determined all of the required roles for your application, the servlet specification requires that all of the roles be listed within the deployment descriptor. This means that you must separately declare each role used within the security-constraint elements. You use the security-role element in order to do this. Each security-role can contain an option description element along with the role-name element. An example of this is shown below:
    XML Code: Example of Role Definition
    <security-role> 
      <role-name>reader</role-name>
    </security-role> 
    <security-role>
       <role-name>writer</role-name> 
    </security-role> 
    <security-role>
       <role-name>clerk</role-name> 
    </security-role> 
    <security-role>
       <role-name>director</role-name> 
    </security-role> 
    <security-role>
       <role-name>administrator</role-name> 
    </security-role>
    Specifying Encrypted URLs

    You determine that certain resources are only available via encrypted HTTPS (SSL) connections. Here you need to use the user-data-constraint subelement of security-constraint to indicate that a sub set of resources can be accessed only with SSL. So attempts to access a resource via http will be automatically to the same resource but using https. The syntax of the user-data-constraint element requires a transport-guarantee subelement (with values of either NONE, INTEGRAL, or CONFIDENTIAL) and an optional description element. Below is the impact of each of the transport-guarantee subelement values:
    • NONE - puts no restrictions on the communication protocol used. This is the default for transport-guarantee.
    • INTEGRAL - means the communication should be of a type that prevents data from being changed in transit without detection.
    • CONFIDENTIAL - means that the data must be transmitted such that it prevents anyone who intercepts it from reading it.


    An example which instructs the container to permit only https connections to the associated resource:
    XML Code: Example of Encrypted URL Definition
    <security-constraint> 
       <!-- ... --> 
       <user-data-constraint>
          <transport-guarantee>CONFIDENTIAL</transport-guarantee> 
       </user-data-constraint>
    </security-constraint>
    In servers that provide full JEE support, the servlet API provides that users must authenticate themselves with client certificates. You can supply the value of CLIENT-CERT of the auth-method sub element of login-config. Note that containers that are fully compliant with servlet 2.4 and JSP 2.0 are not required to support SSL. is in addition to the requirement that these servers require SSL. This is because some web containers are used as plugins (i.e. Apache and Internet Information Server). These servers will encrypt network traffic with SSL for traffic going between the client and server but will not encrypt local traffic between the web server and web container.

    Disabling the Invoker Servlet

    We use the same URL pattern for restricting access to certain resources by using the servlet-mapping element in the deployment descriptor to indicate where these restrictions apply. Most servers use an “invoker servlet” to provide a default URL for servlets. You need to deactivate this servlet so that users cannot access protected servlets via this URL, since it will bypass the access restrictions that were set by the url-pattern subelement of web-resource-collection. The best approach is to remap the /servlet/* pattern in your Web application so that all requests that include the pattern are sent to the same servlet. You create a servlet that prints an error message or redirects users to the top-level page and you send all requests that include /servlet/* pattern to this servlet using the the servlet and servlet-mapping elements. An example is shown below:

    XML Code: Configuration for BlockInvoker Servlet
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <web-app xmlns="http://java.sun.com/xml/ns/j2ee" 
    	      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    	      xsi:schemaLocation= "http://java.sun.com/xml/ns/j2ee
    	      http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">
    
    <servlet> 
    <servlet-name>BlockInvoker</servlet-name> 
    <servlet-class>com.acme.servlets.BlockInvokerServlet</servlet-class>
    </servlet> 
    <servlet-mapping>
       <servlet-name>BlockInvoker</servlet-name>
       <url-pattern>/servlet/*</url-pattern> 
    </servlet-mapping>
    </web-app>
    BASIC Authentication
    BASIC Authentication is even more popular than Form-Based Authentication since it avoids many of the issues related to form-based authentication. In order to avoid the inherit problems of form-based authentication related to situations where cookies are disabled or URL rewriting, BASIC Authentication uses standard HTTP BASIC security. With BASIC security, a dialog box is used instead of an HTML form to authenticate the username and password. Afterwards the authorization request header is used to track which users have already been authenticated. This still requires the use of SSL if network traffic is a concern. However, this has no impact on BASIC authentication set up nor requires changes to any servlets or JSP pages.
    Since there are no additional login or login-error pages to create and configure, BASIC authentication is even easier to set up. Most e-commerce web sites tend to use form-based authentication, whereas intranet applications often use BASIC. There are two other forms of security based on client certificates (i.e DIGEST and client certificates), but few browsers or servers support DIGEST, and only fully J2EE-compliant servers are required to support client certificates.

    The main disadvantages of BASIC authentication are that since the dialog box is tied to the standard look and feel of the browser and not your application, the input dialog box tends to look markedly different than the rest of your application. Another issue is that it is difficult to log in as a different user once you are authenticated. The only thing you can do is to quit the browser and restart in order to log in as a different user. The use of BASIC security involves six steps, as shown below. The steps are for the most part the same as those for form-based authentication. Only the second step involving activating BASIC authentication on the server is different.

    Define Roles and Setup Users with Usernames, Passwords, and Roles
    This is exactly the same as for form-based authentication is used. See the Form-Based Authentication section for details.

    Activating BASIC Authentication in the Server and Designation of Realm
    Similar to form-based authentication, you use the login-config element in the deployment descriptor to control the authentication method. Just enter BASIC as the auth-method sub element and here provide the realm-name subelement to for the realm that will be used by the browser in the pop-up dialog box and in the Authorization request header. An example is shown below:

    XML Code: BASIC Authentication definition including Realm
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <web-app xmlns="http://java.sun.com/xml/ns/j2ee" 
    	      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    	      xsi:schemaLocation= "http://java.sun.com/xml/ns/j2ee
    	      http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">
    
    <security-constraint>...</security-constraint>
    <login-config> 
       <auth-method>BASIC</auth-method> 
       <realm-name>MyRealm</realm-name>
    </login-config>
    </web-app>
    Specify the Restricted URLs
    This is done in the same manner as was done for form-based authentication. Use the security-constraint element to specify the restricted URLs and roles that are allowed to access them. There are four sub-elements for the security-constraint element: display-name (an optional element), web-resource-collection (required element with the restricted URLs), auth-constraint (optional element providing roles that are allowed access to the restricted URLs), and user-data-constraint (optional element indicating whether SSL is required). You can provide multiple web-resource-collection entries within security-constraint.

    List All Possible User Roles
    Is the same as for form-based authentication. To summarize, define one or more security-role elements here. Each security-role element can have an optional description element as well as the required role-name element.

    Specifying Encrypted URLs
    Is the same as with form-based authentication. To summarize, the user-data-constraint subelement of security-constraint is used with a transport-guarantee subelement to specify either INTEGRAL or CONFIDENTIAL. There is also a means within the servlet API provides of indicating that users must authenticate themselves with client certificates. In this case, you supply a value of CLIENT-CERT for the auth-method subelement of login-config. This is valid only for application servers providing full JEE5 support.

    Using SSL with Tomcat
    There is no requirement for servlet and JSP containers to support SSL in version 2.4 of the servlet specification. Generally when a servlet containers doesn’t support SSL it because they are being used as a plug-in to the Web server. In this case, communication between the client and the Web server will be encrypted, but communication between the Web server and the servlet container will not be. This might create a problem where you declare some of the URLs in your application as requiring the use of SSL, but you would not be able to deploy the application on a server where the servlet container is a plug in to the web server. This significantly reduces the portability of application using SSL.

    Since SSL is very important in many applications (especially e-commerce application), many application servers are self-contained and thus provide support for SSL. Tomcat provides SSL support out of the box although it is by default disabled. Below we provide the steps for you to enable SSL support in Tomcat. This is relevant for the two other means of authenticating users via DIGEST and CLIENT-CERT. The steps are provided below.
    1. Create a self-signed public key certificate - It’s is best to use X.509 certificates to validate for you server to validate to clients about their identity. This helps to prevent hackers from gaining access to the Domain Name System (DNS) servers in order to redirect SSL requests to their site. For production, purchase a certificate that has been signed by a trusted authority such as VeriSign. While in test phase, you can use a self-signed certificate. You can use certificates from keytool for this purpose. It requires a bit of work, but for testing self-signed certificates are just as good as trusted ones. To generate one that is valid for 180 days, do the following:


      Java Code: Example of keytool use
      keytool -genkey -alias tomcat -keyalg RSA -validity 180


      The system will also prompt you for your organization, your location, a keystore password, and a key password. Be sure to use the same value for both passwords. For a server certificate, use the server’s name as the name. The system will then create a file called .keystore in your home directory. You can also use the -keystore argument to change where this file is created. For more details on keytool see Oracle’s Java documentation for the version of the JDK you are using for your application. Don’t ever deploy a production server with a self-signed certificate. In most cases, this will get the search engines to define your sites as being a possible spoof site. Obtain a certificate signed by a trusted Certificate Authority.
    2. 2. Copy the keystore file to the Tomcat installation directory - Copy the .keystore file you created using keytool from your home directory to tomcat_dir.
      Uncomment and edit the SSL connector entry in the server.xml file - This file is located in tomcat_dir/ conf/. Use your preferred editor to open it. Search for the commented-out Connector element that has the port attribute set to 8443. Delete the enclosing comment tags and change the port from 8443 to the SSL default value of 443. Add the keystoreFile attribute providing the location and name of the keystore file relative to the tomcat installation directory. Add the keystorePass attribute providing the password you used when creating the file. An example of this is shown below:
      


      XML Code: Example of configuration for keystore file
      <Connector port="443" maxHttpHeaderSize="8192" 
                maxThreads="150" minSpareThreads="25"
	     
                maxSpareThreads="75" enableLookups="false" 
	     
                disableUploadTimeout="true" acceptCount="100" 
	     
                scheme="https" secure="true" clientAuth="false" 
	     
                sslProtocol="TLS" keystoreFile=".keystore" 
	     
                keystorePass="mypassword"/>
    3. Modify the main connector entry in server.xml to use port 443 for SSL redirects. You need to edit the redirectPort attribute to provide this value. An example is shown below:


      XML Code: Example of redirect port configuration
      <Connector port="80" maxHttpHeaderSize="8192" 
	         
                 maxThreads="150" minSpareThreads="25" 
	         
                 maxSpareThreads="75" enableLookups="false" 
	         
                 redirectPort="443" acceptCount="100"
       
          connectionTimeout="20000" disableUploadTimeout="true"/>
    4. Restart the server.
    5. Access https://localhost:8080/ - this is the https default for your local server. Depending on the browser you will either get a Examine Certificate dialog box (Firefox) which you can suppress the warnings from by clicking on “Accept this certificate permanently”; With Internet Explorer, you first see an initial warning dialog box. You click on “View Certificate” to view the certificate and then click on “Install Certificate” to suppress the warnings. The following time you access the URL, you should see the Tomcat home page without any warnings.


    Signing a Server Certificate
    Although you can use self-signed certificates while testing, you will need to obtain a trusted certificate signed by a Certified Authority for your production system. As purchasing a signed digital certificate from a commercial company is relatively expensive, many corporations choose to set themselves up as their own CA. If your company is intending to sign a server certificate as a CA, then you will need to use the Java Security Tool Kit (JSTK). It is available for educational purposes under the Open Source License v2.0 at J2EE Security.
    Below are the steps to sign your own CA and server certificates. Please check the JSTK documentation for specific information about working with your JDK. We are assuming that you have already downloaded the JSTK and already have JDK 5 or above installed.
    1. Set up the Certificate Authority. Use the JSTK’s certtool script to create a public key infrastructure (PKI) for your Certificate Authority. The command to set up a keystore for your CA is the following:
    Java Code: Example of certtool use
    certtool.bat setupca -dn "CN=MyCompany  Root CA, OU=J2EE Division, O=MyCompany Inc., C=US"-storetype jks -password certauth
    


    The CA keystore (i.e. ca.ks) will be setup in a subdiretory, cadir. The keystore type will by jks for Java KeyStore and the CA keystore password is certauth.
    2. Create a self-signed public key certificate. Use the Java keytool command to generate a public–private key pair and self-signed server certificate. An example of the use of the keytool command for generating the self-signed public key certificate is shown below: 


    Java Code: Example of keytool for public key certificate
    keytool -alias tomcat -genkey -keyalg RSA 
-validity 730 -keystore .keystore 
-storepass srvrpass
    


    There is a series of questions related to name and organization that you will need to answer. This is similar to the self-singed certificate setup in the previous section. After completing all of the questions, the command will create a public–private key pair, with the public key wrapped in an X.509 v3 self-signed certificate and stored as a single certificate chain. The keystore identified by the alias tomcat will now have a certificate chain and a private key. The name of the keystore is .keystore. This is located in your working directory with a password of srvrpass. The certificate is considered valid for 730 days (around two years).
    3. Generate a certificate signing request (CSR). Now we use the keytool to generate a CSR in the PKCS#10 format that is suitable to be signed by your CA. Building upon our previous steps, you can do this using the following command:
    Java Code: Example of certificate signing request command
    keytool -certreq -alias tomcat -keystore .keystore -storepass srvrpass -file server.csr

The generated CSR is stored in the file server.csr.
    4. Sign the server certificate using the JSTK Test CA - Use the JSTK certtool command to sign the CSR by JSTK CA. This is shown below:
    


    Java Code: Example of signing of server certificate
    certtool.bat issue -csrfile server.csr 
-cerfile server.cer -password certauth
    
The command accepts the CSR and signs the request by the CA. The Issued Certificate is written to the server.cer file. The password for the CA keystore is certauth.
    5. Import the trusted certificate into the server keystore - the final step is to import the CA singed server certificate back into the server keystore. This is done using the followign command:
    Java Code: Example of command for importing a trusted certificate into keystore
    keytool -import -alias tomcat -keystore .keystore -storepass srvrpass -file server.cer
    After completing these steps you will have a certificate signed by your company located in in the .keystore. You can test the certificate using Tomcat similar to what we did to configure Tomcat to use SSL by entering the following in your browser:
    XML Code: URL for Tomcat Homepage
    http://localhost:8080
    Remember to enter srvrpass for the password of the server keystore.

    OK. That’s it for declarative web application security for the web component developer exam. In the next article we will exam, programmatic security.
    Last edited by Java Exam; 01-20-2012 at 08:11 PM.

Similar Threads

  1. Replies: 0
    Last Post: 01-09-2012, 08:56 PM
  2. Replies: 0
    Last Post: 01-09-2012, 08:25 PM
  3. Replies: 0
    Last Post: 01-06-2012, 12:51 PM
  4. Replies: 0
    Last Post: 12-20-2011, 07:02 PM
  5. Replies: 0
    Last Post: 12-13-2011, 08:42 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •