Set the Linux security environment for Java execution

Source: Internet
Author: User
Set the Linux security environment for running Java-general Linux technology-Linux programming and kernel information. The following is a detailed description. Enterprise Java expert Dennis Sosnoski elaborated on his point of view on how Java Server technology is suitable for Linux, and then gave some suggestions on setting Tomcat Java servlet Engine safely on Linux.


The Linux and Java platforms have a long history but often experience twists and turns. Building a high-performance Virtual Machine must keep up with the increasing collection of core Java APIs, the complexity brought about by this greatly makes it difficult to develop an open source program code "Clean Room" on the Java platform for early operations. The licensed Java technology can be used in Linux, but these implementations are not open source program code. Therefore, most Linux distributions do not include the licensed implementation.


Despite these difficulties, the Java platform provides many benefits, resulting in more and more use of this licensed implementation on Linux, especially for server applications. In this article, I reviewed the advantages of the Java platform for server applications, and then studied the problems involved in simple and secure deployment of Java services on Linux. As an actual example, I will discuss how to set detailed information about the widely used Tomcat Java servlet engine of the Apache Software Foundation for independent jobs.


Why Java Platform?


There are many reasons to explain why the Java platform has become a widely accepted choice for server-based commercial applications. I will mainly discuss three reasons that I think are critical to this environment? Cross-platform compatibility, Managed execution environment, and ease of development.


Java applications provide binary compatibility across multiple operating systems and hardware platforms. Especially for non-GUI server applications, in this type of applications, a very small number of tests are usually required in the actual target system. The staff can perform coding and debugging on any platform they like, while still deploying these applications to environments that they might not directly control.


Java Virtual Machine (JVM) Environment execution features in several ways to enhance program security. One of the most notable aspects is that the combination of strict class checks, array boundary checks, and automatic garbage collection completely prevents the most destructive form of server program code attacks? Buffer overflow, repeated release errors, and free pointers. The Java language was used for applet in the early days. With the development, the language also has a complete system for fine-grained access control over facilities that are already at risk of security. These methods are available for independent applications, but they have been built into the architecture of many Java services.


These program security features also provide the convenience of Java development. It is difficult to make any precise measurement of the category of convenience, however, most staff who turn to Java programmers who have a background in languages such as C and C ++ admit that their productivity has increased since the change. This is partly because class type determination is strictly executed during compilation and execution, and the simplicity of automatic memory management. Another factor is the set of standard APIs developed for the Java platform. These APIs may be a major challenge for new staff, but once learned, they will provide excellent cross-platform support for various enterprise needs.


Of course, for some applications, the Java platform may be a bad choice. Although the JVM architecture is continuously improved, Java applications generally run slightly slower than C or C ++ applications using the same algorithm. Based on my experience and tests, I estimate that the speed difference is within the range of 20% to 50% for most server applications executed on the licensed JVM, however, this depends largely on the quality of the program code. Compared with stand-alone programs, Java applications executed on these JVMs still endure slow startup, but this is not a major problem for long-running server applications. In most cases, the performance is reduced and the start time is slow? It is a small cost for obtaining enhanced security and faster development advantages of the Java platform.


Open source code alternative


In addition to the standard licensed JVM (free of charge, but restricted by source code; available for Linux in the Sun, IBM, BEA, and Blackdown organizations), there are several other alternatives to Linux. These options include the "Clean Room" open source JVM implementation, among which Kaffe (included in many Linux distributions) is the most widely used ). Kaffe is a very meaningful project and it has done some surprising work, but it can only provide limited compatibility with the currently licensed JVM. Therefore, it is generally not applicable to enterprise-class server applications.


There are also several alternative options for the open source code of the local program code compiler for Java programs. The most important project here is the GCJ of the GNU Compiler set (GNU Compiler Collection. Using a native program code compiler, such as CGJ, converts platform-specific Java bytecode into platform-specific program code prior to execution (this is a comparison with execution in JVM, in JVM, bytecode is usually converted into platform-specific program code during execution ).


The compilation of local program code shows that it is very likely to become a method to avoid slow startup of Java applications executed in JVM. However, compilers using this method usually cannot match the stable state performance of the contemporary chartered JVM. This situation is particularly prominent if Java applications use dynamic features of the Java platform (such as using reflection to access fields or load the classes selected during execution. Depending on the implementation and compilation options used, the compilation of local program code may also weaken many of the security features of the Java platform during execution. Finally, due to license issues, many Java APIs cannot be used with compiled local program code. Due to these restrictions, compilation of local program code is not a good choice for Java platform server applications.


C # how?


One alternative to the Java Runtime Environment is Microsoft's C # Language and related Common Language Runtime (CLR ). C # is a closely related derivative of the Java language. CLR may allow C # to be used on many platforms. CLR also provides many JVM execution-time security features (despite escaping from the exit that seriously weakens security assurance ). Microsoft. Net also supports the option to pre-compile the code into the local program for faster startup, which is the same as what GCJ does for Java bytecode. Of course, Linux users cannot directly use this function, because. Net is only applicable to Windows systems.


Mono Project is committed to building "CLean Room" open source code C # for a variety of Linux products and products equivalent to CLR. Now, the C # compiler in this project has been developed and most of the CLR has been completed. Microsoft has released it for standardization. However, from the perspective of performance and functionality, there is still much work to be done before it becomes a reasonable alternative to the Java platform. CLR only includes the basic content equivalent to the Java core category library. Before we can regard it as a reasonable option for enterprise software development, we need to use many additional APIs to supplement it.


The Mono Project is dedicated to developing projects other than CLR.. Net, if the transplantation is successful, and if Microsoft is incorrect. these parts of Net impose its patent rights-then they will help meet the needs of C # to become a reliable platform for Linux server software development. However, to make those assumptions a reality, you still need to do a lot of work. At the same time, java program native program code compiler and open source JVM provide stable alternative options for those who really want to avoid having to use a licensed JVM and can tolerate limited functionality.


Apache Tomcat


Apache Tomcat is one of the most common Java platform server applications. Tomcat is an open source project based on the source code originally donated by Sun. It is an HTTP server and is an official reference implementation developed by Sun through Java Community Process for the widely used servlet and JavaServer Page (JSP) technology. I will use Tomcat as a sample Java application in this article and deploy it as a service on Linux. If you want to execute Tomcat by yourself, you need to install the Java Development Kit (JDK) on the system, instead of installing a smaller Java execution Environment (Java Runtime Environment, JRE ).


Servlet and JSP technologies are used to construct HTTP server applications. Although servlet technology has added many features (including access security, Session management, and execution thread control), what about it? It is roughly equivalent to a CGI interface customized for fast and direct calls in Java. JSP technology provides a simple way to process dynamically generated HTML pages. These HTML pages are directly compiled into servlets for quick execution.


In addition to these two technologies, Tomcat also provides many other features. Based on its own performance, it is actually a full-featured Web server, but it is usually used together with the Apache Web Server front-end on Linux systems. Apache provides Tomcat with a lot of advanced performance for static content. Apache front-end is very useful for Web applications with a high proportion of static content and high usage. However, many simple Web applications do not need to be used. When it is easier to configure and manage, executing Tomcat alone can provide sufficient performance (at least for those who have never used Apache before ).


Port connection problems


One major problem with executing Tomcat separately is that it cannot access the standard HTTP port 80 unless it is executed as a root user. The idea of running server applications as root users is generally not discussed by streaming companies, so I will give up this idea completely? Using ports other than 80 is a better choice (for example, Tomcat default port 8080 ). This is usually applicable to testing, but when the user is accessing the service, it will lead to messy URLs, because the connection port number needs to be clearly stated in the request. The use of non-standard ports also means that if external access is required, all firewalls need to be reconfigured.


Xinetd Solution


Fortunately, Linux supports some simple methods to process port 80 requests using Tomcat (or any other user application. A common method is through xinetd. Xinetd is an Internet service daemon with extensive access control and logging support. It also has convenient and reoriented features. Redirection allows you to configure the system to accept incoming requests from one connection port, and then pass the requests to another connection port or even another IP address for processing.

If you want to set Tomcat on the system to process port 80 requests, you need to add the xinetd configuration file to implement this purpose. Assuming that xinetd is installed in a normal path, you can add a file (as root user) to the/etc/xinetd. d directory to execute this job. Listing 1 provides a sample configuration file for Tomcat.


Listing 1. xinetd redirection Configuration



# Redirects any requests on port 80

# To port 8080 (where Tomcat is listening)

Service tomcat

{

Socket_type = stream

Protocol = tcp

User = root

Wait = no

Port = 80

Redirectly = localhost 8080

Disable = no

}


After adding the configuration file, you need to restart xinetd to truly activate and redirect. In most Linux installations, run the following command as the root user to restart xinetd?


/Sbin/service xinetd restart


? You need to put the configuration file in the/etc/xinetd. d directory. When the system is restarted, the system will be automatically started. If Tomcat is not set to automatically started, the request is rejected before Tomcat is started.


Iptables Solution


Xinetd is a good method for processing request redirection, But it executes a processing order to actually transfer data between connection ports, which indeed increases some overhead. The latest Linux kernel version supports a better way to set redirection by using iptables. The difference between iptables and xinetd is that iptables is a real kernel component. Therefore, it can avoid the overhead added by the xinetd method. The only drawback of using iptables is that it may be more difficult to configure than xinetd, and it can only be used for newer kernel versions.


You need to execute 2.4.x or an updated kernel that supports iptables to use the technology I described here. Configuring and setting iptables is a topic that is determined to be described separately by several articles, so I am not planning to discuss it here. If you need help with iptables, read the Linux distribution manual. To quickly check whether iptables is executed on your system and try to run it as a root user?


/Sbin/service iptables status


If it is being executed, you will see the list of tables and links on the console.


Iptables uses several different tables and encapsulation chains to process rules. To redirect an HTTP request from port 80 to another port in the system, you will use the nat table (Network Address Translation, Network Address Translation) and PREROUTING chain. Listing 2 provides the actual commands to be executed (as a root user) to facilitate the addition of a rule for processing this request. This rule is used to change the target connection port 80 of the incoming packet to the target connection port 8080? This rule works correctly only when you do not prevent external use of port 8080. Once this command is executed, you should be able to immediately process incoming requests.


Listing 2. iptables redirection rules



/Sbin/iptables-t nat \

-A prerouting-j REDIRECT-p tcp \

-- Destination-port 80: 80 -- to-ports 8080


/Sbin/service iptables save


To store the current iptables configuration.


Automatically start Tomcat


Another problem when executing other Java services such as Tomcat is how to automatically start the application when the system starts and how to automatically stop the application when the system shuts down (in other words, run it as a daemon ). Experienced Linux users already know how to do this, but if you are a new Linux user, the following are some basic knowledge.


If you want to execute it on your personal system and want to access Tomcat files and directories like directly executing Tomcat, you can set it with your own user name. However, what is a good idea? Set a separate user for any program to be executed as a daemon. To execute this job for Tomcat, run it as the root user?


/Usr/sbin/useradd tomcat


This creates a user account named tomcat and a home directory/home/Tomcat for tomcat installation. The owner of the created home directory is a tomcat user, and only this user is allowed to access it (of course there are root users ). If you want to access Tomcat installation from another account, you can change the permission to include group access and add the tomcat group to these other accounts.


To execute Tomcat as a daemon, you need to add the service configuration file to the/etc/init. d directory, and you may need to name the file "tomcat 」. Listing 3 provides a sample of the file. This assumes that Tomcat is installed under/home/tomcat, and there are two shell script files in this location for processing the start and stop servers (tcstart. sh and tcstop. sh ). You need to use these files to set the environment variables (including JAVA_HOME and JDK_HOME) required for Tomcat before executing the actual Tomcat startup or stop command code ).


Listing 3. Tomcat service definition



#! /Bin/bash

#

# Tomcat Starts Tomcat Java server.

#

#

# Chkconfig: 345 88 12

# Description: Tomcat is the server for Java servlet applications.

### BEGIN INIT INFO

# Provides: $ tomcat

### END INIT INFO


# Source function library.

./Etc/init. d/functions


[-F/home/tomcat/tcstart. sh] | exit 0

[-F/home/tomcat/tcstop. sh] | exit 0


RETVAL = 0


Umask 077


Start (){

Echo-n $ "Starting Tomcat Java server :"

Daemon su-c/home/tomcat/tcstart. sh tomcat

Echo

Return $ RETVAL

}

Stop (){

Echo-n $ "Shutting down Tomcat Java server :"

Daemon su-c/home/tomcat/tcstop. sh tomcat

Echo

Return $ RETVAL

}

Restart (){

Stop

Start

}

Case "$1" in

Start)

Start

;;

Stop)

Stop

;;

Restart | reload)

Restart

;;

*)

Echo $ "Usage: $0 {start | stop | restart }"

Exit 1

Esac


Exit $?



The following is a sample tcstart. sh, which can be modified to suit your installation.


Listing 4. Sample tcstart. sh

 



#! /Bin/bash

Export JDK_HOME =/usr/java/jdk

Export JAVA_HOME =/usr/java/jdk

# Run the startup script from Tomcat installation

/Home/tomcat/server/bin/startup. sh


Chroot? Largest Security Prison


For the true paranoia, we may further discuss the protection of Java language services. This is especially useful when the service provides some form of access to the local file system. The security feature during JVM execution does not prevent applications that have the right to access the file system from accessing files other than user-specific files. In Tomcat, file access is inherent in the use of the HTTP server. It usually limits the files that provide services for each Web application to those in the application directory, but servlet applications can avoid these restrictions. This also happens when Tomcat is executed together with other front-end Web servers such as Apache.


By using chroot, you can prevent Tomcat (and all Web applications executed under Tomcat) from accessing anything other than the space reserved for the server. Chroot is not specific to Java applications in any way, but it is an easy way to add the final wrapper to the security provided by JVM. Here I will introduce the key points for those who are not familiar with the chroot concept.


The chroot class is similar to the JVM sandbox used to execute Java program code, but it applies to the file system itself. Chroot executes a command and sets the specified location to a valid root directory. The executed command (which can be a shell script that executes other commands (including applications) can only be part of the file system in the specified valid root directory. The rest of the file system does not exist for this command.


To use chroot for applications such as Tomcat, copy some basic system applications and link libraries (including the actual Java JDK installation) to the new virtual root directory. This may take up a lot of space-perhaps from one hundred MB to one thousand MB or more-depending on how much effort you are trying to minimize these applications and linked libraries. The simplest way to set it is also a waste of space ?? To copy the entire/bin,/lib,/usr/bin,/usr/lib directory tree, and Java installation to the new root directory, make the root user the owner of all files and the writer with unique authorization. To minimize disk usage, You can selectively copy only the commands required by the chroot instance (including basic commands such as ls, rm, echo, cat, and actual Java installation) and the databases used by the commands (which can be found by using ldd ).


Next, you will need to create some additional directories as the general system version reduction. This includes/dev, and the device/dev/null and/dev/zero; the edited versions of/etc and/etc/passwd and/etc/group files (only the root and tomcat items are retained), and hosts may exist. If you are running on a multi-processor system, you also need to mount the/proc system in the new root directory because JVM uses this system to coordinate various processors.


Finally, in order to run the command as user tomcat after chroot is set, you may need to build a su command version that can be executed under the virtual root directory (the general version of many distribution versions does not allow this ). To do this, you can obtain the sh-utils source code from the GNU project, build su directly based on the source code, and then copy it to the/bin directory of the new root directory.


After all these settings are complete, you can try to execute them as the root user (assuming that the new root directory is located at/home/tomcat )?


/Usr/sbin/chroot/home/tomcat/bin/su tomcat


If the setting is correct, you should execute the command as tomcat in the new root directory, and you can try to start and stop Tomcat using your script code. After confirming that everything works, The last step is to change the Tomcat service definition in listing 3 to use chroot instead of su and move the su command to tcstart. sh command code and tcstop. sh command code. You also need to make sure that only the root user can modify these script codes.


I hope this overview is clearly explained. Isn't this process suitable for Timid people? If you choose to use the chroot route, but you have never used chroot before, you must refer to one of the chroot reference data on the Internet for details. But this does give your Java server program code the best possible isolation, and in some cases, the inner peace is worth doing.


Conclusion


Both Linux and Java technologies are winning the market share of commercial systems. Although there is a theoretical difference between open source Linux and the licensed Java technology, the two work well together. Linux is an excellent deployment environment for Java applications, especially server-type applications, and Java technology is established and recognized as an advanced method for enterprise software development.


Through proper preventive measures, java Server Applications executed on Linux provide a very high level of security-or even higher than local applications-Because Java eliminates common sources of many vulnerabilities in server applications. The cross-platform nature of Java brings about a huge set of resources including enterprise staff and applications ready for Linux. Java server applications are beginning to play an important role in the growing Linux server market share, and this trend will only help these two technologies in the future.


I would like to thank Miles Sabin for pointing out to me the/proc file system to solve the chroot Java problem on a multi-processor system.
Related Article

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.