The main script of tomcat, catalina.bat, accepts a parameter called ‘-security‘. When starting tomcat with this parameter, a security manager will be installed in order to protect you from malicious applications hosted on your tomcat.
As same as j2se, a policy file called catalina.policy would be used by the security manager to decide whether an operation is allowed.
For example, I have an web application packaged as a war. The war is placed into my home directory. A context file called "simple.xml" has been created and placed into {CATALINA_HOME}/conf/Catalina/localhost.
Tomcat will unpack this war into its webapps folder. So the codes are running from CATALINA_HOME/webapps/simple.
The testing servlet will try to write something into a temp file and then read it out. The source codes are
private void WriteSomething(HttpServletResponse response) throws IOException { File file = File.createTempFile("servlet", null); OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream( file), "iso-8859-1"); osw.write("Written by servlet!"); osw.close(); response.setContentType("text/html"); response.getWriter().write( "A string has been written into " + file.getAbsolutePath() + "<br>"); InputStreamReader isr = new InputStreamReader(new FileInputStream(file)); char[] str = new char[200]; isr.read(str); response.getWriter().write("The content is " + new String(str) + " <br>"); }
When the security manager is installed, operations like read/write disk file will be checked. An exception will be thrown when accessing this servlet. The only way to let it function is to grant it some permission.
Tomcat‘s policy file is catalina.policy, located in conf folder. To the above servlet, the permission need to be granted is
The detailed parameter format about FilePermission is described elsewhere. One thing to note is FilePermission is in java.io package, NOT java.security package.
One interesting thing here is place holders can appear anywhere in the file. I am not sure yet these placeholders refers to available JVM system properties. In the above example, catalina.baserefers to the installation folder. It is "/opt/tomcat" on my linux.
The temp file the servlet attemp to create would be a file within catalina.base/temp, It is "/opt/tomcat/temp" on my linux.
Alternatively you can use java.security.AllPermission to permit any opeartions.