Check java.policy at Build Time to Avoid Runtime Errors

Check java.policy at Build Time to Avoid Runtime Errors

he changes to Java’s security implementation have made it more robust and introduced more programmatic hooks for developers to add to Java’s default security mechanisms. Oddly, even with the introduction of Java Authentication and Authorization Services (JAAS) and its subsequent inclusion in the core API as of JDK 1.4, Java security still relies on a structured text format for its core configuration files: java.security and java.policy. While it is well known that there is a certain amount of overhead to parse XML files, the idiosyncratic layout of a security “grant block” in java.policy means that there are no standard tools to effectively verify its syntactic correctness at build time.

If your security needs are minor, your policy file simple, and your team is small, then it is unlikely that you view this as a serious shortcoming. However, if your environment and security needs are complex, and your team is fairly large then there is ample opportunity to inadvertently introduce syntactic errors into the java.policy file that won’t be recognized until runtime. While extending the Policy class to be backed by an XML file is an option, frequently Sun’s default implementation is what is relied upon and this leaves open the possibility of runtime issues arising with the java.policy file.

To remedy this situation, I coded a simple utility to check java.policy and let me know whether it is syntactically correct. The utility also prints out the specified permissions for each codebase of interest. This article will walk you through the code (download it here or from the link in the left-hand column) and discuss the utility’s function as well as some of the basics of Java 2 security.

What You Need
Java 1.3 or later version. 1.3 has reached its “end of life” according to Sun so I recommend downloading at least 1.4x if you can.

As you read this article it will be helpful to have your java.policy and java.security files available. These two essential Java configuration files are located by default in the ${JAVA_HOME}/jre/lib/security directory. The security.policy file’s role with respect to permissions is that it allows you to specify the policy files that are to be consulted by your application. The permissions in the file URLs that are specified are cumulative, meaning that they are aggregated at runtime to create the full list of permissions allocated to your application(s). The two URLs noted by default are listed below and while there is some benefit to adhering to standard locations for your policy file there is nothing that prevents you from changing it.

policy.url.1=file:${java.home}/lib/security/java.policypolicy.url.2=file:${user.home}/.java.policy

A replacement location can be specified with the VM argument:

Djava.security.manager=C:your_policy_name.policy

Also note that while you can use the policy.url mechanism to specify multiple policy files you only need one and you can name it whatever you’d like.

The security.policy file is structured like a standard Java properties file, which makes it easier to manage and is less likely to change than java.policy. You’ll see too that many of the settings pertain to cryptography providers, the keystore, and the like. These aren’t the kinds of things that multiple developers are likely to modify.

One other setting in security.policy that is critical to the programmatic access to java.policy is the policy provider setting. This is the class that the audit utility must instantiate first to assemble the permissions for evaluation.

policy.provider=sun.security.provider.PolicyFile  

The code below is the typical way to get at the Policy file object.

pcoll = Policy.getPolicy().getPermissions(cs);

This call obtains the Policy file object and then the PermissionsCollection associated with it. More on this in a bit.

Activating the Security Manager
Before delving into the second critical configuration file, java.policy, I need to digress and point out that Java security isn’t “turned on” by default. Java’s security record is so remarkably good considering the ubiquity of Java code in the world today that many Java programmers don’t know or realize this. The manager of all security operations in Java 2 is the SecurityManager class and by default this class is deactivated. You can engage the SecurityManager in one of two ways. First, you can specify it on the command line at runtime:

java –Djava.security.manager   

Or you can programmatically activate it by instantiating a SecurityManager and calling it explicitly to perform the requisite security checks for your application.

Given the importance today of coding secure applications, Sun’s choice to leave this disabled by default is unfortunate to say the least. If you don’t turn on the Security Manager, java.policy isn’t consulted at all and your application will never throw an AccessException. Given this gap in many developer’s understanding of the Java security model it is certain that a lot of developers have been lulled into a false sense of security when in fact they have little or no security in place at all.

Setting Up Grant Blocks
Returning to the java.policy file, as mentioned previously, it is the second critical security configuration file in the default Java runtime environment and it is where permissions are configured. In Java, a Permission is configured in a grant block that is set up for a particular codebase. The first such grant in the default java.policy file provided by Sun is:

// Standard extensions get all permissions by defaultgrant codeBase "file:${java.home}/lib/ext/*" {	permission java.security.AllPermission;};

This grant allows any code installed in the /ext directory to have all permissions, literally. This is why fighting classpath problems by hoisting your code up the classloading delegation ladder into the /ext directory is so dangerous. Code living in this directory has rights to modify system properties and interact with the file system or do anything else you can think of on your system.

Note that Sun’s ‘codeBase’ is specified as a URL and supports the asterisk ( * ) wildcard. If you neglect a quote, a curly brace, or the final semicolon (;) your Permission file won’t be parsed and read properly at runtime (which is obviously why we’re going to verify its format at build time).

All permissions specified in java.policy adhere to the same basic format but may have an additional action modifier appended to them such as in the following example.

// com.tillman.util.security.permissionchecker package is in this directorygrant codeBase "file:/C:/eclipse/workspace/Permissions/PermissionReader/bin/*" {	permission java.security.SecurityPermission "getPolicy";	permission java.io.FilePermission "<>", "read,write,execute,delete";	permission java.net.URLPermission "http://www.nytimes.com", "listen, connect";};

The first permission in the block above is essential because the audit utility needs to get a reference to the Policy object in order to check its permissions so this must be explicitly permitted in the policy file. Obviously, you’ll need to modify the file URL to point to where you’ve placed the audit utility.

The code that checks the permissions is fairly straightforward. The only twist I’ve put in is that I want to be able to specify the codebases to audit in a properties file. This gives me the flexibility to ignore the default Java grant blocks. (You’ll note though that in the output these default blocks are appropriately added to the permissions that are of interest to me). The getFileLocations( ) method in the audit code simply returns a list of the codebases specified in my properties file (note the double backslashes to escape the backslash character on Windows).

From within a while loop, each of the locations specified in my properties file is converted to a codebase URL.

codebase = new File((String)iter.next()).toURL();

Each codebase is then passed as an argument to the CodeSource constructor. The CodeSource is effectively the “key” that the Policy object uses to retrieve the PermissionCollection.

cs = new CodeSource(codebase, null);pcoll = Policy.getPolicy().getPermissions(cs);

The PermissionCollection pcoll variable’s members are returned as an enumeration using the elements( ) method. Finally, we iterate through the enumeration and use each retrieved Permission object’s toString( ) method to print out its name.

enum1 = pcoll.elements();for (; enum1.hasMoreElements(); ) {    		System.out.println((Object)enum1.nextElement());}

The output displays something like this:

path: /C:/eclipse/workspace/Permissions/TestTwo/bin(java.util.PropertyPermission java.version read)(java.util.PropertyPermission java.vm.name read)

If the syntax of any of the permission grant blocks?or the permissions themselves?prove to be incorrect then the utility will display a message describing the parse error. In truth, the call to get the Policy object will blow up in this way without the rest of the code running. Nevertheless, the utility’s listing of the aggregation of the permissions for each codebase will give you another opportunity to confirm that the security you’re implementing is as desired.

Once you activate the SecurityManager the flexibility and power of the Java 2 security architecture is at your disposal. While the java.policy and java.security file formats would perhaps be better implemented as conventional XML files they are still fairly readable and manageable. Moreover, as you’ve seen, the java.policy file can be checked at build time to avoid unexpected runtime security lapses or failures. The Java Policy object can be extended to tailor its behavior to better meet your needs but the standard configuration options are adequate for most security needs.

devx-admin

devx-admin

Share the Post:
Chinese 5G Limitation

Germany Considers Limiting Chinese 5G Tech

A recent report has put forth the possibility that Germany’s Federal Ministry of the Interior and Community may consider limiting the use of Chinese 5G

Modern Warfare

The Barak Tank is Transforming Modern Warfare

The Barak tank is a groundbreaking addition to the Israeli Defense Forces’ arsenal, significantly enhancing their combat capabilities. This AI-powered military vehicle is expected to

AI Cheating Growth

AI Plagiarism Challenges Shake Academic Integrity

As generative AI technologies like ChatGPT become increasingly prevalent among students and raise concerns about widespread cheating, prominent universities have halted their use of AI

US Commitment

US Approves Sustainable Battery Research

The US Department of Energy has revealed a $325 million commitment in the research of innovative battery types, designed to enable solar and wind power

Netanyahu Musk AI

Netanyahu and Musk Discuss AI Future

On September 22, 2023, Israeli Prime Minister Benjamin Netanyahu met with entrepreneur Elon Musk in San Francisco prior to attending the United Nations. In a

Chinese 5G Limitation

Germany Considers Limiting Chinese 5G Tech

A recent report has put forth the possibility that Germany’s Federal Ministry of the Interior and Community may consider limiting the use of Chinese 5G technology by local network providers

Modern Warfare

The Barak Tank is Transforming Modern Warfare

The Barak tank is a groundbreaking addition to the Israeli Defense Forces’ arsenal, significantly enhancing their combat capabilities. This AI-powered military vehicle is expected to transform the way modern warfare

AI Cheating Growth

AI Plagiarism Challenges Shake Academic Integrity

As generative AI technologies like ChatGPT become increasingly prevalent among students and raise concerns about widespread cheating, prominent universities have halted their use of AI detection software, such as Turnitin’s

US Commitment

US Approves Sustainable Battery Research

The US Department of Energy has revealed a $325 million commitment in the research of innovative battery types, designed to enable solar and wind power as continuous, 24-hour energy sources.

Netanyahu Musk AI

Netanyahu and Musk Discuss AI Future

On September 22, 2023, Israeli Prime Minister Benjamin Netanyahu met with entrepreneur Elon Musk in San Francisco prior to attending the United Nations. In a live-streamed discussion, Netanyahu lauded Musk

Urban Gardening

Creating Thriving Cities Through Urban Gardening

The rising popularity of urban gardening is receiving increased recognition for its numerous advantages, as demonstrated in a recent study featured in the Environmental Research Letters journal. Carried out by

What You Need to Know About Cloud Security Strategies

What You Need to Know About Cloud Security Strategies

Today, many businesses are adopting cloud computing services. As a result, it’s important to recognize that security measures for data in the cloud are different from those in traditional on-premises

Romanian Energy Security

Eastern Europe is Achieving Energy Security

Canada and Romania have solidified their commitment to energy security and independence from Russian energy exports by signing a $3-billion export development agreement. The deal is centered on constructing two

Seamless Integration

Unlocking Seamless Smart Home Integration

The vision of an intelligently organized and interconnected smart home that conserves time, energy, and resources has long been desired by many homeowners. However, this aspiration has often been hindered

New Algorithm

MicroAlgo’s Groundbreaking Algorithm

MicroAlgo Inc. has revealed the creation of a knowledge-augmented backtracking search algorithm, developed through extensive research in evolutionary computational techniques. The algorithm is designed to boost problem-solving effectiveness, precision, and

Poland Energy Future

Westinghouse Builds Polish Power Plant

Westinghouse Electric Company and Bechtel have come together to establish a formal partnership in order to design and construct Poland’s inaugural nuclear power plant at the Lubiatowo-Kopalino site in Pomerania.

EV Labor Market

EV Industry Hurting For Skilled Labor

The United Auto Workers strike has highlighted the anticipated change towards a future dominated by electric vehicles (EVs), a shift which numerous people think will result in job losses. However,

Soaring EV Quotas

Soaring EV Quotas Spark Battle Against Time

Automakers are still expected to meet stringent electric vehicle (EV) sales quotas, despite the delayed ban on new petrol and diesel cars. Starting January 2023, more than one-fifth of automobiles

Affordable Electric Revolution

Tesla Rivals Make Bold Moves

Tesla, a name synonymous with EVs, has consistently been at the forefront of the automotive industry’s electric revolution. The products that Elon Musk has developed are at the forefront because

Sunsets' Technique

Inside the Climate Battle: Make Sunsets’ Technique

On February 12, 2023, Luke Iseman and Andrew Song from the solar geoengineering firm Make Sunsets showcased their technique for injecting sulfur dioxide (SO₂) into the stratosphere as a means

AI Adherence Prediction

AI Algorithm Predicts Treatment Adherence

Swoop, a prominent consumer health data company, has unveiled a cutting-edge algorithm capable of predicting adherence to treatment in people with Multiple Sclerosis (MS) and other health conditions. Utilizing artificial

Personalized UX

Here’s Why You Need to Use JavaScript and Cookies

In today’s increasingly digital world, websites often rely on JavaScript and cookies to provide users with a more seamless and personalized browsing experience. These key components allow websites to display

Geoengineering Methods

Scientists Dimming the Sun: It’s a Good Thing

Scientists at the University of Bern have been exploring geoengineering methods that could potentially slow down the melting of the West Antarctic ice sheet by reducing sunlight exposure. Among these

why startups succeed

The Top Reasons Why Startups Succeed

Everyone hears the stories. Apple was started in a garage. Musk slept in a rented office space while he was creating PayPal with his brother. Facebook was coded by a

Bold Evolution

Intel’s Bold Comeback

Intel, a leading figure in the semiconductor industry, has underperformed in the stock market over the past five years, with shares dropping by 4% as opposed to the 176% return

Semiconductor market

Semiconductor Slump: Rebound on the Horizon

In recent years, the semiconductor sector has faced a slump due to decreasing PC and smartphone sales, especially in 2022 and 2023. Nonetheless, as 2024 approaches, the industry seems to

Elevated Content Deals

Elevate Your Content Creation with Amazing Deals

The latest Tech Deals cater to creators of different levels and budgets, featuring a variety of computer accessories and tools designed specifically for content creation. Enhance your technological setup with

Learn Web Security

An Easy Way to Learn Web Security

The Web Security Academy has recently introduced new educational courses designed to offer a comprehensible and straightforward journey through the intricate realm of web security. These carefully designed learning courses