Improving Apache Tomcat Security – A Step By Step Guide Rumi, March 21, 2012 Apache Tomcat boasts an impressive track record when it comes to security. According to the official Apache Tomcat Wiki Pages, there has never been a reported case of actual damage or significant data loss due to a malicious attack on any Apache Tomcat instance. Most vulnerabilities, both major and minor, are discovered by the Tomcat community itself or security researchers, and quickly patched. Thus, the default installation of Tomcat can be said to be "fairly secure". Starting from this baseline, there are additional measures that can be taken to make Tomcat as secure as possible for a given use case. As with any security scenario, Tomcat security is a matter of balancing ease of use and access with restriction and hardening of access. For example, although it is technically more secure to disable Tomcat's deployment capabilities when moving to production, for many organizations the desire to automate deployment supersedes the security benefit of disabling these features. In this article, we will provide an big picture overview of the security capabilities included in Tomcat. In order to implement these practices effectively, administrators should create a well-researched profile of the systems they oversee, and work from this clear set of needs to determine what security improvements can be made. This article covers three categories of security improvement: changes to Tomcat's internal configuration, changes to the operating system on which Tomcat is running, and best security practices for web applications. Don't take chances on your network's Security. Use Tcat to easily enforce secure, consistent configurations across your entire infrastructure from an intuitive central console. Hardening Apache Tomcat In this section, we'll look at things you can do to tune the security of your Tomcat instances to better match your access and functionality requirements. Stay Current As Tomcat is an active open source project, the easiest way to improve the security of your instance is to keep your version up to date and keep up with the Tomcat mailing lists. New bug fixes and security patches are added in every release, and new issues that may apply to your infrastructure are discussed on the Tomcat mailing lists. Apache also notifies community members of major security threats and patches through the Tomcat Announce mailing list. Always upgrade to the latest stable version of Tomcat as soon as possible. Maintain And Use Logs Well-maintained access logs are a vital tool in identifying security holes and sources of attack. In a development environment, it is not always obvious what kinds of malicious activity you should defend against. Maintaining logs once moving to production will help make sure an application which seems secure in development stays secure in the real world. Logs should be maintained on multiple levels – user access, application traffic, Tomcat internals, and OS/firewall, and a single process for reviewing and acting upon logs should be agreed upon by all system administrators. To enable logging of network traffic in Tomcat, use the AccessLogValve component. This element, which can be configured on a Host, Engine, or Context basis, will create a standard web server log file for traffic to any resources associated with it. The Access Log Valve supports a variety of attributes to control the output of the valve. For detailed information about configuring the AccessLogValve, click here. Note that if you are proxying requests to Tomcat through another server, you should also enable logging there. Controlling Access As Tomcat starts with such a good baseline of security, many of the steps you can take to further increase its security involve limiting access to certain resources. Deployment Settings Tomcat "Host" components can be configured to allow various automated deployment scenarios. These are very useful during development, and as continuous deployment becomes more common, a growing number of development teams will want to use these features in production. Any Host can be configured to automatically deploy applications based on one of three parameters – autoDeploy, deployOnStartup, and deployXML. (If you would like more information about how these attributes work, please visit our Tomcat Deployment Guide.) If you do not require automatic deployment, it is a good idea to set these attributes to 'false' – not only can they cause problems due to authorized user error, but they make it easier for an attacker to cause trouble if they gain access to the server. SecurityManager The SecurityManager is a Java component that allows Contexts to be run within inpidual sandboxes. Each sandbox can be configured with different privileges, providing more granular control over their access to system resources and potentially preventing one breached application from allowing access to others. (For an overview of the standard SecurityManager classes, click here). The SecurityManager is normally controlled by a file called "java.policy," which is distributed with the SDK. Tomcat uses the file $CATALINA_BASE/conf/catalina.policy in place of this file. Tomcat also introduces a custom class – org.apache.naming.JndiPermission – that controls access to JNDI resources. However, the format of catalina.policy is the standard policy format: //Example entry grant [signedBy <signer>,] [codeBase <code source>] { permission <class> [<name> [, <action list>]]; }; The downside of using the SecurityManager is that as most applications are not originally designed in to run within a sandbox, the SecurityManager has a reputation for breaking web applications by introducing hard to find permission errors. Running applications within the SecurityManager generally requires users to write custom permissions rules, debug resulting issues, and thoroughly test configurations. Thus, this security practice should generally be implemented in conjunction with the development team. The SecurityManager HOW-TO in the Apache Tomcat documentation includes a Troubleshooting section with some hints for developers facing these issues. For detailed information about running Tomcat with SecurityManager, visit the official Tomcat documentation. The Tomcat Manager Webapp The Tomcat Manager application is a basic web-based Tomcat administrative console for controlling Tomcat instances, application deployment, and other settings. For security reasons, Manager is disabled by default – in fact, a User with privileges to access it is not even configured in tomcat-users.xml. Gaining access to the Tomcat Manager would give an attacker considerable control over your Tomcat instance. The first question you should ask is whether you need access to the Manager at all. If you are using an alternative method of administering your Tomcat instances, it's best to leave the Manager disabled. If you do need to use the Manager application, there are a number of configuration options and best practices you can enforce to limit the risk associated with running it. Limit access The only people that need access to the Manager application are administrators. Access to the Manager application should be limited to known IP addresses (this can be accomplished by using either a RemoteHostValve or RemoteAddrValve component). As an additional precaution, you can run the Manager web application within a special type of Tomcat realm called the LockOut Realm. The standard Tomcat Realm component allows unlimited authorization attempts, opening the door to brute force attacks from a spoofed IP address. The LockOut Realm prevents this by placing a limit on the number of log in attempts within a given time period before a user is locked out of the system. Don't be sloppy Treat access to the Manager application like you would any other important resource, such as a bank account. Enforce the use of strong passwords, don't visit other sites while logged in, and make sure to log out. Most importantly, make sure that anyone else who will be access the application understands and follows the same guidelines. Note that Tomcat 7, currently in beta, includes an improved Manager application, which features more granular roles. This will allow Manager configurations to be less "all or nothing". Realms One method of controlling access to resources in Tomcat is the use of Realms – components that access databases of users that should have access to a given application or group of applications, and the roles/privileges they have within the application once they have logged in. Tomcat includes 6 Realm implementations total: MemoryRealm, JDBCRealm, JAASRealm, UserDatabaseRealm, JNDIRealm, DataSourceRealm. In addition to these, as of Tomcat 6.0.2, two additional pseudo-implementations have been included: LockOut Realm and CombinedRealm Out of these, two – MemoryRealm and JDBCRealm – should not be used as a rule. These Realms have been replaced by the DatabaseRealm and DataSource realms, respectively. This has decreased their use, and thus, the number of bugs (and bug fixes) provided for them has gone down. The replacement realms offer better features in addition to better security, such as thread pooling. The most secure Realm overall is the LockOut Realm, which, as mentioned in the previous section, places a limit on the number of times a user can attempt to authenticate themselves. If you require features from more than one Realm, the CombinedRealm can be used to configure more than one Realm implementation per Engine/Host/Context. Miscellaneous Configuration Options Here are some additional configuration options you can enable to further secure your instances: Shutdown Port By default, Tomcat servers listen on localhost to Port 8005 for shutdown commands. This address is configured via the Server component's "port" attribute: <Server port="VALUE" …/> If your scenario allows it, setting the port to "-1" will better secure your server from unintended shutdowns. With this configuration, Tomcat can only be shutdown via the Terminal by the User that owns the Tomcat process, via a "kill" command. This standard kill will trigger an identical graceful shutdown process to issuing the shutdown command, but in a more secure fashion. Limiting Connector availability By default, connectors listen to all interfaces. Using the "address" attribute of the Tomcat Connector element, you can force the Connector to ignore any interfaces that are not required for your web application. If you need more help configuring connectors, please read our simple Tomcat Connector guide. Secure Webapp Configuration Although appropriate/feasible security measures for web applications will naturally vary from context to context, there are a few practices that apply to all: If there is no reason for any other mechanism to access your application's session cookies, limit access to HTTP only. This is configured in the Context component: <Context useHttpOnly='true' …/> Think twice before enabling attributes that allow increased privileges on a server: Setting the "crossContext" attribute of the Context element to "true" opens your server to the possibility of a corrupted application sending malicious requests to other applications (there is no way to block requests from other applications, only this attribute, that controls whether an application can create them). Enabling symlinks in your web application via the "allowLinking" Context attribute is necessary for some applications. However, when used with a file system that is not case sensitive, it will cause source code disclosure issues. Make sure your file system is case sensitive before implementing it. Lastly, and most obviously, using the "privileged" Context attribute to allow access to Tomcat internals should be avoided unless absolutely necessary, and greater care should be taken to restrict access to these applications. Hardening The Operating System Even if your Apache Tomcat configuration is as secure as possible, an insecure operating system will quickly render your work useless. In this section, we'll look at some steps you can take to secure your server machines themselves. When configuring security options in Tomcat, there is a large degree of compromise factored into the equation – better security often means sacrificing usability. When configuring the underlying operating system, this should be less of a problem. A good rule of thumb is to try to start by giving as little access to the operating system as possible, and then build on the configuration from there until you've reached the bare minimum of system access required for Tomcat to run without errors. Don't Run As Root When running any internet service, it's always a good idea to avoid running it as the root user if possible – the chances of an attacker gaining control of the server and thus the system are too great. When installing Tomcat, make the creation of a new user with a minimum set of privileges that will always run Tomcat for you part of your configuration process. (Note that restricting privileges in this fashion can introduce problems with listening to privileged ports. These are commonly solved by using JSVC, a reverse proxy such as HTTPD, or the iptables tool to invoke the root user and bind the appropriate port to the Tomcat user.) Configuring Your Firewall Your operating system firewall is a powerful line of defense for your server – don't run Tomcat without it. When configuring the firewall, you can use the same rule of thumb as for all OS settings – block everything, and then add privileges one at a time until you have allowed the minimum amount of access required for your scenario. When determining what traffic will be allowed, be sure to consider both inbound and outbound activity. There is no reason to allow outbound activity via interfaces that you do not need, which could potentially be exploited by malicious applications (for example, outbound HTTP requests are often used by malware programs to communicate with operators). Determining Minimum Privileges The User you create to run Tomcat should be allowed only the minimum privileges required to run Tomcat as required by your scenario. From a security standpoint, the ideal user will only have permission to read files, period. However, many users may find it necessary or convenient to allow the modification of start-up scripts and configuration files, or the deployment of new web applications. Whatever configuration you use, simply make sure that you are aware of the associated risks. Securing Your Web Applications Poorly secured web applications represent the single greatest security risk for Apache Tomcat. No matter how much you restrict a web application, whether placing it in a sandbox, limiting its access to resources, or limiting access to specific users, any non-trivial web application will most likely have access to some form of sensitive data, or at least represent an attractive target for a disruption/denial of service attack. In this section, we'll go over some common security risks affecting web applications, and some things you can do to make your web applications as secure as possible. HTTP Request Model Vulnerabilities Some amount of communication via HTTP is unavoidable for the majority of outward-facing web applications, making this a popular channel for attack. Malicious HTTP requests can be used to attempt a wide variety of attacks, including: XSS – Cross-Site Scripting, or XSS, is an attack that exploits holes in client-side security to inject malicious script into an application, which is then used to elevate privileges, steal session cookies, scrape page content, etc. CSRF – Cross-Site Request Forgery, or CSRF, is an attack similar to XSS. However, rather than relying on a user's trust for a site to gain access, these attacks exploit trust mechanisms used between two websites when exchanging information to inject code into privileged pages. SQL Injection – this attack exploits applications that fail to properly filter user-generated SQL statements for string literal escape characters or which do not 'strongly type' user input. Escape characters, such as quotation marks or operators, when improperly filtered, can be used to change the function of a specific query to force disclosure of hidden information or erroneously validate a user. Fields that are not "strongly typed" (i.e., a field that requests a numeric variable but does not verify that the user input is numeric) can be exploited in a similar manner. Request Header Exploits – if an application contains errors in its header-writing code, it is often possible for an attacker to force the disclosure of information about the server version, port address, and more by sending malformed requests. Request URI Exploits – these attacks attempt to make an application which uses the URI to store certain non-trivial session data expose secure data via maliciously crafted requests Preventing Attacks There are a number steps you can take to secure your web applications against the attacks described above. Testing For Vulnerabilities In addition to manually investigating known vulnerabilities, there are a number of well-respected scanning tools available for testing web application vulnerability. These include commercial offerings such as IBM Rational AppScan, HP WebInspect, and Acunetix Web Vulnerability Scanner, as well as open source tools such as Ratproxy. Testing should follow a format similar to the one described below: Scan Research / Repair Found Vulnerabilities Repeat scan Harding Your Web Application Configuration A secure web application should have as many of the following characteristics as possible: Enforced HTTPS No Caching Of Secure Data No Small Key Length Ciphers CSRF and XSS Attack Filtering Enforced HTTPS Forcing HTTPS for all transactions in Tomcat is a multistep process. The HTTPS connector must be configured, the HTTP connector must re-direct to HTTPS, and the web application's deployment descriptor must specify HTTPS as the default protocol. For detailed step-by-step information about creating a keystore and configuring HTTPS/SSL, please visit our Simple Guide To Tomcat SSL Configuration [www.mulesoft.com/tomcat-ssl]. For quick reference, see the common HTTPS configuration below: <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true" maxThreads="450" scheme="https" secure="true" clientAuth="false" sslProtocol="TLS” keystoreFile="conf/keystore" keystorePass="yourpass" proxyHost="10.1.1.1" proxyPort="443" URIEncoding="UTF-8" maxHttpHeaderSize="32768"/> Next, to ensure that your web application always uses HTTPS, configure your HTTP connector to redirect all traffic to the HTTPS connector by specifying the same port as you configured in the previous step using the "redirectPort" attribute. See the example below: <Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="443" proxyHost="10.1.1.1" proxyPort="80" URIEncoding="UTF-8" maxHttpHeaderSize="32768"/> Finally, configure the appropriate transport guarantees in your web application's deployment descriptor (appName/WEB-INF/web.xml). An example configuration is shown below: <security-constraint> <web-resource-collection> <web-resource-name>SecureConnection</web-resource-name> <!– set all URL patterns within the context to trigger a secure connection –> <url-pattern>/*</url-pattern </web-resource-collection> <!– force HTTPS for the application –> <user-data-constraint> <transport-guarantee>CONFIDENTIAL</transport-guarantee> </user-data-constraint> </security constraint <–! allow Favicons –> <security-constraint> <web-resource-collection> <web-resource-name>NonSecureConnectionOK</web-resource-name> <url-pattern>*.ico</url-pattern> </web-resource-collection> <user-data-constraint> <transport-guarantee>NONE</transport-guarantee> </user-data-constraint> </security-constraint> Finally, specify "strong" encryption systems for use with your encrypted data, using the "ciphers" attribute of the Connector element (separate suites with commons): <Connector ciphers="SSL_RSA_WITH_RC4_128_MD5,SSL_RSA_WITH_RC4_128_SHA,…"> For more information about the benefits and features of various cipher suites, visit the Java 6 documentation. Disable Caching Of Secure Data One commonly overlooked web application vulnerability is allowing a proxy server to cache a secure page. While caching can speed up the loading of pages, allowing secure data to be cached by the proxy server introduces an unacceptable level of risk. Use the following settings as appropriate in your application code to ensure that proxy caching for secure pages is disabled: // Standard HTTP 1.1 no-cache header httpResponse.setHeader("Cache-Control", "no-cache,must-revalidate"); // Set IE extended HTTP 1.1 no-cache header httpResponse.addHeader("Cache-Control", "post-check=0,pre-check=0"); // Tell proxy caches not to cache a given resource httpResponse.addHeader("Cache-Control", "proxy-revalidate"); // Standard HTTP 1.0 cache disabling header httpResponse.setHeader("Pragma", "no-cache"); // Standard HTTP 1.0 cache disabling header, prevents caching at the proxy server httpResponse.setDateHeader("Expires", 0); Permissions There are a few other web application security tips that any developer should try to follow if possible; these are centered around a secure permissions configuration. First, avoid writing files to your web application's tree – this requires giving access to your application itself, and should be avoided. Next, narrow the number of areas on your system to which you grant access to the smallest possible number. Ideally, the only areas of the system that any component should have read-write access to are conf/Catalia, conf/Catalina/localhost, the work/, temp/, and log/ directories, and the webapps/ directory (not the web apps themselves). Implement Best Practices As the most widely used Java application server in the world, Apache Tomcat is the only web server for which the Center for Internet Security has published a benchmark. The CIS Tomcat Security Benchmark includes a long list of other best practices you should consider implementing once you have completed the basic due diligence on your system. To download the Tomcat benchmark or any of the Center for Internet Security's other benchmarks, click here. Tcat – Security Made Simple As you might have noticed, there is no magic button to make Tomcat more secure. All the gains in security come with the cost of creating a custom configuration that corresponds to your infrastructure. Using Tcat Server, you can make sure you only have to do that work once. Tcat Profiles allow you to save common configurations and apply them to other instances or groups of instances with a single click, from a central management console. Tcat is based on 100% Apache Tomcat, and runs in front of existing Tomcat infrastructure, so there's no rip and replace! The full edition of Tcat is completely free to download and use during development and pre-production. Download Tcat today! Src: http://www.mulesoft.com/tomcat-security Configurations (Linux) Tomcat