Translate

Thursday, November 1, 2012


Security

Java was designed with security in mind and Java security was designed for:
       ▪ Java users, i.e. people running Java applications. With Java, at least, there is ease of mind. However, as you will see later, Java users need to understand Java’s security eature in order to configure security settings.
      ▪ Java developers. You can use Java APIs to incorporate fine-grained security features into your applications, such as security checks and cryptography.

There are two main topics of Java security:
      ▪Restricting running Java applications. Unlike applets that by default run in a estricted environment, Java applications are unrestricted.
      ▪Cryptography, namely encrypting and decrypting your message and Java code.

Java Security Overview

When people say that Java is secure, it does not mean security comes automatically. Generally, running a Java application is not secure because it runs in an unrestricted environment. This means, a malicious Java program can do anything to its environment, including making you cry when it deletes all your precious data. It can do anything because by default, when you run an application, you give it permissions to do anything.
To impose restrictions, you must run the application with the security manager, which is a Java component responsible for restricting access to system resources. When the security manager is on, all the permissions are revoked. Web browsers install a security manager that imposes security to the network but ban input/output operations. The way to tell the security manager what permissions are allowed is by passing a policy file. A policy file is a text file, so no programming is necessary to configure security settings for the security manager.

Using the Security Manager

The security manager is often used in a Java program that executes other Java classes written by other people.
Here are some examples:
▪An applet viewer. An applet viewer is a Java application that runs applets. Applets can be written by other parties and it is in the interest of the applet viewer to make sure those applets do not attack the host.

▪A servlet container is a Java application that runs servlets. Servlets are like applets but run on the server side. A servlet container is normally written in Java, and when run, it can be set to restrict access
Note
You can use a text editor to create or edit a policy file or you can use the Policy Tool, which is included in the JDK. The Policy Tool is discussed in the section “The Policy Tool.”

Here is the syntax for passing a policy file to the java tool.
java -Djava.security.manager -Djava.security.policy=policyFile  MyClass

arguments where policyFile is the path to a policy file, MyClass is the Java class to
invoke, and arguments is the list of arguments for the Java class. If the java program is invoked with –Djava.security.manager but no -Djava.security.policy is used, the default policy files is used. The default policy files are specified in the security properties file (java.security file) under the ${java.home}/lib/security directory, where ${java.home} is the installation directory of your JRE. The security properties file specifies security-related settings, such as policy files, provider package names, whether or not property file expansion

The default policy file

// Standard extensions get all permissions by default
grant codeBase "file:${{java.ext.dirs}}/*" {
  permission java.security.AllPermission;
};
// default permissions granted to all domains
grant {
  // Allows any thread to stop itself using the
  //java.lang.Thread.stop() method that takes no argument.
  // Note that this permission is granted by default only to remain
  // backwards compatible.
  // It is strongly recommended that you either remove this
  // permission from this policy file or further restrict it to
  // code
  // sources that you specify, because Thread.stop() is potentially
  // unsafe.
  // See "http://java.sun.com/notes" for more information.
  permission java.lang.RuntimePermission "stopThread";
  // allows anyone to listen on un-privileged ports
  permission java.net.SocketPermission "localhost:1024-", "listen";
  // "standard" properies that can be read by anyone
  permission java.util.PropertyPermission "java.version", "read";
  permission java.util.PropertyPermission "java.vendor", "read";
  permission java.util.PropertyPermission "java.vendor.url",
"read";
  permission java.util.PropertyPermission "java.class.version",
    "read";
  permission java.util.PropertyPermission "os.name", "read";
  permission java.util.PropertyPermission "os.version", "read";
  permission java.util.PropertyPermission "os.arch", "read";
  permission java.util.PropertyPermission "file.separator", "read";
  permission java.util.PropertyPermission "path.separator", "read";
  permission java.util.PropertyPermission "line.separator", "read";
  permission java.util.PropertyPermission
    "java.specification.version", "read";
  permission java.util.PropertyPermission
    "java.specification.vendor", "read";
  permission java.util.PropertyPermission
"java.specification.name",
    "read";
  permission java.util.PropertyPermission
    "java.vm.specification.version", "read";
permission java.util.PropertyPermission
    "java.vm.specification.vendor", "read";
  permission java.util.PropertyPermission
    "java.vm.specification.name", "read";
  permission java.util.PropertyPermission "java.vm.version",
"read";
  permission java.util.PropertyPermission "java.vm.vendor", "read";
  permission java.util.PropertyPermission "java.vm.name", "read";
};

The default policy file lists the activities that are permitted when running the security manager using this file. For example, the last few lines specify the permission to read system properties. The java.version, and java.vendor system properties are allowed to be read. But, reading other system properties, such as user.dir is not allowed. Therefore, the default policy is very restricted. In most cases you want to write a policy file that gives the application more room to maneuver. The rest of this section discusses keystore and grant entries. It teaches you how to write your own policy file.

principal principal_class_name_2 "principal_name_2",
    ...
    principal principal_class_name_n principal_name_n
  ]
{
  permission permission_class_name_1 "target_name_1", "action_1",
    signedBy "signer_name_1"
  permission permission_class_name_2 "target_name_2", "action_2",
    signedBy "signer_name_2"
  ...
  permission permission_class_name_n "target_name_n", "action_n",
    signedBy "signer_name_n"
}

The order of signedBy, codeBase, and principal values is not important. A codeBase value indicates the URL of the source code you are granting permission(s) to. An empty codeBase means any code. For example, the following grant entry grants the permission associated with the java.security.AllPermission class to the directory denoted by the value of java.ext.dirs directory:
Permissions:

A permission is represented by the java.security.Permission class, which is an abstract class. Its subclasses represent permissions to access different types of access to system resources.
For example, the java.io.FilePermission class represents a permission to read and write to a file. The permission entry in a policy file has the following syntax:

Permission permissionClassName target action

The permissionClassName argument specifies a permission type that corresponds to a specific permission. For example, the java.io.FilePermission class refers to file manipulation operations. The target argument specifies the target of the permission. Some permission types require a target, some don’t. The action argument specifies the type of action associated with this

The target argument contains the name of a file or a directory. There must be no white spaces in the string. You can use an asterisk to represent all files in a directory and a hyphen to represent the contents of a directory recursively. Table .1 lists some examples and their descriptions.The action argument describe a possible action. Its value is one of the following: read, write, delete, and execute. You can use the combination of  the four. For example, “read,write” means that the permission concerns the reading and writing of the target file or directory.
Target
Description
myFile
myFile file in the current directory
myDirectory
the myDirectory directory in the current
directory
myDirectory/
the myDirectory directory in the current
directory
myDirectory/*
all files in the myDirectory directory
myDirectory/-
all files under myDirectory and under direct and
indirect subdirectories of myDirectory
*
all files in the current directory
-
all files under the current directory
<>
a special string that denotes all files in the
system.
                             Table 1: Examples of targets of File Permission

Note
Use \ as the directory separator in Windows. Therefore, C:\\temp\\* denotes all files under C:\temp. You need to escape the backslash character.java.security.BasicPermission

The Basic Permission class is a subclass of Permission. It is used as the base class for “named” permissions, i.e. ones that contain no actions. Subclasses of this class include java.lang.RuntimePermission, java.security.SecurityPermission, java.util.PropertyPermission, and  java.net.NetPermission.

java.util.PropertyPermission:

The Property Permission class represents the permissions to read the specified system property (by using the getProperty method on java.lang.System) and to alter the value of the specified property (by invoking the setProperty method on java.lang.System). The targets for this permission are the names of Java properties, such as “java.home” and
“user.dir”. You can use an asterisk to denote any property or to substitute part of the name of a property. In other words, “user.*” denotes all properties whose names have the prefix “user.”.

java.net.SocketPermission

This permission represents access to a network via sockets. The target for this permission has the following syntax.
                     hostName:portRange

where hostname can be expressed as a single host, an IP address, localhost

java.lang.RuntimePermission

The RuntimePermission class represents a runtime permission. It is used without an action and the target can be one of the following (all self-explanatory)

createClassLoader
getClassLoader
setContextClassLoader
setSecurityManager
createSecurityManager
exitVM
setFactory
setIO
modifyThread
modifyThreadGroup
stopThread
getProtectionDomain
readFileDescriptor
writeFileDescriptor
loadLibrary.{libraryName}
specifyStreamHandler

java.lang.reflect.ReflectPermission

This permission is related to reflective operations and has no actions. There is only one name defined: suppressAccessChecks, which is used to denote the permission to suppress the standard Java language access checks for public, default, protected, or private members.
java.io.SerializablePermission

This permission has no action and its target is one of the following.

enableSubclassImplementation
enableSubstitution

java.security.SecurityPermission

java.security.AllPermission
This permission is used as a shortcut to denote all permissions.
javax.security.auth.AuthPermission
This permission represents authentication permissions and authentication-
related objects, such as Configuration, LoginContext, Subject, and
SubjectDomainCombiner. This class is used without actions and can have
one of the following as its target.
doAs
doAsPrivileged
getSubject
getSubjectFromDomainCombiner
setReadOnly
modifyPrincipals
modifyPublicCredentials
modifyPrivateCredentials
refreshCredential
destroyCredential
createLoginContext.{name}
getLoginConfiguration
setLoginConfiguration
refreshLoginConfiguration

Using the Policy Tool
Using a text editor to create and edit a policy file is error-prone. Besides, you will have to remember a number of things, including the permission classes and the syntax of each entry. Java comes with a tool named Policy Tool that you can invoke by typing policytool.Figure.1 shows the Policy Tool window. When it opens it always attempts to open the .java.policy file (note, the filename starts with a .) in the user’s home directory. If it cannot find one it will report it as an error

If the default policy file is not found, you can create a new one by clicking
New from the File menu or open an existing one by clicking Open from the

You can now proceed with adding a policy entry by clicking the Add Policy
Entry button, that will open the Policy Entry window as shown in Figure
25.2.
You can add a permission by clicking the Add Permission button in the
Policy Entry window. This will bring up the Permissions window, shown in
Figure 25.3.
Figure 25.3: The Permission window
From the Permission window, you can select a permission class name,
▪Digitally sign the applet.
The first one is normally not an option because this means you cannot
distribute your applet on the Internet. This leaves us with the second option,
which is fortunately is easy enough to do using the JarSigner tool, one of
the tools included in the JDK. In fact, the section “The JarSigner Tool” later
in this chapter tells you how to sign an applet. However, digital signing
requires you to understand cryptography, therefore you should read the
section “Cryptography Overview” before starting to sign your code.
Note
More information on applet security can be found at
http://www.oracle.com/technetwork/java/javase/tech/index-jsp-
136007.html.
Programming with Security
Your users may run your application with the security manager on. If
nothing is done to check this in your code, your application could throw a
crash. To avoid such an abrupt exit, enclose your code with a try block that
catches a SecurityException. For example:
try {
    Path file = Paths.get(filename);
    Files.delete(file);
} catch (IOException e) {
} catch (SecurityException e) {
    System.err.println("You do not have permission to " +
            "delete the file.");
}
Cryptography Overview
From time to time there has always been a need for secure communication
channels, i.e. where messages are safe and other parties cannot understand
and tamper with the messages even if they can get access to them.
Historically, cryptography was only concerned with encryption and
decryption, where two parties exchanging messages can be rest assured that
only they can read the messages. In the beginning, people encrypt and
decrypt messages using symmetric cryptography. In symmetric
cryptography, you use the same key to encrypt and decrypt messages. Here
is a very simple encryption/decryption technique. Today, of course,
encryption techniques are more advanced than the example.
Suppose, the encryption method uses a secret number to shift forward
each character in the alphabet. Therefore, if the secret number is 2, the
encrypted version of "ThisFriday" is "VjkuHtkfca". When you reach the end
of the alphabet, you start from the beginning, therefore y becomes a. The
receiver, knowing the key is 2, can easily decrypt the message.
However, symmetric cryptography requires both parties know in
advance the key for encryption/decryption. Symmetric cryptography is not
suitable for the Internet for the following reasons
▪Two people exchanging messages often do not know each other. For
example, when buying a book at Amazon.com you need to send your
particulars and credit card details. If symmetric cryptography was to
be used, you would have to call Amazon.com prior to the transaction
to agree on a key.
▪Each person wants to be able to communicate with many other
parties. If symmetric cryptography was used, each person would have
to maintain different unique keys, each for a different party.
▪Since you do not know the entity you are going to communicate with,
you need to be sure that they are really who they claim to be.
▪Messages over the Internet pass through many different computers. It
is fairly trivial to tap other people’s messages. Symmetric
cryptography does not guarantee that a third party may not tamper
with the data.
Therefore, today secure communication over the Internet uses asymmetric
cryptography that offers the following three features:
▪ encryption/decryption. Messages are encrypted to hide the messages
from third parties. Only the intended receiver can decrypt them.
▪authentication. Authentication verifies that an entity is who it claims
The RSA algorithm proves to be practical for use on the Internet,
especially for e-commerce, because only a vendor is required to have one
single pair of keys for communications with all its buyers and purchasers do
not need to have a key at all.
An illustration of how public key encryption works normally use two
figures called Bob and Alice, so we’ll use them too here.
Encryption/Decryption
One of the two parties who want to exchange messages must have a pair of
keys. Suppose Alice wants to communicate with Bob and Bob has a public
key and a private key. Bob will send Alice his public key and Alice can use
it to encrypt messages sent to Bob. Only Bob can decrypt them because he
owns the corresponding private key. To send a message to Alice, Bob
encrypts it using his private key and Alice can decrypt it using Bob’s public
key.
electronic file (a document, a Java jar file, etc) is to add your signature to
your document/file. The original file is not encrypted, and the real purpose
of signing is to guarantee that the document/file has not been tampered
with. Signing a document involves creating the digest of the document and
encrypted the digest using the signer’s private key. To check if the
document is still in its still original condition, you perform these two steps.
1. Decrypt the digest accompanying the document using the signer’s
public key. You will soon learn that the public key of a trusted
certificate issuer is widely available.
2. Create a digest of the document.
3. Compare the result of Step 1 and the result of Step 2. If the two
match, then the file is original.
Such authentication method works because only the holder of the private
key can encrypt the document digest, and this digest can only be decrypted
using the associated public key. Assuming you trust that you hold the
original public key, then you know that the file has not been changed.

Figure 25.4: Several certificate issuers whose public keys are embedded
in Internet Explorer
Now, having a certificate, Bob will distribute the certificate instead of his
public key before exchanging messages with another party.
Here is how it works.
A->B    Hi Bob, I’d like to speak with you, but first of all I need to make
sure that you’re really Bob.
B->A   Understandable, here is my certificate
A->B   This is not sufficient, I need something else from you
B->A   Alice, it’s really me + [message digest encrypted using Bob’s
private key]
In the last message from Bob to Alice, the message has been signed
using Bob’s private key, to convince Alice that the message is authentic.
     ---------------------------Remaining information Next Post

No comments: