Solutions to common security problems in J2EE engineering implementation

Source: Internet
Author: User
By fleshwound (http://www.smatrix.org)
(Note: This is part of our complete design, and some other parts still require confidentiality. I hope this article will help the brothers who are working on the J2EE project, any questions about JAVA security and cryptography theory and application can come to our forum: http://bbs.smatrix.org)
In recent years, with the popularization of Internet and computer, e-commerce and e-government have become an important part of today's social life, the online Shop System, which features online ordering and online payment, is currently a popular e-commerce technology.
With its magical charm and powerful security technical support, JAVA soon became the preferred language for WEB information system development, j2EE was born for WEB application development. At present, most J2EE applications are structured in multiple layers. Good layering can bring many benefits. For example, it can make the code structure clear, facilitate Component reuse, and quickly adapt to new application requirements. JAVA also provides powerful security technologies (such as JCA, HTTPS, and JSSA ). For e-commerce systems, the security and efficiency of the system platform are the core issues, which are exactly the strengths of J2EE and related technologies.

Introduction to the APIs used in system 0 and their features
The main technologies and features used in the system are as follows:
(1) EJB: mainly serves as the J2EE middle layer to complete the business logic. Currently, there are three main types of ejbs: Session Bean, Entity Bean, and message-driven Bean (MDB );
(2) JAAS: it is used in J2EE to process authentication and authorization services for resource control;
(3) JSP and Java Servlets: used for J2EE presentation layer to generate a user interface;
(4) JDBC: used for database (resource layer) connection and interaction with the database;
(5) JNDI: Java Naming and Directory Interface, which is actually used to access all resources of J2EE;
(6) JMS: Java Message transmission service, used with MDB.

1. Session Security Issues and Solutions
In a project, there are two methods to save the Session: Put the Session on the client and put the Session on the server. When a Session is saved on the client, the Session state is serialized and then embedded into the HTML page returned to the client. This method is easy to implement when there is very little information in the Session. In addition, this method eliminates the replication status across multiple servers.
However, when the client saves the Session status, the resulting security issues must be taken into account, because hackers may obtain sensitive information through Sniffer attacks. To prevent sensitive information from being exposed, the solution is to encrypt the data or Use HTTPS, using SSL technology.
For applications that want to save a large number of Session states, the best way is to put the Session state on the server. When the status is saved on the server, there is no limitation on the size and type of client Session management. In addition, it avoids the resulting security issues, and does not affect the performance caused by the Session Status transmitted between each request. However, it has high performance requirements on the server. The online shop system has high security requirements. Therefore, the Session is concentrated on the intermediate layer server and SSL connections are used to connect the client to the server.
2 Client Cache security design
Most customers use WEB browsers to cache browsed pages on disks. Therefore, when Browsing webpages, we do not need to send HTTP requests to the server again. Therefore, there is no security problem for common webpages. However, for WEB applications that require confidentiality, security risks and privacy leak. Therefore, the client cache must be properly processed. The best way is to disable caching. But for most customers, it is unrealistic to require no caching on the client. Therefore, we must solve this problem in the middle layer by using Servlet filter technology. This technology was developed after Servlet2.3 and has been widely used in J2EE. To use this technology, perform the following steps:
(1) Compile a Servlet Filter to implement the javax. servlet. Filter interface;
(2) modify the Web. xml file so that the container can know when the filter is called.
Javax. servlet. Filter mainly has three methods:
(1) init (FilterConfig cfg): When the servlet filter service is started, the container calls this method once. The FilterConfig parameter sent to this method contains the initialization parameters of the servlet filter;
(2) destroy (): The container calls this method when the servlet filter service is no longer used;
(3) doFilter (ServletRequest req, ServletResponse res, FilterChain chain): The container calls this method for each servlet Request mapped to this filter before calling the servlet itself. The FilterChain parameter passed to this method can be used to call the next filter in the filter chain. When the last filter in the chain calls the chain. doFilter () method, the initial requested servlet is run. Therefore, all filters should call the chain. doFilter () method. If the additional authentication check in the filter code causes a fault, you do not need to instantiate the original servlet. In this case, you do not need to call the chain. doFilter () method. Instead, you can redirect it to other error pages.
If the servlet maps to many servlet filters, the servlet filter is called according to the order in which the application deployment descriptor (web. xml) appears. The main code of this part is as follows:
// Class library to be introduced
Import javax. servlet .*;
Import javax. servlet. http. HttpServletResponse;
Import java. io .*;
Import java. security .*;
// Set the servlet filtering code segment
Public class cachefilter implements filter {
Protected filterconfig;
Private string cachetp;
// Initialization
Public void Init (filterconfig) throws servletexception
{
This. filterconfig = filterconfig;
Cachetp = config. getinitparameter ("cachecontroltype ");
If (cachetp = NULL)
{
Throw new servletexception ("No Cache control type defined ");
}
}
//
Public void destroy ()
{
This. filterconfig = NULL;
}
// Execute the filter section
Public void dofilter (servletrequest request, servletresponse response, filterchain chain)
Throws ioexception, servletexception {
If (response instanceof HttpServletResponse)
{
HttpServletResponse resp = (HttpServletResponse) response;
Resp. addHeader ("Cache-Control", cachetp );
}
Else
{
Throw new ServletException ("invalid! ");
}
Chain. doFilter (request, response );
}

}
The following content is added in Web. xml.


CacheFilter
CacheFilter
Cache filter

CacheControlType No-store


CacheFilter
/Cachecontrol

3. View Access Security Settings
All users must log on. Only logon can view the view of the user's role and permissions. Therefore, an important issue is how to prevent a view or a part of the view from being directly accessed by an unauthorized customer.
In some cases, resources are restricted to being completely inaccessible to some users. For example, common customer members should not be allowed to access the management background. There are several ways to do this. One method is to add the application logic to the program that processes the Controller or view and prohibit access by some users. Another solution is to set the runtime system. For some resources, it is only allowed to be called internally by another application resource. In this case, access to these resources must be performed through the application resources of another presentation layer, such as a servlet controller. These restricted resources cannot be directly called through a browser.
In J2EE, you can use the built-in security technology in Web containers to control role access to resources. According to the servlet and EJB specifications of the latest version, security is restricted on the web. description in the xml configuration description file, we can configure the web. xml to control role access, modify the configuration description file web. xml allows you to quickly modify security policies.
Security restrictions allow the use of programming methods to control access based on user roles. Resources can be accessed by users of some roles, and access by other roles is prohibited. In addition, a part of a view can also be restricted based on the user's role. If some resources do not allow direct access from the browser, these resources can be configured to allow access only by some special security roles, which are not assigned to any user. In this way, as long as this security role is not assigned, the resources configured in this way will be disabled for direct access by all browsers. The following example is part of the web. xml configuration file. It defines a secure role to restrict direct browser access. The role name is "vip", and the restricted resource names are specialgood1.jsp, specialgood2.jsp, specialgood3.jsp, and bookinfo. jsp. Unless a user or group is assigned a "vip" role, these customers cannot directly access these JSP pages. However, because internal requests are not subject to these security restrictions, a request initially processed by a servlet controller will be directed to these restricted pages, in this way, they can indirectly access these JSP pages.
<Security-constraint>
<Web-resource-collection>
<Web-resource-name> specialgood </web-resource-name>
<Description> special good infomation </description>
<Url-pattern>/shop/jsp/a1/specialgood1.jsp </url-pattern>
<Url-pattern>/shop/jsp/a1/specialgood2.jsp </url-pattern>
<Url-pattern>/shop/jsp/a1/specialgood3.jsp </url-pattern>
<Url-pattern>/shop/jsp/a1/bookinfo. jsp </url-pattern>
<Http-method> GET <Http-method> POST </Web-resource-collection>
<Auth-constraint>
<Role-name> vip </role-name>
</Auth-constraint>
</Security-constraint>
3 coupling problem and solution strategy between different layers
The data structure of the presentation layer, such as httpservletrequest, should be restricted to the presentation layer. If these details are placed on other layers (mainly the business logic layer), the code reusability is greatly reduced, the Code becomes complex, and inter-layer coupling is increased. A common solution is to avoid sharing the data structure at the presentation layer with the business layer, but to copy the relevant status to a more common data structure for sharing. You can also choose to separate related states from the data structure of the presentation layer and share them as independent parameters. In addition, when the data structure of the presentation layer is exposed to the domain object, if the data structure of the request processing such as httpservletrequest is shared with the domain object, this will also increase the coupling of two different aspects in the application. Domain objects should be reusable components. If their implementations depend on protocols or layer-related details, they may be poorly reusable, and it is more difficult to maintain and debug highly coupled applications. A mature solution is to copy the status of the request object to a more common data structure and share the object to the domain object instead of transmitting an httpservletrequest object as a parameter. You can also choose to separate related states from the httpservletrequest object and provide each State as an independent parameter to the domain object.
4. Security Design and Control of EJB
The execution process of EJB is generally as follows: (1) the client retrieves the reference of the home object through JNDI; (2) the JNDI returns the reference of the home object; (3) request to create a new EJB object; (4) Create an EJB object; (5) return an EJB object; (6) call a business method; (7) Call An enterprise Bean. there are three main causes of EJB security problems:
(1) Use packet sniffer to obtain user creden and directly call the session bean; (2) perform unauthorized access to the Entity Bean; (3) invalid access to the message-driven Bean (publish malicious or false messages ).
The above security issues can cause client or server spoofing attacks and DDOS attacks. Solution (1) the solution is to use SSL technology in JAVA to protect communication. (2) the method is to use local interfaces or JAAS (document [1]) for all entity beans. for (1) and (2), we can take the following measures at the same time: let the container complete authentication and transmit user creden。, and use declarative or program-designed security verification roles. For problem (3), J2EE does not provide a good solution. Our solution is to use the digital signature technology to ensure that information comes from a trusted source. The Combined Code of this method is briefly described as follows. messages are transmitted using JMS:
// The client uses the private key of the message sender for signature.
...
Message. setString ("userid", userid );
Message. setString ("useritem", useritem );
Message. setInt ("usersn", serialnum); // contains a serial number
Message. setString ("usercertid", certid );
String signature = getSignature (userid + ":" + useritem + ":" + serialnum + ":" + certid );
// Sign the message. getSignature is the signature function and the private key of the message sender is used for signature. For more information about cryptography, see [2].
Message. setString ("signature", signature );
Sendmessage (message); // send message
...
// Server
String checkstr = userid + ":" + message. getString ("useritem") + ":" +
Message. getInt ("usersn") + ":" + usercertid;
Boolean B _check = checkSignature (checkstr, msg. getString ("signature "),
Usercertid, userid );
// Perform verification. checkSignature is the verification function and must use the public key of the message sender for verification. For more information about cryptography, see [2].
5. CA center and certificate generation
We have already proposed to Use HTTPS and SSL on the client. Therefore, we need to establish a CA center to manage and distribute certificates, so as to enhance the communication security between the client and the server on the intermediate layer. the first step to establish a CA center is to use Keytool in the JAVA toolkit to generate an X509 Certificate, then submit the certificate to the authoritative CA center Vertsign for signature, and then set the certificate as the root certificate, create your own CA. each time a new user registers for a transaction, a unique user certificate must be issued. The key process is how to issue a certificate. the process of issuing a certificate is as follows:
(1) read the CA certificate from the keystore of the intermediate CA Server:
FileInputStream in = new FileInputStream (ShopCAstorename );
KeyStore ks = KeyStore. getInstance ("JKS ");
Ks. load (in, storepass );
Java. security. cert. Certificate c1 = ks. getCertificate (alias );
(2) obtain the private key of the CA:
PrivateKey caprk = (PrivateKey) ks. getKey (alias, cakeypass );
(3) extract issuer information from the CA certificate:
Byte [] encod1 = c1.getEncoded ();
X509CertImpl shopcimp1 = new X509CertImpl (encod1 );
X509CertInfo shopcinfo1 = (X509CertInfo) shopcimp1.get (X509CertImpl. NAME +
"." + X509CertImpl. INFO );
X500Name issuer = (X500Name) shopcinfo1.get (X509CertInfo. SUBJECT +
"." + CertificateIssuerName. DN_NAME );
(4) obtain information about the certificate to be issued, similar to (3;
(5) set the validity period, serial number, issuer, and signature algorithm of the new certificate:
// Set the validity period of the new certificate to one year.
Date begindate = new Date ();
Date enddate = new Date (begindate. getTime () + 3000*24*360*60 * 1000L); CertificateValidity cv = new CertificateValidity (begindate, enddate );
Cinfo2.set (X509CertInfo. VALIDITY, cv );
// Set the serial number of the new certificate
Int sn = (int) (maid. getTime ()/1000 );
CertificateSerialNumber csn = new CertificateSerialNumber (sn );
Cinfo2.set (X509CertInfo. SERIAL_NUMBER, csn );
// Set the new certificate issuer
Cinfo2.set (X509CertInfo. ISSUER + "." +
CertificateIssuerName. DN_NAME, issuer );
// Set the new certificate Algorithm
AlgorithmId algorithm =
New AlgorithmId (AlgorithmId. md5WithRSAEncryption_oid );
Cinfo2.set (CertificateAlgorithmId. NAME +
"." + CertificateAlgorithmId. ALGORITHM, algorithm );
(6) create a certificate and issue it:
// Create a certificate
X509CertImpl newcert = new X509CertImpl (cinfo2 );
// Signature
Newcert. sign (caprk, "MD5WithRSA ");
(7) provide the new certificate to the registered user and prompt for installation. The general practice is to immediately return a certificate object to a Servlet in the middle layer after the user registration is successful, it is returned to the user.
References
[1] Implementation of JAAS-based security mechanisms in EJB containers by Shen Yao, Chen haopeng, and Li xinyan. [J]: computer applications and software 2004.9-16 ~ 18
[2] (US) Jess Garms, translated by ponnan et al.. Java security programming guide [M]. Beijing: Electronics Industry Press 2002
[3] http://java.sun.com/j2ee/
[4] Cai Jian, Jing Nan. Java Network Programming: J2EE (including 1.4 latest functions) [M]. Beijing: Tsinghua University Press 2003
[5] (US) John Bell Tony Loton. Java Servlets 2.3 Programming Guide [M]. Beijing: Electronics Industry Press 2002
[6] (US) Joseph J. bamhei, translated by Liu Yi. J2EE technology insider [M]. Beijing: Machinery Industry Press 2002
[7] (US) Li Gong. JAVA 2 platform security technology-structure, API design and implementation [M]. Beijing: Machinery Industry Press 2000
[8] (English) Danny Ayers and others, translated by Zeng guoping. Java Server advanced programming [M]. Beijing: Machinery Industry Press 2005
Http://www.smatrix.org/bbs [9]
Http://www.smatrix.cn/bbs [10]
(You are welcome to reprint it, but you need to keep the author information! -By felshwound)

Trackback: http://tb.blog.csdn.net/TrackBack.aspx? PostId = 740484

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.