diff options
author | Elliott Hughes <enh@google.com> | 2011-06-06 10:55:15 -0700 |
---|---|---|
committer | Android (Google) Code Review <android-gerrit@google.com> | 2011-06-06 10:55:15 -0700 |
commit | 4f54203252733229489e6d09c7d3e0aaa82754d6 (patch) | |
tree | 686fff927c6b7c73836de0c9a1cc48b4d5ade106 /luni | |
parent | fc041ff241f9a7556e72236f130de0215ecd17db (diff) | |
parent | e26b27faf689c17b7894c78caee32432176349ec (diff) | |
download | libcore-4f54203252733229489e6d09c7d3e0aaa82754d6.zip libcore-4f54203252733229489e6d09c7d3e0aaa82754d6.tar.gz libcore-4f54203252733229489e6d09c7d3e0aaa82754d6.tar.bz2 |
Merge "Remove more dead "security theater" cruft." into dalvik-dev
Diffstat (limited to 'luni')
46 files changed, 208 insertions, 7847 deletions
diff --git a/luni/src/main/java/java/io/FilePermission.java b/luni/src/main/java/java/io/FilePermission.java index 3daeda1..b429f52 100644 --- a/luni/src/main/java/java/io/FilePermission.java +++ b/luni/src/main/java/java/io/FilePermission.java @@ -18,336 +18,14 @@ package java.io; import java.security.Permission; -import java.security.PermissionCollection; -import java.security.PrivilegedAction; -import java.util.Locale; -import libcore.util.Objects; /** - * Legacy security code; this class exists for compatibility only. + * Legacy security code; do not use. */ public final class FilePermission extends Permission implements Serializable { + public FilePermission(String path, String actions) { super(""); } - private static final long serialVersionUID = 7930732926638008763L; + @Override public String getActions() { return null; } - // canonical path of this permission - private transient String canonPath; - - private static final String[] actionList = { "read", "write", "execute", "delete" }; - - // "canonicalized" action list - private String actions; - - // the numeric representation of this action list - // for implies() to check if one action list is the subset of another. - transient int mask = -1; - - // global include all permission? - private transient boolean includeAll = false; - - private transient boolean allDir = false; - - private transient boolean allSubdir = false; - - /** - * Constructs a new FilePermission with the path and actions specified. - * - * @param path - * the pathname of the file or directory to apply the actions to. - * @param actions - * the actions for the {@code path}. May be any combination of - * "read", "write", "execute" and "delete". - * @throws IllegalArgumentException - * if {@code actions} is {@code null} or an empty string, or if - * it contains a string other than "read", "write", "execute" - * and "delete". - * @throws NullPointerException - * if {@code path} is {@code null}. - */ - public FilePermission(String path, String actions) { - super(path); - init(path, actions); - } - - private void init(final String path, String pathActions) { - if (pathActions == null || pathActions.isEmpty()) { - throw new IllegalArgumentException("pathActions == null || pathActions.isEmpty()"); - } - this.actions = toCanonicalActionString(pathActions); - - if (path == null) { - throw new NullPointerException("path == null"); - } - if (path.equals("<<ALL FILES>>")) { - includeAll = true; - } else { - canonPath = path; - try { - canonPath = new File(path).getCanonicalPath(); - } catch (IOException e) { - } - if (path.equals("*") || path.endsWith(File.separator + "*")) { - allDir = true; - } - if (path.equals("-") || path.endsWith(File.separator + "-")) { - allSubdir = true; - } - } - } - - /** - * Returns the string representing this permission's actions. It must be of - * the form "read,write,execute,delete", all lower case and in the correct - * order if there is more than one action. - * - * @param action - * the action name - * @return the string representing this permission's actions - */ - private String toCanonicalActionString(String action) { - actions = action.trim().toLowerCase(Locale.US); - - // get the numerical representation of the action list - mask = getMask(actions); - - // convert the mask to a canonical action list. - int len = actionList.length; - // the test mask - shift the 1 to the leftmost position of the - // actionList - int highestBitMask = 1 << (len - 1); - - // if a bit of mask is set, append the corresponding action to result - StringBuilder result = new StringBuilder(); - boolean addedItem = false; - for (int i = 0; i < len; i++) { - if ((highestBitMask & mask) != 0) { - if (addedItem) { - result.append(","); - } - result.append(actionList[i]); - addedItem = true; - } - highestBitMask = highestBitMask >> 1; - } - return result.toString(); - } - - /** - * Returns the numerical representation of the argument. - * - * @param actionNames - * the action names - * @return the action mask - */ - private int getMask(String actionNames) { - int actionInt = 0, head = 0, tail = 0; - do { - tail = actionNames.indexOf(",", head); - String action = tail > 0 ? actionNames.substring(head, tail).trim() - : actionNames.substring(head).trim(); - if (action.equals("read")) { - actionInt |= 8; - } else if (action.equals("write")) { - actionInt |= 4; - } else if (action.equals("execute")) { - actionInt |= 2; - } else if (action.equals("delete")) { - actionInt |= 1; - } else { - throw new IllegalArgumentException("Invalid action: " + action); - } - head = tail + 1; - } while (tail > 0); - return actionInt; - } - - /** - * Returns the actions associated with this file permission. - * - * @return the actions associated with this file permission. - */ - @Override - public String getActions() { - return actions; - } - - /** - * Indicates if this file permission is equal to another. The two are equal - * if {@code obj} is a FilePermission, they have the same path, and they - * have the same actions. - * - * @param obj - * the object to check equality with. - * @return {@code true} if this file permission is equal to {@code obj}, - * {@code false} otherwise. - */ - @Override - public boolean equals(Object obj) { - if (obj instanceof FilePermission) { - FilePermission fp = (FilePermission) obj; - if (!Objects.equal(fp.actions, actions)) { - return false; - } - - /* Matching actions and both are <<ALL FILES>> ? */ - if (fp.includeAll || includeAll) { - return fp.includeAll == includeAll; - } - return fp.canonPath.equals(canonPath); - } - return false; - } - - /** - * Indicates whether the permission {@code p} is implied by this file - * permission. This is the case if {@code p} is an instance of - * {@code FilePermission}, if {@code p}'s actions are a subset of this - * file permission's actions and if {@code p}'s path is implied by this - * file permission's path. - * - * @param p - * the permission to check. - * @return {@code true} if the argument permission is implied by the - * receiver, and {@code false} if it is not. - */ - @Override - public boolean implies(Permission p) { - int match = impliesMask(p); - return match != 0 && match == ((FilePermission) p).mask; - } - - /** - * Returns an int describing what masks are implied by a specific - * permission. - * - * @param p - * the permission - * @return the mask applied to the given permission - */ - int impliesMask(Permission p) { - if (!(p instanceof FilePermission)) { - return 0; - } - FilePermission fp = (FilePermission) p; - int matchedMask = mask & fp.mask; - // Can't match any bits? - if (matchedMask == 0) { - return 0; - } - - // Is this permission <<ALL FILES>> - if (includeAll) { - return matchedMask; - } - - // We can't imply all files - if (fp.includeAll) { - return 0; - } - - // Scan the length of p checking all match possibilities - // \- implies everything except \ - int thisLength = canonPath.length(); - if (allSubdir && thisLength == 2 - && !fp.canonPath.equals(File.separator)) { - return matchedMask; - } - // need /- to imply /- - if (fp.allSubdir && !allSubdir) { - return 0; - } - // need /- or /* to imply /* - if (fp.allDir && !allSubdir && !allDir) { - return 0; - } - - boolean includeDir = false; - int pLength = fp.canonPath.length(); - // do not compare the * or - - if (allDir || allSubdir) { - thisLength--; - } - if (fp.allDir || fp.allSubdir) { - pLength--; - } - for (int i = 0; i < pLength; i++) { - char pChar = fp.canonPath.charAt(i); - // Is p longer than this permissions canonLength? - if (i >= thisLength) { - if (i == thisLength) { - // Is this permission include all? (must have matched up - // until this point). - if (allSubdir) { - return matchedMask; - } - // Is this permission include a dir? Continue the check - // afterwards. - if (allDir) { - includeDir = true; - } - } - // If not includeDir then is has to be a mismatch. - if (!includeDir) { - return 0; - } - /** - * If we have * for this and find a separator it is invalid. IE: - * this is '/a/*' and p is '/a/b/c' we should fail on the - * separator after the b. Except for root, canonical paths do - * not end in a separator. - */ - if (pChar == File.separatorChar) { - return 0; - } - } else { - // Are the characters matched? - if (canonPath.charAt(i) != pChar) { - return 0; - } - } - } - // Must have matched up to this point or it's a valid file in an include - // all directory - if (pLength == thisLength) { - if (allSubdir) { - // /- implies /- or /* - return fp.allSubdir || fp.allDir ? matchedMask : 0; - } - return allDir == fp.allDir ? matchedMask : 0; - } - return includeDir ? matchedMask : 0; - } - - /** - * Returns a new PermissionCollection in which to place FilePermission - * objects. - * - * @return A new PermissionCollection object suitable for storing - * FilePermission objects. - */ - @Override - public PermissionCollection newPermissionCollection() { - return new FilePermissionCollection(); - } - - /** - * Calculates the hash code value for this file permission. - * - * @return the hash code value for this file permission. - */ - @Override - public int hashCode() { - return (canonPath == null ? getName().hashCode() : canonPath.hashCode()) - + mask; - } - - private void writeObject(ObjectOutputStream stream) throws IOException { - stream.defaultWriteObject(); - } - - private void readObject(ObjectInputStream stream) throws IOException, - ClassNotFoundException { - stream.defaultReadObject(); - init(getName(), actions); - } + @Override public boolean implies(Permission permission) { return true; } } diff --git a/luni/src/main/java/java/io/FilePermissionCollection.java b/luni/src/main/java/java/io/FilePermissionCollection.java deleted file mode 100644 index 9db656b..0000000 --- a/luni/src/main/java/java/io/FilePermissionCollection.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package java.io; - -import java.security.Permission; -import java.security.PermissionCollection; -import java.util.Enumeration; -import java.util.Vector; - -/** - * Collects {@link FilePermission} objects and allows to query whether a - * particular permission is implied by it. - */ -final class FilePermissionCollection extends PermissionCollection implements - Serializable { - - private static final long serialVersionUID = 2202956749081564585L; - - Vector<Permission> permissions = new Vector<Permission>(); - - /** - * Construct a new FilePermissionCollection - */ - public FilePermissionCollection() { - } - - /** - * Add a permission object to the permission collection. - * - * @param permission - * the FilePermission object to add to the collection. - * @throws IllegalArgumentException - * if {@code permission} is not an instance of - * {@code FilePermission}. - * @throws IllegalStateException - * if this collection is read-only. - * @see java.security.PermissionCollection#add(java.security.Permission) - */ - @Override - public void add(Permission permission) { - if (isReadOnly()) { - throw new IllegalStateException(); - } - if (permission instanceof FilePermission) { - permissions.addElement(permission); - } else { - throw new IllegalArgumentException(permission.toString()); - } - } - - /** - * Returns an enumeration for the collection of permissions. - * - * @return a permission enumeration for this permission collection. - * @see java.security.PermissionCollection#elements() - */ - @Override - public Enumeration<Permission> elements() { - return permissions.elements(); - } - - /** - * Indicates whether this permissions collection implies a specific - * {@code permission}. - * - * @param permission - * the permission to check. - * @see java.security.PermissionCollection#implies(java.security.Permission) - */ - @Override - public boolean implies(Permission permission) { - if (permission instanceof FilePermission) { - FilePermission fp = (FilePermission) permission; - int matchedMask = 0; - int i = 0; - while (i < permissions.size() - && ((matchedMask & fp.mask) != fp.mask)) { - // Cast will not fail since we added it - matchedMask |= ((FilePermission) permissions.elementAt(i)) - .impliesMask(permission); - i++; - } - return ((matchedMask & fp.mask) == fp.mask); - } - return false; - } -} diff --git a/luni/src/main/java/java/io/SerializablePermission.java b/luni/src/main/java/java/io/SerializablePermission.java index a1465fe..fbe13fd 100644 --- a/luni/src/main/java/java/io/SerializablePermission.java +++ b/luni/src/main/java/java/io/SerializablePermission.java @@ -18,37 +18,17 @@ package java.io; import java.security.BasicPermission; +import java.security.Permission; /** - * Legacy security code; this class exists for compatibility only. + * Legacy security code; do not use. */ public final class SerializablePermission extends BasicPermission { - private static final long serialVersionUID = 8537212141160296410L; + public SerializablePermission(String permissionName) { super(""); } - // Serializable field - @SuppressWarnings("unused") - private String actions; + public SerializablePermission(String name, String actions) { super("", ""); } - /** - * Constructs a new {@code SerializablePermission} with the specified name. - * - * @param permissionName - * the name of the new permission. - */ - public SerializablePermission(String permissionName) { - super(permissionName); - } + @Override public String getActions() { return null; } - /** - * Constructs a new {@code SerializablePermission} with the specified name. - * The action list is ignored. - * - * @param name - * the name of the new permission. - * @param actions - * ignored. - */ - public SerializablePermission(String name, String actions) { - super(name, actions); - } + @Override public boolean implies(Permission permission) { return true; } } diff --git a/luni/src/main/java/java/lang/RuntimePermission.java b/luni/src/main/java/java/lang/RuntimePermission.java index 752c74a..bbec049 100644 --- a/luni/src/main/java/java/lang/RuntimePermission.java +++ b/luni/src/main/java/java/lang/RuntimePermission.java @@ -18,34 +18,17 @@ package java.lang; import java.security.BasicPermission; +import java.security.Permission; /** - * Legacy security code; this class exists for compatibility only. + * Legacy security code; do not use. */ public final class RuntimePermission extends BasicPermission { + public RuntimePermission(String permissionName) { super(""); } - private static final long serialVersionUID = 7399184964622342223L; + public RuntimePermission(String name, String actions) { super("", ""); } - /** - * Creates an instance of {@code RuntimePermission} with the specified name. - * - * @param permissionName - * the name of the new permission. - */ - public RuntimePermission(String permissionName) { - super(permissionName); - } + @Override public String getActions() { return null; } - /** - * Creates an instance of {@code RuntimePermission} with the specified name - * and action list. The action list is ignored. - * - * @param name - * the name of the new permission. - * @param actions - * ignored. - */ - public RuntimePermission(String name, String actions) { - super(name, actions); - } + @Override public boolean implies(Permission permission) { return true; } } diff --git a/luni/src/main/java/java/lang/SecurityManager.java b/luni/src/main/java/java/lang/SecurityManager.java index b1208ed..98e92cc 100644 --- a/luni/src/main/java/java/lang/SecurityManager.java +++ b/luni/src/main/java/java/lang/SecurityManager.java @@ -17,23 +17,12 @@ package java.lang; -import dalvik.system.VMStack; -import java.io.File; import java.io.FileDescriptor; -import java.io.FilePermission; -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Member; import java.net.InetAddress; -import java.net.SocketPermission; -import java.security.AccessController; -import java.security.AllPermission; import java.security.Permission; -import java.security.Security; -import java.security.SecurityPermission; /** - * Legacy security code; this class exists for compatibility only. + * Legacy security code; do not use. * * <p>Security managers do <strong>not</strong> provide a * secure environment for executing untrusted code. Untrusted code cannot be @@ -41,367 +30,123 @@ import java.security.SecurityPermission; */ public class SecurityManager { /** - * Flag to indicate whether a security check is in progress. - * * @deprecated Use {@link #checkPermission} */ @Deprecated protected boolean inCheck; - /** - * Constructs a new {@code SecurityManager} instance. - */ - public SecurityManager() { - } + public SecurityManager() { } - /** - * Does nothing. - */ - public void checkAccept(String host, int port) { - } + public void checkAccept(String host, int port) { } - /** - * Does nothing. - */ - public void checkAccess(Thread thread) { - } + public void checkAccess(Thread thread) { } - /** - * Does nothing. - */ - public void checkAccess(ThreadGroup group) { - } + public void checkAccess(ThreadGroup group) { } - /** - * Does nothing. - */ - public void checkConnect(String host, int port) { - } + public void checkConnect(String host, int port) { } - /** - * Does nothing. - */ - public void checkConnect(String host, int port, Object context) { - } + public void checkConnect(String host, int port, Object context) { } - /** - * Does nothing. - */ - public void checkCreateClassLoader() { - } + public void checkCreateClassLoader() { } - /** - * Does nothing. - */ - public void checkDelete(String file) { - } + public void checkDelete(String file) { } - /** - * Does nothing. - */ - public void checkExec(String cmd) { - } + public void checkExec(String cmd) { } - /** - * Does nothing. - */ - public void checkExit(int status) { - } + public void checkExit(int status) { } - /** - * Does nothing. - */ - public void checkLink(String libName) { - } + public void checkLink(String libName) { } - /** - * Does nothing. - */ - public void checkListen(int port) { - } + public void checkListen(int port) { } - /** - * Does nothing. - */ - public void checkMemberAccess(Class<?> cls, int type) { - } + public void checkMemberAccess(Class<?> cls, int type) { } - /** - * Does nothing. - */ - public void checkMulticast(InetAddress maddr) { - } + public void checkMulticast(InetAddress maddr) { } /** - * Does nothing. * @deprecated use {@link #checkMulticast(java.net.InetAddress)} */ - @Deprecated - public void checkMulticast(InetAddress maddr, byte ttl) { - } + @Deprecated public void checkMulticast(InetAddress maddr, byte ttl) { } - /** - * Does nothing. - */ - public void checkPackageAccess(String packageName) { - } + public void checkPackageAccess(String packageName) { } - /** - * Does nothing. - */ - public void checkPackageDefinition(String packageName) { - } + public void checkPackageDefinition(String packageName) { } - /** - * Does nothing. - */ - public void checkPropertiesAccess() { - } + public void checkPropertiesAccess() { } - /** - * Does nothing. - */ - public void checkPropertyAccess(String key) { - } + public void checkPropertyAccess(String key) { } - /** - * Does nothing. - */ - public void checkRead(FileDescriptor fd) { - } + public void checkRead(FileDescriptor fd) { } - /** - * Does nothing. - */ - public void checkRead(String file) { - } + public void checkRead(String file) { } - /** - * Does nothing. - */ - public void checkRead(String file, Object context) { - } + public void checkRead(String file, Object context) { } - /** - * Does nothing. - */ - public void checkSecurityAccess(String target) { - } + public void checkSecurityAccess(String target) { } - /** - * Does nothing. - */ - public void checkSetFactory() { - } + public void checkSetFactory() { } - /** - * Returns true. - */ - public boolean checkTopLevelWindow(Object window) { - return true; - } + public boolean checkTopLevelWindow(Object window) { return true; } - /** - * Does nothing. - */ - public void checkSystemClipboardAccess() { - } + public void checkSystemClipboardAccess() { } - /** - * Does nothing. - */ - public void checkAwtEventQueueAccess() { - } + public void checkAwtEventQueueAccess() { } - /** - * Does nothing. - */ - public void checkPrintJobAccess() { - } + public void checkPrintJobAccess() { } - /** - * Does nothing. - */ - public void checkWrite(FileDescriptor fd) { - } + public void checkWrite(FileDescriptor fd) { } - /** - * Does nothing. - */ - public void checkWrite(String file) { - } + public void checkWrite(String file) { } /** - * Indicates if this security manager is currently checking something. - * - * @return {@code true} if this security manager is executing a security - * check method; {@code false} otherwise. * @deprecated Use {@link #checkPermission}. */ - @Deprecated - public boolean getInCheck() { - return inCheck; - } + @Deprecated public boolean getInCheck() { return inCheck; } - /** - * Returns an array containing one entry for each method in the current - * execution stack. Each entry is the {@code java.lang.Class} which - * represents the class in which the method is defined. - * - * @return all classes in the execution stack. - */ - @SuppressWarnings("unchecked") - protected Class[] getClassContext() { - return VMStack.getClasses(-1); - } + protected Class[] getClassContext() { return null; } /** - * Returns the class loader of the first class in the execution stack whose - * class loader is not a system class loader. - * - * @return the most recent non-system class loader. * @deprecated Use {@link #checkPermission}. */ - @Deprecated - protected ClassLoader currentClassLoader() { - /* - * First, check if AllPermission is allowed. If so, then we are - * effectively running in an unsafe environment, so just answer null - * (==> everything is a system class). - */ - try { - checkPermission(new AllPermission()); - return null; - } catch (SecurityException ex) { - } - - /* - * Now, check if there are any non-system class loaders in the stack up - * to the first privileged method (or the end of the stack. - */ - Class<?>[] classes = VMStack.getClasses(-1); - return classes.length > 0 ? classes[0].getClassLoaderImpl() : null; - } + @Deprecated protected ClassLoader currentClassLoader() { return null; } /** - * Returns the index in the call stack of the first class whose class loader - * is not a system class loader. - * - * @return the frame index of the first method whose class was loaded by a - * non-system class loader. * @deprecated Use {@link #checkPermission}. */ - @Deprecated - protected int classLoaderDepth() { - /* - * First, check if AllPermission is allowed. If so, then we are - * effectively running in an unsafe environment, so just answer -1 (==> - * everything is a system class). - */ - try { - checkPermission(new AllPermission()); - return -1; - } catch (SecurityException ex) { - } - - /* - * Now, check if there are any non-system class loaders in the stack up - * to the first privileged method (or the end of the stack. - */ - Class<?>[] classes = VMStack.getClasses(-1); - return classes.length > 0 ? 0 : -1; + @Deprecated protected int classLoaderDepth() { + return -1; } /** - * Returns null. * @deprecated Use {@link #checkPermission}. */ - @Deprecated - protected Class<?> currentLoadedClass() { - return null; - } + @Deprecated protected Class<?> currentLoadedClass() { return null; } /** - * Returns the index in the call stack of the first method which is - * contained in the class with the specified name. Returns -1 if no methods - * from this class are in the stack. - * - * @param name - * the name of the class to look for. - * @return the frame index of the first method found is contained in the - * class identified by {@code name}. * @deprecated Use {@link #checkPermission}. */ - @Deprecated - protected int classDepth(String name) { - Class<?>[] classes = VMStack.getClasses(-1); - for (int i = 0; i < classes.length; i++) { - if (classes[i].getName().equals(name)) { - return i; - } - } - return -1; - } + @Deprecated protected int classDepth(String name) { return -1; } /** - * Indicates whether there is a method in the call stack from the class with - * the specified name. - * - * @param name - * the name of the class to look for. - * @return {@code true} if a method from the class identified by {@code - * name} is executing; {@code false} otherwise. * @deprecated Use {@link #checkPermission}. */ - @Deprecated - protected boolean inClass(String name) { - return classDepth(name) != -1; - } + @Deprecated protected boolean inClass(String name) { return false; } /** - * Indicates whether there is a method in the call stack from a class which - * was defined by a non-system class loader. - * - * @return {@code true} if a method from a class that was defined by a - * non-system class loader is executing; {@code false} otherwise. * @deprecated Use {@link #checkPermission} */ - @Deprecated - protected boolean inClassLoader() { - return currentClassLoader() != null; - } + @Deprecated protected boolean inClassLoader() { return false; } /** - * Returns the thread group which should be used to instantiate new threads. - * By default, this is the same as the thread group of the thread running - * this method. - * - * @return ThreadGroup the thread group to create new threads in. + * Returns the current thread's thread group. */ public ThreadGroup getThreadGroup() { return Thread.currentThread().getThreadGroup(); } - /** - * Returns an object which encapsulates the security state of the current - * point in the execution. - * - * @return an object that encapsulates information about the current - * execution environment. - */ - public Object getSecurityContext() { - return AccessController.getContext(); - } + public Object getSecurityContext() { return null; } - /** - * Does nothing. - */ - public void checkPermission(Permission permission) { - } + public void checkPermission(Permission permission) { } - /** - * Does nothing. - */ - public void checkPermission(Permission permission, Object context) { - } + public void checkPermission(Permission permission, Object context) { } } diff --git a/luni/src/main/java/java/lang/reflect/ReflectPermission.java b/luni/src/main/java/java/lang/reflect/ReflectPermission.java index afc30a2..4d10a80 100644 --- a/luni/src/main/java/java/lang/reflect/ReflectPermission.java +++ b/luni/src/main/java/java/lang/reflect/ReflectPermission.java @@ -18,43 +18,17 @@ package java.lang.reflect; import java.security.BasicPermission; +import java.security.Permission; /** - * Legacy security code; this class exists for compatibility only. + * Legacy security code; do not use. */ public final class ReflectPermission extends BasicPermission { + public ReflectPermission(String name) { super(""); } - private static final long serialVersionUID = 7412737110241507485L; + public ReflectPermission(String name, String actions) { super("", ""); } - /** - * Constructs a new {@code ReflectPermission} instance with the specified - * name. - * - * @param permissionName - * the name of the new permission - * @throws IllegalArgumentException - * if {@code name} is empty - * @throws NullPointerException - * if {@code name} is {@code null} - */ - public ReflectPermission(String permissionName) { - super(permissionName); - } + @Override public String getActions() { return null; } - /** - * Constructs a new {@code ReflectPermission} instance with the specified - * name and action list. The action list will be ignored. - * - * @param name - * the name of the new permission - * @param actions - * this parameter will be ignored - * @throws IllegalArgumentException - * if {@code name} is empty - * @throws NullPointerException - * if {@code name} is {@code null} - */ - public ReflectPermission(String name, String actions) { - super(name, actions); - } + @Override public boolean implies(Permission permission) { return true; } } diff --git a/luni/src/main/java/java/net/NetPermission.java b/luni/src/main/java/java/net/NetPermission.java index d9f57fe..c1a2631 100644 --- a/luni/src/main/java/java/net/NetPermission.java +++ b/luni/src/main/java/java/net/NetPermission.java @@ -17,33 +17,18 @@ package java.net; +import java.security.BasicPermission; +import java.security.Permission; + /** - * Legacy security code; this class exists for compatibility only. + * Legacy security code; do not use. */ -public final class NetPermission extends java.security.BasicPermission { +public final class NetPermission extends BasicPermission { + public NetPermission(String name) { super(""); } - private static final long serialVersionUID = -8343910153355041693L; + public NetPermission(String name, String actions) { super("", ""); } - /** - * Creates an instance of this class with the given name. - * - * @param name - * the name of the new NetPermission instance. - */ - public NetPermission(String name) { - super(name); - } + @Override public String getActions() { return null; } - /** - * Creates an instance of this class with the given name and an action list. - * The action list is ignored and should be {@code null}. - * - * @param name - * the name of the new {@code NetPermission} instance. - * @param actions - * the ignored action string. - */ - public NetPermission(String name, String actions) { - super(name, actions); - } + @Override public boolean implies(Permission permission) { return true; } } diff --git a/luni/src/main/java/java/net/SocketPermission.java b/luni/src/main/java/java/net/SocketPermission.java index 92168c5..fbbfc70 100644 --- a/luni/src/main/java/java/net/SocketPermission.java +++ b/luni/src/main/java/java/net/SocketPermission.java @@ -17,624 +17,16 @@ package java.net; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; import java.io.Serializable; import java.security.Permission; -import java.security.PermissionCollection; -import java.util.Locale; /** - * Legacy security code; this class exists for compatibility only. + * Legacy security code; do not use. */ public final class SocketPermission extends Permission implements Serializable { + public SocketPermission(String host, String action) { super(""); } - private static final long serialVersionUID = -7204263841984476862L; + @Override public String getActions() { return null; } - // Bit masks for each of the possible actions - static final int SP_CONNECT = 1; - - static final int SP_LISTEN = 2; - - static final int SP_ACCEPT = 4; - - static final int SP_RESOLVE = 8; - - // list of actions permitted for socket permission in order, indexed by mask - // value - private static final String[] actionNames = { "", "connect", "listen", "", - "accept", "", "", "", "resolve" }; - - // If a wildcard is present store the information - private transient boolean isPartialWild; - - private transient boolean isWild; - - // The highest port number - private static final int HIGHEST_PORT = 65535; - - // The lowest port number - private static final int LOWEST_PORT = 0; - - transient String hostName; // Host name as returned by InetAddress - - transient String ipString; // IP address as returned by InetAddress - - transient boolean resolved; // IP address has been resolved - - // the port range; - transient int portMin = LOWEST_PORT; - - transient int portMax = HIGHEST_PORT; - - private String actions; // List of all actions allowed by this permission - - transient int actionsMask = SP_RESOLVE; - - /** - * Constructs a new {@code SocketPermission} instance. The hostname can be a - * DNS name, an individual hostname, an IP address or the empty string which - * implies {@code localhost}. The port or port range is optional. - * <p> - * The action list is a comma-separated list which can consists of the - * possible operations {@code "connect"}, {@code "listen"}, {@code "accept"} - * , and {@code "resolve"}. They are case-insensitive and can be put - * together in any order. {@code "resolve"} is implied per default. - * - * @param host - * the hostname this permission is valid for. - * @param action - * the action string of this permission. - */ - public SocketPermission(String host, String action) { - super(host.isEmpty() ? "localhost" : host); - hostName = getHostString(host); - if (action == null) { - throw new NullPointerException(); - } - if (action.isEmpty()) { - throw new IllegalArgumentException(); - } - - setActions(action); - actions = toCanonicalActionString(action); - // Use host since we are only checking for port presence - parsePort(host, hostName); - } - - /** - * Compares the argument {@code o} to this instance and returns {@code true} - * if they represent the same permission using a class specific comparison. - * - * @param other - * the object to compare with this {@code SocketPermission} - * instance. - * @return {@code true} if they represent the same permission, {@code false} - * otherwise. - * @see #hashCode - */ - @Override - public boolean equals(Object other) { - if (this == other) { - return true; - } - if (other == null || this.getClass() != other.getClass()) { - return false; - } - SocketPermission sp = (SocketPermission) other; - if (!hostName.equalsIgnoreCase(sp.hostName)) { - if (getIPString(true) == null || !ipString.equalsIgnoreCase(sp.getIPString(true))) { - return false; - } - } - if (this.actionsMask != SP_RESOLVE) { - if (this.portMin != sp.portMin) { - return false; - } - if (this.portMax != sp.portMax) { - return false; - } - } - return this.actionsMask == sp.actionsMask; - } - - /** - * Returns the hash value for this {@code SocketPermission} instance. Any - * two objects which returns {@code true} when passed to {@code equals()} - * must return the same value as a result of this method. - * - * @return the hashcode value for this instance. - * @see #equals - */ - @Override - public int hashCode() { - return hostName.hashCode() ^ actionsMask ^ portMin ^ portMax; - } - - /** - * Gets a comma-separated list of all actions allowed by this permission. If - * more than one action is returned they follow this order: {@code connect}, - * {@code listen}, {@code accept}, {@code resolve}. - * - * @return the comma-separated action list. - */ - @Override - public String getActions() { - return actions; - } - - /** - * Stores the actions for this permission as a bit field. - * - * @param actions - * java.lang.String the action list - */ - private void setActions(String actions) throws IllegalArgumentException { - if (actions.isEmpty()) { - return; - } - boolean parsing = true; - String action; - StringBuilder sb = new StringBuilder(); - int pos = 0, length = actions.length(); - while (parsing) { - char c; - sb.setLength(0); - while (pos < length && (c = actions.charAt(pos++)) != ',') { - sb.append(c); - } - if (pos == length) { - parsing = false; - } - action = sb.toString().trim().toLowerCase(Locale.US); - if (action.equals(actionNames[SP_CONNECT])) { - actionsMask |= SP_CONNECT; - } else if (action.equals(actionNames[SP_LISTEN])) { - actionsMask |= SP_LISTEN; - } else if (action.equals(actionNames[SP_ACCEPT])) { - actionsMask |= SP_ACCEPT; - } else if (action.equals(actionNames[SP_RESOLVE])) { - // do nothing - } else { - throw new IllegalArgumentException("Invalid action: " + action); - } - } - } - - /** - * Checks whether this {@code SocketPermission} instance allows all actions - * which are allowed by the given permission object {@code p}. All argument - * permission actions, hosts and ports must be implied by this permission - * instance in order to return {@code true}. This permission may imply - * additional actions not present in the argument permission. - * - * @param p - * the socket permission which has to be implied by this - * instance. - * @return {@code true} if this permission instance implies all permissions - * represented by {@code p}, {@code false} otherwise. - */ - @Override - public boolean implies(Permission p) { - SocketPermission sp; - try { - sp = (SocketPermission) p; - } catch (ClassCastException e) { - return false; - } - - // tests if the action list of p is the subset of the one of the - // receiver - if (sp == null || (actionsMask & sp.actionsMask) != sp.actionsMask) { - return false; - } - - // only check the port range if the action string of the current object - // is not "resolve" - if (!p.getActions().equals("resolve")) { - if ((sp.portMin < this.portMin) || (sp.portMax > this.portMax)) { - return false; - } - } - - // Verify the host is valid - return checkHost(sp); - } - - /** - * Creates a new {@code PermissionCollection} to store {@code - * SocketPermission} objects. - * - * @return the new permission collection. - */ - @Override - public PermissionCollection newPermissionCollection() { - return new SocketPermissionCollection(); - } - - /** - * Parse the port, including the minPort, maxPort - * @param hostPort the host[:port] one - * @param host the host name we just get - * @throws IllegalArgumentException If the port is not a positive number or minPort - * is not less than or equal maxPort - */ - private void parsePort(String hostPort, String host) throws IllegalArgumentException { - String port = hostPort.substring(host.length()); - String emptyString = ""; - - if (emptyString.equals(port)) { - // Not specified - portMin = 80; - portMax = 80; - return; - } - - if (":*".equals(port)) { - // The port range should be 0-65535 - portMin = 0; - portMax = 65535; - return; - } - - // Omit ':' - port = port.substring(1); - int negIdx = port.indexOf('-'); - String strPortMin = emptyString; - String strPortMax = emptyString; - if (-1 == negIdx) { - // No neg mark, only one number - strPortMin = port; - strPortMax = port; - } else { - strPortMin = port.substring(0, negIdx); - strPortMax = port.substring(negIdx + 1); - if (emptyString.equals(strPortMin)) { - strPortMin = "0"; - } - if (emptyString.equals(strPortMax)) { - strPortMax = "65535"; - } - } - try { - portMin = Integer.valueOf(strPortMin).intValue(); - portMax = Integer.valueOf(strPortMax).intValue(); - - if (portMin > portMax) { - throw new IllegalArgumentException("MinPort is greater than MaxPort: " + port); - } - } catch (NumberFormatException e) { - throw new IllegalArgumentException("Invalid port number: " + port); - } - } - - /** - * Creates a canonical action list. - * - * @param action - * java.lang.String - * - * @return java.lang.String - */ - private String toCanonicalActionString(String action) { - if (action == null || action.isEmpty() || actionsMask == SP_RESOLVE) { - return actionNames[SP_RESOLVE]; // If none specified return the - } - // implied action resolve - StringBuilder sb = new StringBuilder(); - if ((actionsMask & SP_CONNECT) == SP_CONNECT) { - sb.append(','); - sb.append(actionNames[SP_CONNECT]); - } - if ((actionsMask & SP_LISTEN) == SP_LISTEN) { - sb.append(','); - sb.append(actionNames[SP_LISTEN]); - } - if ((actionsMask & SP_ACCEPT) == SP_ACCEPT) { - sb.append(','); - sb.append(actionNames[SP_ACCEPT]); - } - sb.append(','); - sb.append(actionNames[SP_RESOLVE]);// Resolve is always implied - // Don't copy the first ','. - return actions = sb.substring(1, sb.length()); - } - - private String getIPString(boolean isCheck) { - if (!resolved) { - try { - return InetAddress.getAllByName(hostName)[0].getHostAddress(); - } catch (UnknownHostException ignored) { - } - resolved = true; - } - return null; - } - - /** - * Get the host part from the host[:port] one. The host should be - * - * <pre> - * host = (hostname | IPv4address | IPv6reference | IPv6 in full uncompressed form) - * </pre> - * - * The wildcard "*" may be included once in a DNS name host specification. - * If it is included, it must be in the leftmost position - * - * @param host - * the {@code host[:port]} string. - * @return the host name. - * @throws IllegalArgumentException - * if the host is invalid. - */ - private String getHostString(String host) throws IllegalArgumentException { - host = host.trim(); - int idx = -1; - idx = host.indexOf(':'); - isPartialWild = (host.length() > 0 && host.charAt(0) == '*'); - if (isPartialWild) { - resolved = true; - isWild = (host.length() == 1); - if (isWild) { - return host; - } - if (idx > -1) { - host = host.substring(0, idx); - } - return host.toLowerCase(Locale.US); - } - - int lastIdx = host.lastIndexOf(':'); - - if (idx == lastIdx) { - if (-1 != idx) { - // only one colon, should be port - host = host.substring(0, idx); - } - return host.toLowerCase(Locale.US); - } - // maybe IPv6 - boolean isFirstBracket = (host.charAt(0) == '['); - if (!isFirstBracket) { - // No bracket, should be in full form - int colonNum = 0; - for (int i = 0; i < host.length(); ++i) { - if (host.charAt(i) == ':') { - colonNum++; - } - } - // Get rid of the colon before port - if (8 == colonNum) { - host = host.substring(0, lastIdx); - } - if (isIP6AddressInFullForm(host)) { - return host.toLowerCase(Locale.US); - } - throw new IllegalArgumentException("Invalid port number: " + host); - } - // forward bracket found - int bbracketIdx = host.indexOf(']'); - if (-1 == bbracketIdx) { - // no back bracket found, wrong - throw new IllegalArgumentException("Invalid port number: " + host); - } - host = host.substring(0, bbracketIdx + 1); - if (isValidIP6Address(host)) { - return host.toLowerCase(Locale.US); - } - throw new IllegalArgumentException("Invalid port number: " + host); - } - - private static boolean isValidHexChar(char c) { - return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f'); - } - - private static boolean isValidIP4Word(String word) { - char c; - if (word.length() < 1 || word.length() > 3) { - return false; - } - for (int i = 0; i < word.length(); i++) { - c = word.charAt(i); - if (!(c >= '0' && c <= '9')) { - return false; - } - } - if (Integer.parseInt(word) > 255) { - return false; - } - return true; - } - - private static boolean isIP6AddressInFullForm(String ipAddress) { - if (isValidIP6Address(ipAddress)) { - int doubleColonIndex = ipAddress.indexOf("::"); - if (doubleColonIndex >= 0) { - // Simplified form which contains :: - return false; - } - return true; - } - return false; - } - - private static boolean isValidIP6Address(String ipAddress) { - int length = ipAddress.length(); - boolean doubleColon = false; - int numberOfColons = 0; - int numberOfPeriods = 0; - int numberOfPercent = 0; - String word = ""; - char c = 0; - char prevChar = 0; - int offset = 0; // offset for [] IP addresses - - if (length < 2) { - return false; - } - - for (int i = 0; i < length; i++) { - prevChar = c; - c = ipAddress.charAt(i); - switch (c) { - - // case for an open bracket [x:x:x:...x] - case '[': - if (i != 0) { - return false; // must be first character - } - if (ipAddress.charAt(length - 1) != ']') { - return false; // must have a close ] - } - offset = 1; - if (length < 4) { - return false; - } - break; - - // case for a closed bracket at end of IP [x:x:x:...x] - case ']': - if (i != length - 1) { - return false; // must be last character - } - if (ipAddress.charAt(0) != '[') { - return false; // must have a open [ - } - break; - - // case for the last 32-bits represented as IPv4 x:x:x:x:x:x:d.d.d.d - case '.': - numberOfPeriods++; - if (numberOfPeriods > 3) { - return false; - } - if (!isValidIP4Word(word)) { - return false; - } - if (numberOfColons != 6 && !doubleColon) { - return false; - } - // a special case ::1:2:3:4:5:d.d.d.d allows 7 colons with an - // IPv4 ending, otherwise 7 :'s is bad - if (numberOfColons == 7 && ipAddress.charAt(0 + offset) != ':' - && ipAddress.charAt(1 + offset) != ':') { - return false; - } - word = ""; - break; - - case ':': - numberOfColons++; - if (numberOfColons > 7) { - return false; - } - if (numberOfPeriods > 0) { - return false; - } - if (prevChar == ':') { - if (doubleColon) { - return false; - } - doubleColon = true; - } - word = ""; - break; - case '%': - if (numberOfColons == 0) { - return false; - } - numberOfPercent++; - - // validate that the stuff after the % is valid - if ((i + 1) >= length) { - // in this case the percent is there but no number is - // available - return false; - } - try { - Integer.parseInt(ipAddress.substring(i + 1)); - } catch (NumberFormatException e) { - // right now we just support an integer after the % so if - // this is not - // what is there then return - return false; - } - break; - - default: - if (numberOfPercent == 0) { - if (word.length() > 3) { - return false; - } - if (!isValidHexChar(c)) { - return false; - } - } - word += c; - } - } - - // Check if we have an IPv4 ending - if (numberOfPeriods > 0) { - if (numberOfPeriods != 3 || !isValidIP4Word(word)) { - return false; - } - } else { - // If we're at then end and we haven't had 7 colons then there is a - // problem unless we encountered a doubleColon - if (numberOfColons != 7 && !doubleColon) { - return false; - } - - // If we have an empty word at the end, it means we ended in either - // a : or a . - // If we did not end in :: then this is invalid - if (numberOfPercent == 0) { - if (word == "" && ipAddress.charAt(length - 1 - offset) == ':' - && ipAddress.charAt(length - 2 - offset) != ':') { - return false; - } - } - } - - return true; - } - - /** - * Determines whether or not this permission could refer to the same host as - * sp. - */ - boolean checkHost(SocketPermission sp) { - if (isPartialWild) { - if (isWild) { - return true; // Match on any host - } - int length = hostName.length() - 1; - return sp.hostName.regionMatches(sp.hostName.length() - length, - hostName, 1, length); - } - // The ipString may not be the same, some hosts resolve to - // multiple ips - return (getIPString(false) != null && ipString.equals(sp.getIPString(false))) - || hostName.equals(sp.hostName); - } - - private void writeObject(ObjectOutputStream stream) throws IOException { - stream.defaultWriteObject(); - } - - private void readObject(ObjectInputStream stream) throws IOException, - ClassNotFoundException { - stream.defaultReadObject(); - // Initialize locals - isPartialWild = false; - isWild = false; - portMin = LOWEST_PORT; - portMax = HIGHEST_PORT; - actionsMask = SP_RESOLVE; - hostName = getHostString(getName()); - parsePort(getName(), hostName); - setActions(actions); - } + @Override public boolean implies(Permission permission) { return true; } } diff --git a/luni/src/main/java/java/net/SocketPermissionCollection.java b/luni/src/main/java/java/net/SocketPermissionCollection.java deleted file mode 100644 index 1611308..0000000 --- a/luni/src/main/java/java/net/SocketPermissionCollection.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package java.net; - -import java.security.Permission; -import java.security.PermissionCollection; -import java.util.Enumeration; -import java.util.Vector; - -/** - * Legacy security code; this class exists for compatibility only. - */ -final class SocketPermissionCollection extends PermissionCollection { - - private static final long serialVersionUID = 2787186408602843674L; - - private Vector<Permission> permissions = new Vector<Permission>(); - - // Constructs a new instance of this class. - public SocketPermissionCollection() { - } - - // Adds the argument to the collection. - @Override - public void add(Permission permission) { - if (isReadOnly()) { - throw new IllegalStateException(); - } - if (!(permission instanceof SocketPermission)) { - throw new IllegalArgumentException(permission.toString()); - } - permissions.addElement(permission); - } - - // Returns an enumeration of the permissions - @Override - public Enumeration<Permission> elements() { - return permissions.elements(); - } - - /** - * Returns whether this permission collection implies {@code permission}. - * Basically it tests whether {@code permission} is the subset of this - * collection. - */ - @Override - public boolean implies(Permission permission) { - if (!(permission instanceof SocketPermission)) { - return false; - } - SocketPermission sp, argPerm = (SocketPermission) permission; - int pmask = argPerm.actionsMask; - int allMask = 0; - int i = 0, count = permissions.size(); - while ((i < count) && ((allMask & pmask) != pmask)) { - sp = (SocketPermission) permissions.elementAt(i); - if (sp.checkHost(argPerm)) { - if ((sp.actionsMask & SocketPermission.SP_RESOLVE) == SocketPermission.SP_RESOLVE) { - allMask |= SocketPermission.SP_RESOLVE; - } - // Only set flags if the port range and host can be implied - if ((argPerm.portMin >= sp.portMin) - && (argPerm.portMax <= sp.portMax)) { - if ((sp.actionsMask & SocketPermission.SP_CONNECT) == SocketPermission.SP_CONNECT) { - allMask |= SocketPermission.SP_CONNECT; - } - if ((sp.actionsMask & SocketPermission.SP_ACCEPT) == SocketPermission.SP_ACCEPT) { - allMask |= SocketPermission.SP_ACCEPT; - } - if ((sp.actionsMask & SocketPermission.SP_LISTEN) == SocketPermission.SP_LISTEN) { - allMask |= SocketPermission.SP_LISTEN; - } - } - } - ++i; - } - - return (allMask & pmask) == pmask; - } -} diff --git a/luni/src/main/java/java/security/AccessControlContext.java b/luni/src/main/java/java/security/AccessControlContext.java index 470870d..9762c41 100644 --- a/luni/src/main/java/java/security/AccessControlContext.java +++ b/luni/src/main/java/java/security/AccessControlContext.java @@ -32,175 +32,16 @@ package java.security; -import java.util.ArrayList; -import org.apache.harmony.security.fortress.PolicyUtils; - /** - * {@code AccessControlContext} encapsulates the {@code ProtectionDomain}s on - * which access control decisions are based. + * Legacy security code; do not use. */ public final class AccessControlContext { - - // List of ProtectionDomains wrapped by the AccessControlContext - // It has the following characteristics: - // - 'context' can not be null - // - never contains null(s) - // - all elements are unique (no dups) - ProtectionDomain[] context; - - DomainCombiner combiner; - - /** - * Constructs a new instance of {@code AccessControlContext} with the - * specified {@code AccessControlContext} and {@code DomainCombiner}. - * - * @param acc - * the {@code AccessControlContext} related to the given {@code - * DomainCombiner} - * @param combiner - * the {@code DomainCombiner} related to the given {@code - * AccessControlContext} - * @throws NullPointerException - * if {@code acc} is {@code null} - */ public AccessControlContext(AccessControlContext acc, DomainCombiner combiner) { - // no need to clone() here as ACC is immutable - this.context = acc.context; - this.combiner = combiner; - } - - /** - * Constructs a new instance of {@code AccessControlContext} with the - * specified array of {@code ProtectionDomain}s. - * - * @param context - * the {@code ProtectionDomain}s that are used to perform access - * checks in the context of this {@code AccessControlContext} - * @throws NullPointerException - * if {@code context} is {@code null} - */ - public AccessControlContext(ProtectionDomain[] context) { - if (context == null) { - throw new NullPointerException("context can not be null"); - } - if (context.length != 0) { - // remove dup entries - ArrayList<ProtectionDomain> a = new ArrayList<ProtectionDomain>(); - for (int i = 0; i < context.length; i++) { - if (context[i] != null && !a.contains(context[i])) { - a.add(context[i]); - } - } - if (a.size() != 0) { - this.context = new ProtectionDomain[a.size()]; - a.toArray(this.context); - } - } - if (this.context == null) { - // Prevent numerous checks for 'context==null' - this.context = new ProtectionDomain[0]; - } - } - - /** - * Checks the specified permission against the vm's current security policy. - * The check is based on this {@code AccessControlContext} as opposed to the - * {@link AccessController#checkPermission(Permission)} method which - * performs access checks based on the context of the current thread. This - * method returns silently if the permission is granted, otherwise an - * {@code AccessControlException} is thrown. - * <p> - * A permission is considered granted if every {@link ProtectionDomain} in - * this context has been granted the specified permission. - * <p> - * If privileged operations are on the call stack, only the {@code - * ProtectionDomain}s from the last privileged operation are taken into - * account. - * <p> - * If inherited methods are on the call stack, the protection domains of the - * declaring classes are checked, not the protection domains of the classes - * on which the method is invoked. - * - * @param perm - * the permission to check against the policy - * @throws AccessControlException - * if the specified permission is not granted - * @throws NullPointerException - * if the specified permission is {@code null} - * @see AccessController#checkPermission(Permission) - */ - public void checkPermission(Permission perm) throws AccessControlException { - if (perm == null) { - throw new NullPointerException("Permission cannot be null"); - } - for (int i = 0; i < context.length; i++) { - if (!context[i].implies(perm)) { - throw new AccessControlException("Permission check failed " + perm, perm); - } - } } + public AccessControlContext(ProtectionDomain[] context) { } - /** - * Compares the specified object with this {@code AccessControlContext} for - * equality. Returns {@code true} if the specified object is also an - * instance of {@code AccessControlContext}, and the two contexts - * encapsulate the same {@code ProtectionDomain}s. The order of the {@code - * ProtectionDomain}s is ignored by this method. - * - * @param obj - * object to be compared for equality with this {@code - * AccessControlContext} - * @return {@code true} if the specified object is equal to this {@code - * AccessControlContext}, otherwise {@code false} - */ - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj instanceof AccessControlContext) { - AccessControlContext that = (AccessControlContext) obj; - if (!(PolicyUtils.matchSubset(context, that.context) && PolicyUtils - .matchSubset(that.context, context))) { - return false; - } - if (combiner != null) { - return combiner.equals(that.combiner); - } - return that.combiner == null; - } - return false; - } - - /** - * Returns the {@code DomainCombiner} associated with this {@code - * AccessControlContext}. - * - * @return the {@code DomainCombiner} associated with this {@code - * AccessControlContext} - */ - public DomainCombiner getDomainCombiner() { - return combiner; - } - - - /** - * Returns the hash code value for this {@code AccessControlContext}. - * Returns the same hash code for {@code AccessControlContext}s that are - * equal to each other as required by the general contract of - * {@link Object#hashCode}. - * - * @return the hash code value for this {@code AccessControlContext} - * @see Object#equals(Object) - * @see AccessControlContext#equals(Object) - */ - public int hashCode() { - int hash = 0; - for (int i = 0; i < context.length; i++) { - hash ^= context[i].hashCode(); - } - return hash; - } + public void checkPermission(Permission perm) throws AccessControlException { } + public DomainCombiner getDomainCombiner() { return null; } } diff --git a/luni/src/main/java/java/security/AccessController.java b/luni/src/main/java/java/security/AccessController.java index d49927c..f1f6bf9 100644 --- a/luni/src/main/java/java/security/AccessController.java +++ b/luni/src/main/java/java/security/AccessController.java @@ -33,12 +33,10 @@ package java.security; /** - * Legacy security code; this class exists for compatibility only. + * Legacy security code; do not use. */ public final class AccessController { - - private AccessController() { - } + private AccessController() { } /** * Calls {@code action.run()}. @@ -88,24 +86,7 @@ public final class AccessController { return doPrivileged(action); } - /** - * Does nothing. - */ - public static void checkPermission(Permission permission) throws AccessControlException { - } + public static void checkPermission(Permission permission) throws AccessControlException { } - /** - * Returns the {@code AccessControlContext} for the current {@code Thread} - * including the inherited access control context of the thread that spawned - * the current thread (recursively). - * - * <p>The returned context may be used to perform access checks at a later - * point in time, possibly by another thread. - * - * @return the {@code AccessControlContext} for the current {@code Thread} - * @see Thread#currentThread - */ - public static AccessControlContext getContext() { - return new AccessControlContext(new ProtectionDomain[0]); - } + public static AccessControlContext getContext() { return new AccessControlContext(null); } } diff --git a/luni/src/main/java/java/security/AllPermission.java b/luni/src/main/java/java/security/AllPermission.java index c05a230..1f54e78 100644 --- a/luni/src/main/java/java/security/AllPermission.java +++ b/luni/src/main/java/java/security/AllPermission.java @@ -17,110 +17,15 @@ package java.security; - /** - * Legacy security code; this class exists for compatibility only. + * Legacy security code; do not use. */ public final class AllPermission extends Permission { + public AllPermission(String name, String actions) { super(""); } - /** - * @serial - */ - private static final long serialVersionUID = -2916474571451318075L; - - // Permission name - private static final String ALL_PERMISSIONS = "<all permissions>"; - - // Actions name - private static final String ALL_ACTIONS = "<all actions>"; - - /** - * Constructs a new instance of {@code AllPermission}. The two argument - * version is provided for class {@code Policy} so that it has a consistent - * call pattern across all permissions. The name and action list are both - * ignored. - * - * @param name - * ignored. - * @param actions - * ignored. - */ - public AllPermission(String name, String actions) { - super(ALL_PERMISSIONS); - } - - /** - * Constructs a new instance of {@code AllPermission}. - */ - public AllPermission() { - super(ALL_PERMISSIONS); - } - - /** - * Compares the specified object with this {@code AllPermission} for - * equality and returns {@code true} if the specified object is equal, - * {@code false} otherwise. To be equal, the given object needs to be an - * instance of {@code AllPermission}. - * - * @param obj - * object to be compared for equality with this {@code - * AllPermission}. - * @return {@code true} if the specified object is equal to this {@code - * AllPermission}, otherwise {@code false}. - * @see #hashCode - */ - @Override - public boolean equals(Object obj) { - return (obj instanceof AllPermission); - } - - /** - * Returns the hash code value for this {@code AllPermission}. Returns the - * same hash code for {@code AllPermission}s that are equal to each other as - * required by the general contract of {@link Object#hashCode}. - * - * @return the hash code value for this {@code AllPermission}. - * @see Object#equals(Object) - * @see AllPermission#equals(Object) - */ - @Override - public int hashCode() { - return 1; - } - - /** - * Returns the actions associated with this {@code AllPermission}. Since - * {@code AllPermission} objects allow all actions, this method returns - * always the string "<all actions>". - * - * @return the actions associated with this {@code AllPermission}. - */ - @Override - public String getActions() { - return ALL_ACTIONS; - } + public AllPermission() { super(""); } - /** - * Indicates whether the given permission is implied by this permission. - * {@code AllPermission} objects imply all other permissions. - * - * @return always {@code true}. - * @param permission - * the permission to check. - */ - @Override - public boolean implies(Permission permission) { - return true; - } + @Override public String getActions() { return null; } - /** - * Returns a new {@code PermissionCollection} for holding permissions of - * this class. - * - * @return a new {@code PermissionCollection}. - */ - @Override - public PermissionCollection newPermissionCollection() { - return new AllPermissionCollection(); - } + @Override public boolean implies(Permission permission) { return true; } } diff --git a/luni/src/main/java/java/security/AllPermissionCollection.java b/luni/src/main/java/java/security/AllPermissionCollection.java index ee1c22c..ae9b72c 100644 --- a/luni/src/main/java/java/security/AllPermissionCollection.java +++ b/luni/src/main/java/java/security/AllPermissionCollection.java @@ -17,122 +17,15 @@ package java.security; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.ObjectStreamField; import java.util.Enumeration; -import java.util.NoSuchElementException; /** - * Specific {@code PermissionCollection} for storing {@code AllPermission}s. All - * instances of {@code AllPermission} are equivalent, so it is enough to store a - * single added instance. - * - * @see AllPermission + * Legacy security code; do not use. */ final class AllPermissionCollection extends PermissionCollection { + @Override public void add(Permission permission) { } - private static final long serialVersionUID = -4023755556366636806L; - - private static final ObjectStreamField[] serialPersistentFields = { - new ObjectStreamField("all_allowed", boolean.class), - }; - - // Single element of collection. - private transient Permission all; - - /** - * Adds an {@code AllPermission} to the collection. - */ - @Override - public void add(Permission permission) { - if (isReadOnly()) { - throw new SecurityException("collection is read-only"); - } - if (!(permission instanceof AllPermission)) { - throw new IllegalArgumentException("Invalid permission: " + permission); - } - all = permission; - } - - /** - * Returns the enumeration of the collection. - */ - @Override - public Enumeration<Permission> elements() { - return new SingletonEnumeration<Permission>(all); - } - - /** - * An auxiliary implementation for enumerating a single object. - * - */ - static final class SingletonEnumeration<E> implements Enumeration<E> { - - private E element; - - /** - * Constructor taking the single element. - * @param single the element - */ - public SingletonEnumeration(E single) { - element = single; - } - - /** - * Returns true if the element is not enumerated yet. - */ - public boolean hasMoreElements() { - return element != null; - } - - /** - * Returns the element and clears internal reference to it. - */ - public E nextElement() { - if (element == null) { - throw new NoSuchElementException(); - } - E last = element; - element = null; - return last; - } - } - - /** - * Indicates whether the argument permission is implied by the receiver. - * {@code AllPermission} objects imply all other permissions. - * - * @return boolean {@code true} if the argument permission is implied by the - * receiver, and {@code false} if it is not. - * @param permission - * the permission to check. - */ - @Override - public boolean implies(Permission permission) { - return all != null; - } - - /** - * Writes the fields according to expected format, adding the boolean field - * {@code all_allowed} which is {@code true} if this collection is not - * empty. - */ - private void writeObject(java.io.ObjectOutputStream out) throws IOException { - ObjectOutputStream.PutField fields = out.putFields(); - fields.put("all_allowed", all != null); - out.writeFields(); - } + @Override public Enumeration<Permission> elements() { return null; } - /** - * Restores internal state. - */ - private void readObject(java.io.ObjectInputStream in) throws IOException, - ClassNotFoundException { - ObjectInputStream.GetField fields = in.readFields(); - if (fields.get("all_allowed", false)) { - all = new AllPermission(); - } - } + @Override public boolean implies(Permission permission) { return true; } } diff --git a/luni/src/main/java/java/security/BasicPermission.java b/luni/src/main/java/java/security/BasicPermission.java index 9bc59ac..38ee757 100644 --- a/luni/src/main/java/java/security/BasicPermission.java +++ b/luni/src/main/java/java/security/BasicPermission.java @@ -17,181 +17,17 @@ package java.security; -import java.io.IOException; import java.io.Serializable; /** - * Legacy security code; this class exists for compatibility only. + * Legacy security code; do not use. */ -public abstract class BasicPermission extends Permission implements - Serializable { +public abstract class BasicPermission extends Permission implements Serializable { + public BasicPermission(String name) { super(""); } - private static final long serialVersionUID = 6279438298436773498L; + public BasicPermission(String name, String action) { super(""); } - /** - * Constructs a new instance of {@code BasicPermission} with the specified - * name. - * - * @param name - * the name of the permission. - * @throws NullPointerException if {@code name} is {@code null}. - * @throws IllegalArgumentException if {@code name.length() == 0}. - */ - public BasicPermission(String name) { - super(name); - checkName(name); - } + @Override public String getActions() { return null; } - /** - * Constructs a new instance of {@code BasicPermission} with the specified - * name. The {@code action} parameter is ignored. - * - * @param name - * the name of the permission. - * @param action - * is ignored. - * @throws NullPointerException - * if {@code name} is {@code null}. - * @throws IllegalArgumentException - * if {@code name.length() == 0}. - */ - public BasicPermission(String name, String action) { - super(name); - checkName(name); - } - - /** - * Checks name parameter - */ - private final void checkName(String name) { - if (name == null) { - throw new NullPointerException("name == null"); - } - if (name.isEmpty()) { - throw new IllegalArgumentException("name.isEmpty()"); - } - } - - /** - * Compares the specified object with this {@code BasicPermission} for - * equality. Returns {@code true} if the specified object has the same class - * and the two {@code Permissions}s have the same name. - * <p> - * The {@link #implies(Permission)} method should be used for making access - * control checks. - * - * @param obj - * object to be compared for equality with this {@code - * BasicPermission}. - * @return {@code true} if the specified object is equal to this {@code - * BasicPermission}, otherwise {@code false}. - */ - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - - if (obj != null && obj.getClass() == this.getClass()) { - return this.getName().equals(((Permission)obj).getName()); - } - return false; - } - - /** - * Returns the hash code value for this {@code BasicPermission}. Returns the - * same hash code for {@code BasicPermission}s that are equal to each other - * as required by the general contract of {@link Object#hashCode}. - * - * @return the hash code value for this {@code BasicPermission}. - * @see Object#equals(Object) - * @see BasicPermission#equals(Object) - */ - @Override - public int hashCode() { - return getName().hashCode(); - } - - /** - * Returns the actions associated with this permission. Since {@code - * BasicPermission} instances have no actions, an empty string is returned. - * - * @return an empty string. - */ - @Override - public String getActions() { - return ""; - } - - /** - * Indicates whether the specified permission is implied by this permission. - * - * @param permission - * the permission to check against this permission. - * @return {@code true} if the specified permission is implied by this - * permission, {@code false} otherwise. - */ - @Override - public boolean implies(Permission permission) { - if (permission != null && permission.getClass() == this.getClass()) { - return nameImplies(getName(), permission.getName()); - } - return false; - } - - /** - * Checks if {@code thisName} implies {@code thatName}, - * accordingly to hierarchical property naming convention. - * It is assumed that names cannot be {@code null} or empty. - */ - static boolean nameImplies(String thisName, String thatName) { - if (thisName == thatName) { - return true; - } - int end = thisName.length(); - if (end > thatName.length()) { - return false; - } - if (thisName.charAt(--end) == '*' - && (end == 0 || thisName.charAt(end - 1) == '.')) { - //wildcard found - end--; - } else if (end != (thatName.length()-1)) { - //names are not equal - return false; - } - for (int i = end; i >= 0; i--) { - if (thisName.charAt(i) != thatName.charAt(i)) { - return false; - } - } - return true; - } - - /** - * Returns an empty {@link PermissionCollection} for holding permissions. - * <p> - * For {@code PermissionCollection} (and subclasses which do not override - * this method), the collection which is returned does <em>not</em> invoke - * the {@link #implies(Permission)} method of the permissions which are - * stored in it when checking if the collection implies a permission. - * Instead, it assumes that if the type of the permission is correct, and - * the name of the permission is correct, there is a match. - * - * @return an empty {@link PermissionCollection} for holding permissions. - * @see BasicPermissionCollection - */ - @Override - public PermissionCollection newPermissionCollection() { - return new BasicPermissionCollection(); - } - - /** - * Checks name after default deserialization. - */ - private void readObject(java.io.ObjectInputStream in) throws IOException, - ClassNotFoundException { - in.defaultReadObject(); - checkName(this.getName()); - } + @Override public boolean implies(Permission permission) { return true; } } diff --git a/luni/src/main/java/java/security/BasicPermissionCollection.java b/luni/src/main/java/java/security/BasicPermissionCollection.java deleted file mode 100644 index fae3854..0000000 --- a/luni/src/main/java/java/security/BasicPermissionCollection.java +++ /dev/null @@ -1,198 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package java.security; - -import java.io.IOException; -import java.io.InvalidObjectException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.ObjectStreamField; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.Map; - -/** - * Specific {@code PermissionCollection} for storing {@code BasicPermissions} of - * arbitrary type. - * - * @see BasicPermission - * @see PermissionCollection - */ -final class BasicPermissionCollection extends PermissionCollection { - - private static final long serialVersionUID = 739301742472979399L; - - private static final ObjectStreamField[] serialPersistentFields = { - new ObjectStreamField("all_allowed", boolean.class), - new ObjectStreamField("permissions", Hashtable.class), - new ObjectStreamField("permClass", Class.class), - }; - - //should be final, but because of writeObject() cannot be - private transient Map<String, Permission> items = new HashMap<String, Permission>(); - - // true if this Collection contains a BasicPermission with '*' as its permission name - private transient boolean allEnabled; // = false; - - private Class<? extends Permission> permClass; - - /** - * Adds a permission to the collection. The first added permission must be a - * subclass of BasicPermission, next permissions must be of the same class - * as the first one. - * - * @see java.security.PermissionCollection#add(java.security.Permission) - */ - @Override - public void add(Permission permission) { - if (isReadOnly()) { - throw new SecurityException("collection is read-only"); - } - if (permission == null) { - throw new IllegalArgumentException("permission == null"); - } - - Class<? extends Permission> inClass = permission.getClass(); - if (permClass != null) { - if (permClass != inClass) { - throw new IllegalArgumentException("Invalid permission: " + permission); - } - } else if( !(permission instanceof BasicPermission)) { - throw new IllegalArgumentException("Invalid permission: " + permission); - } else { - // this is the first element provided that another thread did not add - synchronized (this) { - if (permClass != null && inClass != permClass) { - throw new IllegalArgumentException("Invalid permission: " + permission); - } - permClass = inClass; - } - } - - String name = permission.getName(); - items.put(name, permission); - allEnabled = allEnabled || (name.length() == 1 && '*' == name.charAt(0)); - } - - /** - * Returns enumeration of contained elements. - */ - @Override - public Enumeration<Permission> elements() { - return Collections.enumeration(items.values()); - } - - /** - * Indicates whether the argument permission is implied by the receiver. - * - * @return boolean {@code true} if the argument permission is implied by the - * receiver, and {@code false} if it is not. - * @param permission - * the permission to check. - * @see Permission - */ - @Override - public boolean implies(Permission permission) { - if (permission == null || permission.getClass() != permClass) { - return false; - } - if (allEnabled) { - return true; - } - String checkName = permission.getName(); - //first check direct coincidence - if (items.containsKey(checkName)) { - return true; - } - //now check if there are suitable wildcards - //suppose we have "a.b.c", let's check "a.b.*" and "a.*" - char[] name = checkName.toCharArray(); - //I presume that "a.b.*" does not imply "a.b." - //so the dot at end is ignored - int pos = name.length - 2; - for (; pos >= 0; pos--) { - if (name[pos] == '.') { - break; - } - } - while (pos >= 0) { - name[pos + 1] = '*'; - if (items.containsKey(new String(name, 0, pos + 2))) { - return true; - } - for (--pos; pos >= 0; pos--) { - if (name[pos] == '.') { - break; - } - } - } - return false; - } - - /** - * Expected format is the following: - * <dl> - * <dt>boolean all_allowed - * <dd>This is set to true if this BasicPermissionCollection contains a - * {@code BasicPermission} with '*' as its permission name. - * <dt>Class<T> permClass - * <dd>The class to which all {@code BasicPermission}s in this - * BasicPermissionCollection belongs. - * <dt>Hashtable<K,V> permissions - * <dd>The {@code BasicPermission}s in this collection. All {@code - * BasicPermission}s in the collection must belong to the same class. The - * Hashtable is indexed by the {@code BasicPermission} name; the value of - * the Hashtable entry is the permission. - * </dl> - */ - private void writeObject(java.io.ObjectOutputStream out) throws IOException { - ObjectOutputStream.PutField fields = out.putFields(); - fields.put("all_allowed", allEnabled); - fields.put("permissions", new Hashtable<String, Permission>(items)); - fields.put("permClass", permClass); - out.writeFields(); - } - - /** - * Reads the object from stream and checks its consistency: all contained - * permissions must be of the same subclass of BasicPermission. - */ - private void readObject(java.io.ObjectInputStream in) throws IOException, - ClassNotFoundException { - ObjectInputStream.GetField fields = in.readFields(); - - items = new HashMap<String, Permission>(); - synchronized (this) { - permClass = (Class<? extends Permission>)fields.get("permClass", null); - items.putAll((Hashtable<String, Permission>) fields.get( - "permissions", new Hashtable<String, Permission>())); - for (Iterator<Permission> iter = items.values().iterator(); iter.hasNext();) { - if (iter.next().getClass() != permClass) { - throw new InvalidObjectException("Inconsistent types of contained permissions"); - } - } - allEnabled = fields.get("all_allowed", false); - if (allEnabled && !items.containsKey("*")) { - throw new InvalidObjectException("Invalid state of wildcard flag"); - } - } - } -} diff --git a/luni/src/main/java/java/security/CodeSource.java b/luni/src/main/java/java/security/CodeSource.java index 41104e6..0f1a2fa 100644 --- a/luni/src/main/java/java/security/CodeSource.java +++ b/luni/src/main/java/java/security/CodeSource.java @@ -17,613 +17,23 @@ package java.security; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.OptionalDataException; import java.io.Serializable; -import java.net.SocketPermission; import java.net.URL; -import java.security.cert.CertPath; import java.security.cert.Certificate; -import java.security.cert.CertificateEncodingException; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.List; -import javax.security.auth.x500.X500Principal; -import org.apache.harmony.security.fortress.PolicyUtils; /** - * {@code CodeSource} encapsulates the location from where code is loaded and - * the certificates that were used to verify that code. This information is used - * by {@code SecureClassLoader} to define protection domains for loaded classes. - * - * @see SecureClassLoader - * @see ProtectionDomain + * Legacy security code; do not use. */ public class CodeSource implements Serializable { + public CodeSource(URL location, Certificate[] certs) { } - private static final long serialVersionUID = 4977541819976013951L; - - // Location of this CodeSource object - private URL location; - - // Array of certificates assigned to this CodeSource object - private transient java.security.cert.Certificate[] certs; - - // Array of CodeSigners - private transient CodeSigner[] signers; - - // SocketPermission() in implies() method takes to many time. - // Need to cache it for better performance. - private transient SocketPermission sp; - - // Cached factory used to build CertPath-s in <code>getCodeSigners()</code>. - private transient CertificateFactory factory; - - /** - * Constructs a new instance of {@code CodeSource} with the specified - * {@code URL} and the {@code Certificate}s. - * - * @param location - * the {@code URL} representing the location from where code is - * loaded, maybe {@code null}. - * @param certs - * the {@code Certificate} used to verify the code, loaded from - * the specified {@code location}, maybe {@code null}. - */ - public CodeSource(URL location, Certificate[] certs) { - this.location = location; - if (certs != null) { - this.certs = new Certificate[certs.length]; - System.arraycopy(certs, 0, this.certs, 0, certs.length); - } - } - - /** - * Constructs a new instance of {@code CodeSource} with the specified - * {@code URL} and the {@code CodeSigner}s. - * - * @param location - * the {@code URL} representing the location from where code is - * loaded, maybe {@code null}. - * @param signers - * the {@code CodeSigner}s of the code, loaded from the specified - * {@code location}. Maybe {@code null}. - */ - public CodeSource(URL location, CodeSigner[] signers) { - this.location = location; - if (signers != null) { - this.signers = new CodeSigner[signers.length]; - System.arraycopy(signers, 0, this.signers, 0, signers.length); - } - } - - /** - * Compares the specified object with this {@code CodeSource} for equality. - * Returns {@code true} if the specified object is also an instance of - * {@code CodeSource}, points to the same {@code URL} location and the two - * code sources encapsulate the same {@code Certificate}s. The order of the - * {@code Certificate}s is ignored by this method. - * - * @param obj - * object to be compared for equality with this {@code - * CodeSource}. - * @return {@code true} if the specified object is equal to this {@code - * CodeSource}, otherwise {@code false}. - */ - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - - if (!(obj instanceof CodeSource)) { - return false; - } - - CodeSource that = (CodeSource) obj; - - if (this.location != null) { - if (that.location == null) { - return false; - } - if (!this.location.equals(that.location)) { - return false; - } - } else if (that.location != null) { - return false; - } - - // do not use this.certs, as we also need to take care about - // CodeSigners' certificates - Certificate[] thizCerts = getCertificatesNoClone(); - Certificate[] thatCerts = that.getCertificatesNoClone(); - if (!PolicyUtils.matchSubset(thizCerts, thatCerts)) { - return false; - } - if (!PolicyUtils.matchSubset(thatCerts, thizCerts)) { - return false; - } - return true; - } - - /** - * Returns the certificates of this {@code CodeSource}. If the - * {@link #CodeSource(URL, CodeSigner[])} constructor was used to create - * this instance, the certificates are obtained from the supplied signers. - * <p> - * External modifications of the returned {@code Certificate[]} has no - * impact on this {@code CodeSource}. - * - * @return the certificates of this {@code CodeSource} or {@code null} if - * there is none. - */ - public final Certificate[] getCertificates() { - getCertificatesNoClone(); - if (certs == null) { - return null; - } - Certificate[] tmp = new Certificate[certs.length]; - System.arraycopy(certs, 0, tmp, 0, certs.length); - return tmp; - } - - // Acts exactly as {@link #getCertificates()} does, but does not clone the - // array before returning (and returns reference to <code>this.certs</code> - // if this array is not null).<br> - // @return a reference to the certificates array, or null if there are no - // certificates associated. - private Certificate[] getCertificatesNoClone() { - if (certs != null) { - return certs; - } - - if (signers == null) { - return null; - } - // Extract Certificates from the CodeSigner-s - ArrayList<Certificate> v = new ArrayList<Certificate>(); - for (int i = 0; i < signers.length; i++) { - v.addAll(signers[i].getSignerCertPath().getCertificates()); - } - - certs = v.toArray(new Certificate[v.size()]); - return certs; - } - - /** - * Returns the {@code CodeSigner}s of this {@code CodeSource}. If the - * {@link #CodeSource(URL, Certificate[])} constructor was used to create - * this instance, the signers are obtained from the supplied certificates. - * Only X.509 certificates are analyzed. - * - * @return the signers of this {@code CodeSource}, or {@code null} if there - * is none. - */ - public final CodeSigner[] getCodeSigners() { - if (signers != null) { - CodeSigner[] tmp = new CodeSigner[signers.length]; - System.arraycopy(signers, 0, tmp, 0, tmp.length); - return tmp; - } - if(certs == null || factory != null){ - // factory != null means we've done this exercise already. - return null; - } - - X500Principal prevIssuer = null; - ArrayList<Certificate> list = new ArrayList<Certificate>(certs.length); - ArrayList<CodeSigner> asigners = new ArrayList<CodeSigner>(); - - // The presumption is that the chains of certificates are placed - // according to the CertPath agreement: - // - // the lowest certs first; the CAs are at the last - // - // So the following loop scans trough the certs and checks - // that every next certificate is an Issuer of the previous one. - // Any certificate that is not an Issuer of the previous one starts a - // new chain (== a new CertPath) - - for (int i = 0; i < certs.length; i++) { - if (!(certs[i] instanceof X509Certificate)) { - // Only X509Certificate-s are taken into account - see API spec. - continue; - } - X509Certificate x509 = (X509Certificate) certs[i]; - if (prevIssuer == null) { - // start a very first chain - prevIssuer = x509.getIssuerX500Principal(); - list.add(x509); - } else { - X500Principal subj = x509.getSubjectX500Principal(); - if (!prevIssuer.equals(subj)) { - // Ok, this ends the previous chain, - // so transform this one into CertPath ... - CertPath cpath = makeCertPath(list); - if (cpath != null) { - asigners.add(new CodeSigner(cpath, null)); - } - // ... and start a new one - list.clear(); - }// else { it's still the same chain } - prevIssuer = x509.getSubjectX500Principal(); - list.add(x509); - } - } - if (!list.isEmpty()) { - CertPath cpath = makeCertPath(list); - if (cpath != null) { - asigners.add(new CodeSigner(cpath, null)); - } - } - if (asigners.isEmpty()) { - // 'signers' is 'null' already - return null; - } - signers = new CodeSigner[asigners.size()]; - asigners.toArray(signers); - CodeSigner[] tmp = new CodeSigner[asigners.size()]; - System.arraycopy(signers, 0, tmp, 0, tmp.length); - return tmp; - } - - // Makes an CertPath from a given List of X509Certificate-s. - // @param list - // @return CertPath, or null if CertPath cannot be made - private CertPath makeCertPath(List<? extends Certificate> list) { - if (factory == null) { - try { - factory = CertificateFactory.getInstance("X.509"); - } catch (CertificateException ex) { - //? throw new Error("X.509 is a 'must be'", ex); - return null; - } - } - try { - return factory.generateCertPath(list); - } catch (CertificateException ex) { - // ignore(ex) - } - return null; - } - - /** - * Returns the location of this {@code CodeSource}. - * - * @return the location of this {@code CodeSource}, maybe {@code null}. - */ - public final URL getLocation() { - return location; - } - - /** - * Returns the hash code value for this {@code CodeSource}. - * Returns the same hash code for {@code CodeSource}s that are - * equal to each other as required by the general contract of - * {@link Object#hashCode}. - * - * @return the hash code value for this {@code CodeSource}. - * @see Object#equals(Object) - * @see CodeSource#equals(Object) - */ - @Override - public int hashCode() { - // - // hashCode() is undocumented there. Should we also use certs[i] to - // compute the hash ? - // for now, I don't take certs[] into account - return location == null ? 0 : location.hashCode(); - } - - /** - * Indicates whether the specified code source is implied by this {@code - * CodeSource}. Returns {@code true} if all of the following conditions are - * {@code true}, otherwise {@code false}: - * <p> - * <ul> - * <li>{@code cs} is not {@code null} - * <li>if this {@code CodeSource} has associated certificates, all - * certificates are present in {@code cs}. The certificates are extracted - * from the signers if signers are present. - * <li>if this {@code CodeSource}'s location is not {@code null}, the - * following conditions are checked - * <ul> - * <li>this {@code CodeSource}'s location is not {@code null} - * <li>this {@code CodeSource}'s location protocol is equal to {@code cs}'s - * location protocol - * <li>if this {@code CodeSource}'s location host is not {@code null}, the - * following conditions are checked - * <ul> - * <li>{@code cs}'s host is not {@code null} - * <li>the {@link SocketPermission} of this {@code CodeSource}'s location - * host implies the {@code SocketPermission} of {@code cs}'s location host - * </ul> - * <li>if this {@code CodeSource}'s location port != -1 the port of {@code - * cs}'s location is equal to this {@code CodeSource}'s location port - * <li>this {@code CodeSource}'s location file matches {@code cs}'s file - * whereas special wildcard matching applies as described below - * <li>this {@code CodeSource}'s location reference is equal to to {@code - * cs}'s location reference - * </ul> - * </ul> - * <p> - * Note: If this {@code CodeSource} has a {@code null} location and not any - * certificates, this method returns {@code true}. - * <p> - * Matching rules for the {@code CodeSource}'s location file: - * <ul> - * <li>if this {@code CodeSource}'s location file ends with {@code "/-"}, - * then {@code cs}'s file must start with {@code CodeSource}'s location file - * (exclusive the trailing '-') - * <li>if this {@code CodeSource}'s location file ends with {@code "/*"}, - * then {@code cs}'s file must start with {@code CodeSource}'s location file - * (exclusive the trailing '*') and must not have any further '/' - * <li>if this {@code CodeSource}'s location file ends with {@code "/"}, - * then {@code cs}'s file must start with {@code CodeSource}'s location file - * <li>if this {@code CodeSource}'s location file does not end with {@code - * "/"}, then {@code cs}'s file must start with {@code CodeSource}'s - * location file with the '/' appended to it. - * </ul> - * Examples for locations that imply the location - * "http://harmony.apache.org/milestones/M9/apache-harmony.jar": - * - * <pre> - * http: - * http://*/milestones/M9/* - * http://*.apache.org/milestones/M9/* - * http://harmony.apache.org/milestones/- - * http://harmony.apache.org/milestones/M9/apache-harmony.jar - * </pre> - * - * @param cs - * the code source to check. - * @return {@code true} if the argument code source is implied by this - * {@code CodeSource}, otherwise {@code false}. - */ - public boolean implies(CodeSource cs) { - // - // Here, javadoc:N refers to the appropriate item in the API spec for - // the CodeSource.implies() - // The info was taken from the 1.5 final API spec - - // javadoc:1 - if (cs == null) { - return false; - } - - // javadoc:2 - // with a comment: the javadoc says only about certificates and does - // not explicitly mention CodeSigners' certs. - // It seems more convenient to use getCerts() to get the real - // certificates - with a certificates got form the signers - Certificate[] thizCerts = getCertificatesNoClone(); - if (thizCerts != null) { - Certificate[] thatCerts = cs.getCertificatesNoClone(); - if (thatCerts == null - || !PolicyUtils.matchSubset(thizCerts, thatCerts)) { - return false; - } - } - - // javadoc:3 - if (this.location != null) { - //javadoc:3.1 - if (cs.location == null) { - return false; - } - //javadoc:3.2 - if (this.location.equals(cs.location)) { - return true; - } - //javadoc:3.3 - if (!this.location.getProtocol().equals(cs.location.getProtocol())) { - return false; - } - //javadoc:3.4 - String thisHost = this.location.getHost(); - if (thisHost != null) { - String thatHost = cs.location.getHost(); - if (thatHost == null) { - return false; - } - - // 1. According to the spec, an empty string will be considered - // as "localhost" in the SocketPermission - // 2. 'file://' URLs will have an empty getHost() - // so, let's make a special processing of localhost-s, I do - // believe this'll improve performance of file:// code sources - - // - // Don't have to evaluate both the boolean-s each time. - // It's better to evaluate them directly under if() statement. - // - // boolean thisIsLocalHost = thisHost.length() == 0 || "localhost".equals(thisHost); - // boolean thatIsLocalHost = thatHost.length() == 0 || "localhost".equals(thatHost); - // - // if( !(thisIsLocalHost && thatIsLocalHost) && - // !thisHost.equals(thatHost)) { - - if (!((thisHost.length() == 0 || "localhost".equals(thisHost)) && (thatHost - .length() == 0 || "localhost".equals(thatHost))) - && !thisHost.equals(thatHost)) { - - // Obvious, but very slow way.... - // - // SocketPermission thisPerm = new SocketPermission( - // this.location.getHost(), "resolve"); - // SocketPermission thatPerm = new SocketPermission( - // cs.location.getHost(), "resolve"); - // if (!thisPerm.implies(thatPerm)) { - // return false; - // } - // - // let's cache it: - - if (this.sp == null) { - this.sp = new SocketPermission(thisHost, "resolve"); - } - - if (cs.sp == null) { - cs.sp = new SocketPermission(thatHost, "resolve"); - } - - if (!this.sp.implies(cs.sp)) { - return false; - } - } // if( ! this.location.getHost().equals(cs.location.getHost()) - } // if (this.location.getHost() != null) - - //javadoc:3.5 - if (this.location.getPort() != -1) { - if (this.location.getPort() != cs.location.getPort()) { - return false; - } - } - - //javadoc:3.6 - String thisFile = this.location.getFile(); - String thatFile = cs.location.getFile(); - - if (thisFile.endsWith("/-")) { //javadoc:3.6."/-" - if (!thatFile.startsWith(thisFile.substring(0, thisFile - .length() - 2))) { - return false; - } - } else if (thisFile.endsWith("/*")) { //javadoc:3.6."/*" - if (!thatFile.startsWith(thisFile.substring(0, thisFile - .length() - 2))) { - return false; - } - // no further separators(s) allowed - if (thatFile.indexOf("/", thisFile.length() - 1) != -1) { - return false; - } - } else { - // javadoc:3.6."/" - if (!thisFile.equals(thatFile)) { - if (!thisFile.endsWith("/")) { - if (!thatFile.equals(thisFile + "/")) { - return false; - } - } else { - return false; - } - } - } - - //javadoc:3.7 - if (this.location.getRef() != null) { - if (!this.location.getRef().equals(cs.location.getRef())) { - return false; - } - } - // ok, every check was made, and they all were successful. - // it's ok to return true. - } // if this.location != null - - // javadoc: a note about CodeSource with null location and null Certs - // is applicable here - return true; - } - - /** - * Returns a string containing a concise, human-readable description of the - * this {@code CodeSource} including its location, its certificates and its - * signers. - * - * @return a printable representation for this {@code CodeSource}. - */ - @Override - public String toString() { - StringBuilder buf = new StringBuilder(); - buf.append("CodeSource, url="); - buf.append(location == null ? "<null>" : location.toString()); - - if (certs == null) { - buf.append(", <no certificates>"); - } else { - buf.append("\nCertificates [\n"); - for (int i = 0; i < certs.length; i++) { - buf.append(i + 1).append(") ").append(certs[i]).append("\n"); - } - buf.append("]\n"); - } - if (signers != null) { - buf.append("\nCodeSigners [\n"); - for (int i = 0; i < signers.length; i++) { - buf.append(i + 1).append(") ").append(signers[i]).append("\n"); - } - buf.append("]\n"); - } - return buf.toString(); - } - - private void writeObject(ObjectOutputStream oos) throws IOException { - - oos.defaultWriteObject(); + public CodeSource(URL location, CodeSigner[] signers) { } - if (certs == null || certs.length == 0) { - oos.writeInt(0); - } else { - oos.writeInt(certs.length); - for (int i = 0; i < certs.length; i++) { - try { - oos.writeUTF(certs[i].getType()); - byte[] data = certs[i].getEncoded(); - // hope there are no certificates with 'data==null' - oos.writeInt(data.length); - oos.write(data); - } catch (CertificateEncodingException ex) { - throw (IOException) new IOException("Could not store certificate").initCause(ex); - } - } - } - if (signers != null && signers.length != 0) { - oos.writeObject(signers); - } - } + public final Certificate[] getCertificates() { return null; } - private void readObject(ObjectInputStream ois) throws IOException, - ClassNotFoundException { + public final CodeSigner[] getCodeSigners() { return null; } - ois.defaultReadObject(); + public final URL getLocation() { return null; } - int certsCount = ois.readInt(); - certs = null; - if (certsCount != 0) { - certs = new Certificate[certsCount]; - for (int i = 0; i < certsCount; i++) { - String type = ois.readUTF(); - CertificateFactory factory; - try { - factory = CertificateFactory.getInstance(type); - } catch (CertificateException ex) { - throw new ClassNotFoundException("Could not find CertificateFactory of type " + - type, ex); - } - int dataLen = ois.readInt(); - byte[] data = new byte[dataLen]; - ois.readFully(data); - ByteArrayInputStream bais = new ByteArrayInputStream(data); - try { - certs[i] = factory.generateCertificate(bais); - } catch (CertificateException ex) { - throw (IOException) new IOException("Could not generate certificate").initCause(ex); - } - } - } - try { - signers = (CodeSigner[]) ois.readObject(); - } catch (OptionalDataException ex) { - if (!ex.eof) { - throw ex; - } - // no signers (ex.eof==true <= no data left) is allowed - } - } + public boolean implies(CodeSource cs) { return true; } } diff --git a/luni/src/main/java/java/security/DomainCombiner.java b/luni/src/main/java/java/security/DomainCombiner.java index 374f0eb..7b0e571 100644 --- a/luni/src/main/java/java/security/DomainCombiner.java +++ b/luni/src/main/java/java/security/DomainCombiner.java @@ -18,7 +18,7 @@ package java.security; /** - * Legacy security code; this class exists for compatibility only. + * Legacy security code; do not use. */ public interface DomainCombiner { diff --git a/luni/src/main/java/java/security/Permission.java b/luni/src/main/java/java/security/Permission.java index 044c01f..4b7ef84 100644 --- a/luni/src/main/java/java/security/Permission.java +++ b/luni/src/main/java/java/security/Permission.java @@ -20,123 +20,20 @@ package java.security; import java.io.Serializable; /** - * Legacy security code; this class exists for compatibility only. + * Legacy security code; do not use. */ public abstract class Permission implements Guard, Serializable { + public Permission(String name) { } - private static final long serialVersionUID = -5636570222231596674L; + public final String getName() { return null; } - private final String name; + public void checkGuard(Object obj) throws SecurityException { } - /** - * Compares the specified object with this {@code Permission} for equality - * and returns {@code true} if the specified object is equal, {@code false} - * otherwise. - * <p> - * The {@link #implies(Permission)} method should be used for making access - * control checks. - * - * @param obj - * object to be compared for equality with this {@code - * Permission}. - * @return {@code true} if the specified object is equal to this {@code - * Permission}, otherwise {@code false}. - */ - @Override - public abstract boolean equals(Object obj); - - /** - * Returns the hash code value for this {@code Permission}. Returns the same - * hash code for {@code Permission}s that are equal to each other as - * required by the general contract of {@link Object#hashCode}. - * - * @return the hash code value for this {@code Permission}. - * @see Object#equals(Object) - * @see Permission#equals(Object) - */ - @Override - public abstract int hashCode(); + public PermissionCollection newPermissionCollection() { + return new AllPermissionCollection(); + } - /** - * Returns a comma separated string identifying the actions associated with - * this permission. The returned actions are in canonical form. For example: - * - * <pre> - * sp0 = new SocketPermission("www.example.com", "connect,resolve") - * sp1 = new SocketPermission("www.example.com", "resolve,connect") - * sp0.getActions().equals(sp1.getActions()) //yields true - * </pre> - * - * Both permissions return "connect,resolve" (in that order) if {@code - * #getActions()} is invoked. Returns an empty String, if no actions are - * associated with this permission. - * - * @return the actions associated with this permission or an empty string if - * no actions are associated with this permission. - */ public abstract String getActions(); - /** - * Indicates whether the specified permission is implied by this permission. - * - * @param permission - * the permission to check against this permission. - * @return {@code true} if the specified permission is implied by this - * permission, {@code false} otherwise. - */ public abstract boolean implies(Permission permission); - - /** - * Constructs a new instance of {@code Permission} with its name. - * - * @param name - * the name of the permission. - */ - public Permission(String name) { - this.name = name; - } - - /** - * Returns the name of this permission. - * - * @return the name of this permission. - */ - public final String getName() { - return name; - } - - /** - * Does nothing. - */ - public void checkGuard(Object obj) throws SecurityException { - } - - /** - * Returns a specific {@link PermissionCollection} container for permissions - * of this type. Returns {@code null} if any permission collection can be - * used. - * <p> - * Subclasses may override this method to return an appropriate collection - * for the specific permissions they implement. - * - * @return an empty {@link PermissionCollection} or {@code null} if any - * permission collection can be used. - */ - public PermissionCollection newPermissionCollection() { - return null; - } - - /** - * Returns a string containing a concise, human-readable description of the - * this {@code Permission} including its name and its actions. - * - * @return a printable representation for this {@code Permission}. - */ - @Override - public String toString() { - String actions = getActions(); - actions = (actions == null || actions.length() == 0) ? "" : " " - + getActions(); - return "(" + getClass().getName() + " " + getName() + actions + ")"; - } } diff --git a/luni/src/main/java/java/security/PermissionCollection.java b/luni/src/main/java/java/security/PermissionCollection.java index 4677034..557eeec 100644 --- a/luni/src/main/java/java/security/PermissionCollection.java +++ b/luni/src/main/java/java/security/PermissionCollection.java @@ -23,98 +23,17 @@ import java.util.Enumeration; import java.util.List; /** - * {@code PermissionCollection} is the common base class for all collections - * that provide a convenient method for determining whether or not a given - * permission is implied by any of the permissions present in this collection. - * <p> - * A {@code PermissionCollection} is typically created by using the - * {@link Permission#newPermissionCollection()} factory method. If the mentioned - * method returns {@code null}, then a {@code PermissionCollection} of any type - * can be used. If a collection is returned, it must be used for holding several - * permissions of the particular type. - * <p> - * Subclasses must be implemented thread save. + * Legacy security code; do not use. */ public abstract class PermissionCollection implements Serializable { - private static final long serialVersionUID = -6727011328946861783L; - - private boolean readOnly; // = false; - - /** - * Adds the specified {@code Permission} to this collection. - * - * @param permission - * the {@code Permission} to add. - * @throws IllegalStateException - * if the collection is read only. - */ public abstract void add(Permission permission); - /** - * Returns an enumeration over all {@link Permission}s encapsulated by this - * {@code PermissionCollection}. - * - * @return an enumeration over all {@link Permission}s. - */ public abstract Enumeration<Permission> elements(); - /** - * Indicates whether the specified permission is implied by this {@code - * PermissionCollection}. - * - * @param permission - * the permission to check. - * @return {@code true} if the given permission is implied by the - * permissions in this collection, {@code false} otherwise. - */ public abstract boolean implies(Permission permission); - /** - * Indicates whether new permissions can be added to this {@code - * PermissionCollection}. - * - * @return {@code true} if the receiver is read only, {@code false} if new - * elements can still be added to this {@code PermissionCollection}. - */ - public boolean isReadOnly() { - return readOnly; - } - - /** - * Marks this {@code PermissionCollection} as read only, so that no new - * permissions can be added to it. - */ - public void setReadOnly() { - readOnly = true; - } + public boolean isReadOnly() { return true; } - /** - * Returns a string containing a concise, human-readable description of this - * {@code PermissionCollection}. - * - * @return a printable representation for this {@code PermissionCollection}. - */ - @Override - public String toString() { - List<String> elist = new ArrayList<String>(100); - Enumeration<Permission> elenum = elements(); - String superStr = super.toString(); - int totalLength = superStr.length() + 5; - if (elenum != null) { - while (elenum.hasMoreElements()) { - String el = elenum.nextElement().toString(); - totalLength += el.length(); - elist.add(el); - } - } - int esize = elist.size(); - totalLength += esize * 4; - StringBuilder result = new StringBuilder(totalLength).append(superStr) - .append(" ("); - for (int i = 0; i < esize; i++) { - result.append("\n ").append(elist.get(i).toString()); - } - return result.append("\n)\n").toString(); - } + public void setReadOnly() { } } diff --git a/luni/src/main/java/java/security/Permissions.java b/luni/src/main/java/java/security/Permissions.java index 88a3414..6122aab 100644 --- a/luni/src/main/java/java/security/Permissions.java +++ b/luni/src/main/java/java/security/Permissions.java @@ -17,227 +17,16 @@ package java.security; -import java.io.IOException; -import java.io.InvalidObjectException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.ObjectStreamField; import java.io.Serializable; import java.util.Enumeration; -import java.util.HashMap; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.Map; -import java.util.NoSuchElementException; /** - * {@code Permissions} represents a {@code PermissionCollection} where the - * contained permissions can be of different types. The permissions are - * organized in their appropriate {@code PermissionCollection} obtained by - * {@link Permission#newPermissionCollection()}. For permissions which do not - * provide a dedicated {@code PermissionCollection}, a default permission - * collection, based on a hash table, will be used. + * Legacy security code; do not use. */ -public final class Permissions extends PermissionCollection implements - Serializable { +public final class Permissions extends PermissionCollection implements Serializable { + public void add(Permission permission) {} - private static final long serialVersionUID = 4858622370623524688L; + public Enumeration<Permission> elements() { return null; } - private static final ObjectStreamField[] serialPersistentFields = { - new ObjectStreamField("perms", Hashtable.class), - new ObjectStreamField("allPermission", PermissionCollection.class), - }; - - // Hash to store PermissionCollection's - private transient Map klasses = new HashMap(); - - private boolean allEnabled; // = false; - - /** - * Adds the given {@code Permission} to this heterogeneous {@code - * PermissionCollection}. The {@code permission} is stored in its - * appropriate {@code PermissionCollection}. - * - * @param permission - * the {@code Permission} to be added. - * @throws SecurityException - * if this collection's {@link #isReadOnly()} method returns - * {@code true}. - * @throws NullPointerException - * if {@code permission} is {@code null}. - */ - public void add(Permission permission) { - if (isReadOnly()) { - throw new SecurityException("collection is read-only"); - } - - if (permission == null) { - throw new NullPointerException("permission == null"); - } - - Class klass = permission.getClass(); - PermissionCollection klassMates = (PermissionCollection)klasses - .get(klass); - - if (klassMates == null) { - synchronized (klasses) { - klassMates = (PermissionCollection)klasses.get(klass); - if (klassMates == null) { - - klassMates = permission.newPermissionCollection(); - if (klassMates == null) { - klassMates = new PermissionsHash(); - } - klasses.put(klass, klassMates); - } - } - } - klassMates.add(permission); - - if (klass == AllPermission.class) { - allEnabled = true; - } - } - - public Enumeration<Permission> elements() { - return new MetaEnumeration(klasses.values().iterator()); - } - - /** - * An auxiliary implementation for enumerating individual permissions from a - * collection of PermissionCollections. - * - */ - static final class MetaEnumeration implements Enumeration { - - private Iterator pcIter; - - private Enumeration current; - - /** - * Initiates this enumeration. - * - * @param outer an iterator over external collection of - * PermissionCollections - */ - public MetaEnumeration(Iterator outer) { - pcIter = outer; - current = getNextEnumeration(); - } - - private Enumeration getNextEnumeration() { - while (pcIter.hasNext()) { - Enumeration en = ((PermissionCollection)pcIter.next()) - .elements(); - if (en.hasMoreElements()) { - return en; - } - } - return null; - } - - /** - * Indicates if there are more elements to enumerate. - */ - public boolean hasMoreElements() { - return current != null /* && current.hasMoreElements() */; - } - - /** - * Returns next element. - */ - public Object nextElement() { - if (current != null) { - //assert current.hasMoreElements(); - Object next = current.nextElement(); - if (!current.hasMoreElements()) { - current = getNextEnumeration(); - } - - return next; - } - throw new NoSuchElementException(); - } - } - - public boolean implies(Permission permission) { - if (permission == null) { - // RI compatible - throw new NullPointerException("permission == null"); - } - if (allEnabled) { - return true; - } - Class klass = permission.getClass(); - PermissionCollection klassMates = null; - - UnresolvedPermissionCollection billets = (UnresolvedPermissionCollection)klasses - .get(UnresolvedPermission.class); - if (billets != null && billets.hasUnresolved(permission)) { - // try to fill up klassMates with freshly resolved permissions - synchronized (klasses) { - klassMates = (PermissionCollection)klasses.get(klass); - try { - klassMates = billets.resolveCollection(permission, - klassMates); - } catch (Exception ignore) { - //TODO log warning - ignore.printStackTrace(); - } - - if (klassMates != null) { - //maybe klassMates were just created - // so put them into common map - klasses.put(klass, klassMates); - // very uncommon case, but not improbable one - if (klass == AllPermission.class) { - allEnabled = true; - } - } - } - } else { - klassMates = (PermissionCollection)klasses.get(klass); - } - - if (klassMates != null) { - return klassMates.implies(permission); - } - return false; - } - - /** - * Reads the object from stream and checks for consistency. - */ - private void readObject(java.io.ObjectInputStream in) throws IOException, - ClassNotFoundException { - ObjectInputStream.GetField fields = in.readFields(); - Map perms = (Map)fields.get("perms", null); - klasses = new HashMap(); - synchronized (klasses) { - for (Iterator iter = perms.entrySet().iterator(); iter.hasNext();) { - Map.Entry entry = (Map.Entry) iter.next(); - Class key = (Class) entry.getKey(); - PermissionCollection pc = (PermissionCollection) entry.getValue(); - if (key != pc.elements().nextElement().getClass()) { - throw new InvalidObjectException("collection is corrupted"); - } - klasses.put(key, pc); - } - } - allEnabled = fields.get("allPermission", null) != null; - if (allEnabled && !klasses.containsKey(AllPermission.class)) { - throw new InvalidObjectException("all-enabled flag is corrupted"); - } - } - - /** - * Outputs fields via default mechanism. - */ - private void writeObject(java.io.ObjectOutputStream out) throws IOException { - ObjectOutputStream.PutField fields = out.putFields(); - fields.put("perms", new Hashtable(klasses)); - fields.put("allPermission", allEnabled ? klasses - .get(AllPermission.class) : null); - out.writeFields(); - } + public boolean implies(Permission permission) { return true; } } diff --git a/luni/src/main/java/java/security/Policy.java b/luni/src/main/java/java/security/Policy.java index f89861e..1c58937 100644 --- a/luni/src/main/java/java/security/Policy.java +++ b/luni/src/main/java/java/security/Policy.java @@ -18,467 +18,41 @@ package java.security; import java.util.Enumeration; -import org.apache.harmony.security.fortress.DefaultPolicy; -import org.apache.harmony.security.fortress.Engine; -import org.apache.harmony.security.fortress.PolicyUtils; - /** - * {@code Policy} is the common super type of classes which represent a system - * security policy. The {@code Policy} specifies which permissions apply to - * which code sources. - * <p> - * The system policy can be changed by setting the {@code 'policy.provider'} - * property in the file named {@code JAVA_HOME/lib/security/java.security} to - * the fully qualified class name of the desired {@code Policy}. - * <p> - * Only one instance of a {@code Policy} is active at any time. + * Legacy security code; do not use. */ public abstract class Policy { - - // Key to security properties, defining default policy provider. - private static final String POLICY_PROVIDER = "policy.provider"; - - // The SecurityPermission required to set custom Policy. - private static final SecurityPermission SET_POLICY = new SecurityPermission( - "setPolicy"); - - // The SecurityPermission required to get current Policy. - private static final SecurityPermission GET_POLICY = new SecurityPermission("getPolicy"); - - // The policy currently in effect. - // protected by Policy.class monitor. - private static Policy activePolicy; - - // Store spi implementation service name - private static final String POLICYSERVICE = "Policy"; - - // Used to access common engine functionality - private static final Engine ENGINE = new Engine(POLICYSERVICE); - - private final String type; - - private final Policy.Parameters params; - - private final Provider provider; - - // Store used spi implementation - private final PolicySpi spiImpl; - - private static final String CREATE_POLICY = "createPolicy."; - - public Policy() { - this(null, null, null, null); - } - - private Policy(PolicySpi spi, Provider p, String t, Policy.Parameters para) { - this.spiImpl = spi; - this.provider = p; - this.type = t; - this.params = para; - } - - private static class PolicyDelegate extends Policy { - - public PolicyDelegate(PolicySpi spi, Provider p, String t, - Policy.Parameters para) { - super(spi, p, t, para); - } - } - - /** - * Answers a Policy object with the specified type and the specified - * parameter. - * - * Traverses the list of registered security providers, beginning with the - * most preferred Provider. A new Policy object encapsulating the PolicySpi - * implementation from the first Provider that supports the specified type - * is returned. - * - * Note that the list of registered providers may be retrieved via the - * Security.getProviders() method. - * - * @param type - * the specified Policy type. See Appendix A in the Java - * Cryptography Architecture API Specification & Reference for a - * list of standard Policy types. - * @param params - * parameters for the Policy, which may be null. - * @return the new Policy object. - * @throws NoSuchAlgorithmException - * if no Provider supports a PolicySpi implementation for the - * specified type. - * @throws NullPointerException - * if the specified type is null. - * @throws IllegalArgumentException - * if the specified parameters' type are not allowed by the - * PolicySpi implementation from the selected Provider. - */ - public static Policy getInstance(String type, Policy.Parameters params) - throws NoSuchAlgorithmException { - if (type == null) { - throw new NullPointerException(); - } - - try { - Engine.SpiAndProvider sap = ENGINE.getInstance(type, params); - return new PolicyDelegate((PolicySpi) sap.spi, sap.provider, type, params); - } catch (NoSuchAlgorithmException e) { - if (e.getCause() == null) { - throw e; - } - throw new IllegalArgumentException("Unrecognized policy parameter: " + params, e); - } - } - - /** - * Answers a Policy object of the specified type. - * - * A new Policy object encapsulating the PolicySpi implementation from the - * specified provider is returned. The specified provider must be registered - * in the provider list via the Security.getProviders() method, otherwise - * NoSuchProviderException will be thrown. - * - * @param type - * the specified Policy type. So far in Java 6, only 'JavaPolicy' - * supported. - * @param params - * the Policy.Parameter object, which may be null. - * @param provider - * the provider. - * @return the new Policy object. - * - * @throws NoSuchProviderException - * if the specified provider is not registered in the security - * provider list. - * @throws NoSuchAlgorithmException - * if the specified provider does not support a PolicySpi - * implementation for the specified type. - * @throws NullPointerException - * if the specified type is null. - * @throws IllegalArgumentException - * if the specified Provider is null, or if the specified - * parameters' type are not allowed by the PolicySpi - * implementation from the specified Provider. - */ - public static Policy getInstance(String type, Policy.Parameters params, - String provider) throws NoSuchProviderException, - NoSuchAlgorithmException { - if ((provider == null) || provider.isEmpty()) { - throw new IllegalArgumentException("Provider is null or empty string"); - } - - Provider impProvider = Security.getProvider(provider); - if (impProvider == null) { - throw new NoSuchProviderException("Provider " + provider + " is not available"); - } - - return getInstanceImpl(type, params, impProvider); - } - - /** - * Answers a Policy object of the specified type. - * - * A new Policy object encapsulating the PolicySpi implementation from the - * specified Provider object is returned. Note that the specified Provider - * object does not have to be registered in the provider list. - * - * @param type - * the specified Policy type. So far in Java 6, only 'JavaPolicy' - * supported. - * @param params - * the Policy.Parameter object, which may be null. - * @param provider - * the Policy service Provider. - * @return the new Policy object. - * - * @throws NoSuchAlgorithmException - * if the specified Provider does not support a PolicySpi - * implementation for the specified type. - * @throws IllegalArgumentException - * if the specified Provider is null, or if the specified - * parameters' type are not allowed by the PolicySpi - * implementation from the specified Provider. - * @throws NullPointerException - * if the specified type is null. - */ - public static Policy getInstance(String type, Policy.Parameters params, - Provider provider) throws NoSuchAlgorithmException { - if (provider == null) { - throw new IllegalArgumentException("provider == null"); - } - return getInstanceImpl(type, params, provider); - } - - private static Policy getInstanceImpl(String type, Policy.Parameters params, Provider provider) - throws NoSuchAlgorithmException { - if (type == null) { - throw new NullPointerException(); - } - - try { - Object spi = ENGINE.getInstance(type, provider, params); - return new PolicyDelegate((PolicySpi) spi, provider, type, params); - } catch (NoSuchAlgorithmException e) { - if (e.getCause() == null) { - throw e; - } - throw new IllegalArgumentException("Unrecognized policy parameter: " + params, e); - } - } - /** - * Answers Policy parameters. - * - * This method will only answer non-null parameters if it was obtained via a - * call to Policy.getInstance. Otherwise this method returns null. - * - * @return Policy parameters, or null. + * Legacy security code; do not use. */ - public Policy.Parameters getParameters() { - return params; - } + public static interface Parameters { } - /** - * Answers the Provider of this Policy. - * - * This method will only answer non-null Provider if it was obtained via a - * call to Policy.getInstance. Otherwise this method returns null. - * - * @return the Provider of this Policy, or null. - */ - public Provider getProvider() { - return provider; - } + public Policy() { } - /** - * Answers the type of this Policy. - * - * This method will only answer non-null type if it was obtained via a call - * to Policy.getInstance. Otherwise this method returns null. - * - * @return the type of this Policy, or null. - */ - public String getType() { - return type; - } + public static Policy getInstance(String type, Policy.Parameters params) throws NoSuchAlgorithmException { return null; } - /** - * A read-only empty PermissionCollection instance. - */ - public static final PermissionCollection UNSUPPORTED_EMPTY_COLLECTION = new PermissionCollection() { + public static Policy getInstance(String type, Policy.Parameters params, String provider) throws NoSuchProviderException, NoSuchAlgorithmException { return null; } - private static final long serialVersionUID = 1L; + public static Policy getInstance(String type, Policy.Parameters params, Provider provider) throws NoSuchAlgorithmException { return null; } - @Override - public void add(Permission permission) { - throw new SecurityException( - "attempt to add a Permission to a readonly Permissions object"); - } + public Policy.Parameters getParameters() { return null; } - @Override - public Enumeration<Permission> elements() { - return new Permissions().elements(); - } + public Provider getProvider() { return null; } - @Override - public boolean implies(Permission permission) { - if (permission == null) { - throw new NullPointerException(); - } - return false; - } + public String getType() { return null; } - @Override - public boolean isReadOnly() { - // always returns true since it is a read-only instance. - // RI does not override this method. - return true; - } - }; + public static final PermissionCollection UNSUPPORTED_EMPTY_COLLECTION = new AllPermissionCollection(); - /** - * A marker interface for Policy parameters. - */ - public static interface Parameters { - // a marker interface - } + public PermissionCollection getPermissions(CodeSource cs) { return null; } - /** - * Returns a {@code PermissionCollection} describing what permissions are - * allowed for the specified {@code CodeSource} based on the current - * security policy. - * <p> - * Note that this method is not called for classes which are in the system - * domain (i.e. system classes). System classes are always given - * full permissions (i.e. AllPermission). This can not be changed by - * installing a new policy. - * - * @param cs - * the {@code CodeSource} to compute the permissions for. - * @return the permissions that are granted to the specified {@code - * CodeSource}. - */ - public PermissionCollection getPermissions(CodeSource cs) { - return spiImpl == null ? Policy.UNSUPPORTED_EMPTY_COLLECTION : spiImpl - .engineGetPermissions(cs); - } + public void refresh() { } - /** - * Reloads the policy configuration for this {@code Policy} instance. - */ - public void refresh() { - if (spiImpl != null) { - spiImpl.engineRefresh(); - } - } + public PermissionCollection getPermissions(ProtectionDomain domain) { return null; } - /** - * Returns a {@code PermissionCollection} describing what permissions are - * allowed for the specified {@code ProtectionDomain} (more specifically, - * its {@code CodeSource}) based on the current security policy. - * <p> - * Note that this method is not< called for classes which are in the - * system domain (i.e. system classes). System classes are always - * given full permissions (i.e. AllPermission). This can not be changed by - * installing a new policy. - * - * @param domain - * the {@code ProtectionDomain} to compute the permissions for. - * @return the permissions that are granted to the specified {@code - * CodeSource}. - */ - public PermissionCollection getPermissions(ProtectionDomain domain) { - Permissions permissions = new Permissions(); - if (domain != null) { - try { - PermissionCollection cds = getPermissions(domain - .getCodeSource()); - if (cds != Policy.UNSUPPORTED_EMPTY_COLLECTION) { - Enumeration<Permission> elements = cds.elements(); - while (elements.hasMoreElements()) { - permissions.add(elements.nextElement()); - } - } - } catch (NullPointerException e) { - // ignore the exception, just add nothing to the result set - } + public boolean implies(ProtectionDomain domain, Permission permission) { return true; } - PermissionCollection pds = domain.getPermissions(); - if (pds != null) { - Enumeration<Permission> pdElements = pds.elements(); - while (pdElements.hasMoreElements()) { - permissions.add(pdElements.nextElement()); - } - } - } - return permissions; - } + public static Policy getPolicy() { return null; } - /** - * Indicates whether the specified {@code Permission} is implied by the - * {@code PermissionCollection} of the specified {@code ProtectionDomain}. - * - * @param domain - * the {@code ProtectionDomain} for which the permission should - * be granted. - * @param permission - * the {@code Permission} for which authorization is to be - * verified. - * @return {@code true} if the {@code Permission} is implied by the {@code - * ProtectionDomain}, {@code false} otherwise. - */ - public boolean implies(ProtectionDomain domain, Permission permission) { - return spiImpl == null ? defaultImplies(domain, permission) : spiImpl - .engineImplies(domain, permission); - } - - private boolean defaultImplies(ProtectionDomain domain, Permission permission) { - if (domain == null && permission == null) { - throw new NullPointerException(); - } - boolean implies = false; - if (domain != null) { - PermissionCollection total = getPermissions(domain); - PermissionCollection inherent = domain.getPermissions(); - if (inherent != null) { - Enumeration<Permission> en = inherent.elements(); - while (en.hasMoreElements()) { - total.add(en.nextElement()); - } - } - try { - implies = total.implies(permission); - } catch (NullPointerException e) { - // return false instead of throwing the NullPointerException - implies = false; - } - } - return implies; - } - - /** - * Returns the current system security policy. If no policy has been - * instantiated then this is done using the security property {@code - * "policy.provider"}. - * - * @return the current system security policy. - */ - public static Policy getPolicy() { - return getAccessiblePolicy(); - } - - // Reads name of default policy provider from security.properties, - // loads the class and instantiates the provider.<br> - // In case of any error, including undefined provider name, - // returns new instance of org.apache.harmony.security.FilePolicy provider. - private static Policy getDefaultProvider() { - final String defaultClass = Security.getProperty(POLICY_PROVIDER); - if (defaultClass == null) { - return new DefaultPolicy(); - } - - // TODO accurate classloading - try { - return (Policy) Class.forName(defaultClass, true, - ClassLoader.getSystemClassLoader()).newInstance(); - } catch (Exception e) { - return new DefaultPolicy(); - } - } - - /** - * Returns {@code true} if system policy provider is instantiated. - */ - static boolean isSet() { - synchronized (Policy.class) { - return activePolicy != null; - } - } - - /** - * Shortcut accessor for friendly classes, to skip security checks. - * If active policy was set to <code>null</code>, loads default provider, - * so this method never returns <code>null</code>. <br> - * This method is synchronized with setPolicy() - */ - static Policy getAccessiblePolicy() { - synchronized (Policy.class) { - if (activePolicy == null) { - activePolicy = getDefaultProvider(); - } - return activePolicy; - } - } - - /** - * Sets the system wide policy. - * @param policy - * the {@code Policy} to set. - */ - public static void setPolicy(Policy policy) { - synchronized (Policy.class) { - activePolicy = policy; - } - } + public static void setPolicy(Policy policy) { } } diff --git a/luni/src/main/java/java/security/PrivilegedAction.java b/luni/src/main/java/java/security/PrivilegedAction.java index d635f58..cf6712e 100644 --- a/luni/src/main/java/java/security/PrivilegedAction.java +++ b/luni/src/main/java/java/security/PrivilegedAction.java @@ -18,11 +18,8 @@ package java.security; /** - * Legacy security code; this class exists for compatibility only. + * Legacy security code; do not use. */ public interface PrivilegedAction<T> { - /** - * Returns the result of running the action. - */ public T run(); } diff --git a/luni/src/main/java/java/security/PrivilegedActionException.java b/luni/src/main/java/java/security/PrivilegedActionException.java index e470ebf..d44479b 100644 --- a/luni/src/main/java/java/security/PrivilegedActionException.java +++ b/luni/src/main/java/java/security/PrivilegedActionException.java @@ -18,61 +18,17 @@ package java.security; /** - * Legacy security code; this class exists for compatibility only. + * Legacy security code; do not use. */ public class PrivilegedActionException extends Exception { private static final long serialVersionUID = 4724086851538908602l; - private Exception exception; - - /** - * Constructs a new instance of {@code PrivilegedActionException} with the - * cause. - * - * @param ex - * the exception which is the cause for this exception. - */ public PrivilegedActionException(Exception ex) { super(ex); - this.exception = ex; } - /** - * Returns the exception that was thrown by a - * {@code PrivilegedExceptionAction}. - * - * @return the exception that was thrown by a - * {@code PrivilegedExceptionAction}. - */ public Exception getException() { - return exception; // return ( getCause() instanceof Exception ) ? - // getCause() : null; - } - - /** - * Returns the exception that was thrown by a - * {@code PrivilegedExceptionAction}. - * - * @return the exception that was thrown by a - * {@code PrivilegedExceptionAction}. - */ - @Override - public Throwable getCause() { - return exception; + return null; } - - /** - * Returns a string containing a concise, human-readable description of this - * {@code PrivilegedActionException}. - * - * @return a printable representation for this {@code - * PrivilegedActionException}. - */ - @Override - public String toString() { - String s = getClass().getName(); - return exception == null ? s : s + ": " + exception; - } - } diff --git a/luni/src/main/java/java/security/PrivilegedExceptionAction.java b/luni/src/main/java/java/security/PrivilegedExceptionAction.java index a9496ad..f24efac 100644 --- a/luni/src/main/java/java/security/PrivilegedExceptionAction.java +++ b/luni/src/main/java/java/security/PrivilegedExceptionAction.java @@ -18,11 +18,8 @@ package java.security; /** - * Legacy security code; this class exists for compatibility only. + * Legacy security code; do not use. */ public interface PrivilegedExceptionAction<T> { - /** - * Returns the result of running the action. - */ T run() throws Exception; } diff --git a/luni/src/main/java/java/security/ProtectionDomain.java b/luni/src/main/java/java/security/ProtectionDomain.java index 3b4449d..d7b4cf1 100644 --- a/luni/src/main/java/java/security/ProtectionDomain.java +++ b/luni/src/main/java/java/security/ProtectionDomain.java @@ -18,244 +18,20 @@ package java.security; /** - * {@code ProtectionDomain} represents all permissions that are granted to a - * specific code source. The {@link ClassLoader} associates each class with the - * corresponding {@code ProtectionDomain}, depending on the location and the - * certificates (encapsulates in {@link CodeSource}) it loads the code from. - * <p> - * A class belongs to exactly one protection domain and the protection domain - * can not be changed during the lifetime of the class. + * Legacy security code; do not use. */ public class ProtectionDomain { + public ProtectionDomain(CodeSource cs, PermissionCollection permissions) { } - // CodeSource for this ProtectionDomain - private CodeSource codeSource; + public ProtectionDomain(CodeSource cs, PermissionCollection permissions, ClassLoader cl, Principal[] principals) { } - // Static permissions for this ProtectionDomain - private PermissionCollection permissions; + public final ClassLoader getClassLoader() { return null; } - // ClassLoader - private ClassLoader classLoader; + public final CodeSource getCodeSource() { return null; } - // Set of principals associated with this ProtectionDomain - private Principal[] principals; + public final PermissionCollection getPermissions() { return null; } - // false if this ProtectionDomain was constructed with static - // permissions, true otherwise. - private boolean dynamicPerms; + public final Principal[] getPrincipals() { return null; } - /** - * Constructs a new instance of {@code ProtectionDomain} with the specified - * code source and the specified static permissions. - * <p> - * If {@code permissions} is not {@code null}, the {@code permissions} - * collection is made immutable by calling - * {@link PermissionCollection#setReadOnly()} and it is considered as - * granted statically to this {@code ProtectionDomain}. - * <p> - * The policy will not be consulted by access checks against this {@code - * ProtectionDomain}. - * <p> - * If {@code permissions} is {@code null}, the method {@link - * ProtectionDomain#implies(Permission)} always returns {@code false}. - * - * @param cs - * the code source associated with this domain, maybe {@code - * null}. - * @param permissions - * the {@code PermissionCollection} containing all permissions to - * be statically granted to this {@code ProtectionDomain}, maybe - * {@code null}. - */ - public ProtectionDomain(CodeSource cs, PermissionCollection permissions) { - this.codeSource = cs; - if (permissions != null) { - permissions.setReadOnly(); - } - this.permissions = permissions; - //this.classLoader = null; - //this.principals = null; - //dynamicPerms = false; - } - - /** - * Constructs a new instance of {@code ProtectionDomain} with the specified - * code source, the permissions, the class loader and the principals. - * <p> - * If {@code permissions} is {@code null}, and access checks are performed - * against this protection domain, the permissions defined by the policy are - * consulted. If {@code permissions} is not {@code null}, the {@code - * permissions} collection is made immutable by calling - * {@link PermissionCollection#setReadOnly()}. If access checks are - * performed, the policy and the provided permission collection are checked. - * <p> - * External modifications of the provided {@code principals} array has no - * impact on this {@code ProtectionDomain}. - * - * @param cs - * the code source associated with this domain, maybe {@code - * null}. - * @param permissions - * the permissions associated with this domain, maybe {@code - * null}. - * @param cl - * the class loader associated with this domain, maybe {@code - * null}. - * @param principals - * the principals associated with this domain, maybe {@code - * null}. - */ - public ProtectionDomain(CodeSource cs, PermissionCollection permissions, - ClassLoader cl, Principal[] principals) { - this.codeSource = cs; - if (permissions != null) { - permissions.setReadOnly(); - } - this.permissions = permissions; - this.classLoader = cl; - if (principals != null) { - this.principals = new Principal[principals.length]; - System.arraycopy(principals, 0, this.principals, 0, - this.principals.length); - } - dynamicPerms = true; - } - - /** - * Returns the {@code ClassLoader} associated with this {@code - * ProtectionDomain}. - * - * @return the {@code ClassLoader} associated with this {@code - * ProtectionDomain}, maybe {@code null}. - */ - public final ClassLoader getClassLoader() { - return classLoader; - } - - /** - * Returns the {@code CodeSource} of this {@code ProtectionDomain}. - * - * @return the {@code CodeSource} of this {@code ProtectionDomain}, maybe - * {@code null}. - */ - public final CodeSource getCodeSource() { - return codeSource; - } - - /** - * Returns the static permissions that are granted to this {@code - * ProtectionDomain}. - * - * @return the static permissions that are granted to this {@code - * ProtectionDomain}, maybe {@code null}. - */ - public final PermissionCollection getPermissions() { - return permissions; - } - - /** - * Returns the principals associated with this {@code ProtectionDomain}. - * Modifications of the returned {@code Principal} array has no impact on - * this {@code ProtectionDomain}. - * - * @return the principals associated with this {@code ProtectionDomain}. - */ - public final Principal[] getPrincipals() { - if( principals == null ) { - return new Principal[0]; - } - Principal[] tmp = new Principal[principals.length]; - System.arraycopy(principals, 0, tmp, 0, tmp.length); - return tmp; - } - - /** - * Indicates whether the specified permission is implied by this {@code - * ProtectionDomain}. - * <p> - * If this {@code ProtectionDomain} was constructed with - * {@link #ProtectionDomain(CodeSource, PermissionCollection)}, the - * specified permission is only checked against the permission collection - * provided in the constructor. If {@code null} was provided, {@code false} - * is returned. - * <p> - * If this {@code ProtectionDomain} was constructed with - * {@link #ProtectionDomain(CodeSource, PermissionCollection, ClassLoader, Principal[])} - * , the specified permission is checked against the policy and the - * permission collection provided in the constructor. - * - * @param permission - * the permission to check against the domain. - * @return {@code true} if the specified {@code permission} is implied by - * this {@code ProtectionDomain}, {@code false} otherwise. - */ - public boolean implies(Permission permission) { - // First, test with the Policy, as the default Policy.implies() - // checks for both dynamic and static collections of the - // ProtectionDomain passed... - if (dynamicPerms - && Policy.getAccessiblePolicy().implies(this, permission)) { - return true; - } - - // ... and we get here if - // either the permissions are static - // or Policy.implies() did not check for static permissions - // or the permission is not implied - return permissions == null ? false : permissions.implies(permission); - } - - /** - * Returns a string containing a concise, human-readable description of the - * this {@code ProtectionDomain}. - * - * @return a printable representation for this {@code ProtectionDomain}. - */ - @Override - public String toString() { - StringBuilder buf = new StringBuilder(200); - buf.append("ProtectionDomain\n"); - buf.append("CodeSource=").append( - codeSource == null ? "<null>" : codeSource.toString()).append( - "\n"); - buf.append("ClassLoader=").append( - classLoader == null ? "<null>" : classLoader.toString()) - .append("\n"); - if (principals == null || principals.length == 0) { - buf.append("<no principals>\n"); - } else { - buf.append("Principals: <\n"); - for (int i = 0; i < principals.length; i++) { - buf.append("\t").append( - principals[i] == null ? "<null>" : principals[i] - .toString()).append("\n"); - } - buf.append(">"); - } - - //permissions here - buf.append("Permissions:\n"); - if (permissions == null) { - buf.append("\t\t<no static permissions>\n"); - } else { - buf.append("\t\tstatic: ").append(permissions.toString()).append( - "\n"); - } - - if (dynamicPerms) { - if (Policy.isSet()) { - PermissionCollection perms; - perms = Policy.getAccessiblePolicy().getPermissions(this); - if (perms == null) { - buf.append("\t\t<no dynamic permissions>\n"); - } else { - buf.append("\t\tdynamic: ").append(perms.toString()) - .append("\n"); - } - } else { - buf.append("\t\t<no dynamic permissions>\n"); - } - } - return buf.toString(); - } + public boolean implies(Permission permission) { return true; } } diff --git a/luni/src/main/java/java/security/SecurityPermission.java b/luni/src/main/java/java/security/SecurityPermission.java index c2dfc56..98afcb2 100644 --- a/luni/src/main/java/java/security/SecurityPermission.java +++ b/luni/src/main/java/java/security/SecurityPermission.java @@ -18,34 +18,14 @@ package java.security; /** - * Legacy security code; this class exists for compatibility only. + * Legacy security code; do not use. */ public final class SecurityPermission extends BasicPermission { + public SecurityPermission(String name) { super(""); } - private static final long serialVersionUID = 5236109936224050470L; + public SecurityPermission(String name, String action) { super("", ""); } - /** - * Constructs a new instance of {@code SecurityPermission} with the given - * name. - * - * @param name - * the name of the permission. - */ - public SecurityPermission(String name) { - super(name); - } + @Override public String getActions() { return null; } - /** - * Constructs a new instance of {@code SecurityPermission} with the given - * {@code name} and {@code action} list. The action list is ignored - it is - * existing for compatibility reasons only. - * - * @param name - * the name of the permission. - * @param action - * ignored. - */ - public SecurityPermission(String name, String action) { - super(name, action); - } + @Override public boolean implies(Permission permission) { return true; } } diff --git a/luni/src/main/java/java/security/UnresolvedPermission.java b/luni/src/main/java/java/security/UnresolvedPermission.java index 2884421..30fc6df 100644 --- a/luni/src/main/java/java/security/UnresolvedPermission.java +++ b/luni/src/main/java/java/security/UnresolvedPermission.java @@ -17,393 +17,26 @@ package java.security; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.NotSerializableException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; import java.io.Serializable; import java.security.cert.Certificate; -import java.security.cert.CertificateEncodingException; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; -import org.apache.harmony.security.fortress.PolicyUtils; /** - * Legacy security code; this class exists for compatibility only. + * Legacy security code; do not use. */ -public final class UnresolvedPermission extends Permission - implements Serializable { - - private static final long serialVersionUID = -4821973115467008846L; - - private String type; - - private String name; - - private String actions; - - // The signer certificates - private transient Certificate[] targetCerts; - - // Cached hash value - private transient int hash; - - /** - * Constructs a new instance of {@code UnresolvedPermission}. The supplied - * parameters are used when this instance is resolved to the concrete - * {@code Permission}. - * - * @param type - * the fully qualified class name of the permission this class is - * resolved to. - * @param name - * the name of the permission this class is resolved to, maybe - * {@code null}. - * @param actions - * the actions of the permission this class is resolved to, maybe - * {@code null}. - * @param certs - * the certificates of the permission this class is resolved to, - * maybe {@code null}. - * @throws NullPointerException - * if type is {@code null}. - */ - public UnresolvedPermission(String type, String name, String actions, - Certificate[] certs) { - super(type); - checkType(type); - this.type = type; - this.name = name; - this.actions = actions; - if (certs != null) { - this.targetCerts = new Certificate[certs.length]; - System.arraycopy(certs, 0, targetCerts, 0, certs.length); - } - hash = 0; +public final class UnresolvedPermission extends Permission implements Serializable { + public UnresolvedPermission(String type, String name, String actions, Certificate[] certs) { + super(""); } - // Check type parameter - private final void checkType(String type) { - if (type == null) { - throw new NullPointerException("type == null"); - } + public String getUnresolvedName() { return null; } - // type is the class name of the Permission class. - // Empty string is inappropriate for class name. - // But this check is commented out for compatibility with RI. - // see JIRA issue HARMONY-733 - // if (type.length() == 0) { - // throw new IllegalArgumentException("type cannot be empty"); - // } - } - - /** - * Compares the specified object with this {@code UnresolvedPermission} for - * equality and returns {@code true} if the specified object is equal, - * {@code false} otherwise. To be equal, the specified object needs to be an - * instance of {@code UnresolvedPermission}, the two {@code - * UnresolvedPermission}s must refer to the same type and must have the same - * name, the same actions and certificates. - * - * @param obj - * object to be compared for equality with this {@code - * UnresolvedPermission}. - * @return {@code true} if the specified object is equal to this {@code - * UnresolvedPermission}, otherwise {@code false}. - */ - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - if (obj instanceof UnresolvedPermission) { - UnresolvedPermission that = (UnresolvedPermission) obj; - if (getName().equals(that.getName()) - && (name == null ? that.name == null : name - .equals(that.name)) - && (actions == null ? that.actions == null : actions - .equals(that.actions)) - && equalsCertificates(this.targetCerts, that.targetCerts)) { - return true; - } - } - return false; - } + public String getUnresolvedActions() { return null; } - /* - * check whether given array of certificates are equivalent - */ - private boolean equalsCertificates(Certificate[] certs1, - Certificate[] certs2) { - if (certs1 == null || certs2 == null) { - return certs1 == certs2; - } + public String getUnresolvedType() { return null; } - int length = certs1.length; - if (length != certs2.length) { - return false; - } + public Certificate[] getUnresolvedCerts() { return null; } - if (length > 0) { - boolean found; - for (int i = 0; i < length; i++) { - // Skip the checking for null - if(certs1[i] == null){ - continue; - } - found = false; - for (int j = 0; j < length; j++) { - if (certs1[i].equals(certs2[j])) { - found = true; - break; - } - } + @Override public String getActions() { return null; } - if (!found) { - return false; - } - } - - for (int i = 0; i < length; i++) { - if(certs2[i] == null){ - continue; - } - found = false; - for (int j = 0; j < length; j++) { - if (certs2[i].equals(certs1[j])) { - found = true; - break; - } - } - - if (!found) { - return false; - } - } - } - return true; - } - - /** - * Returns the hash code value for this {@code UnresolvedPermission}. - * Returns the same hash code for {@code UnresolvedPermission}s that are - * equal to each other as required by the general contract of - * {@link Object#hashCode}. - * - * @return the hash code value for this {@code UnresolvedPermission}. - * @see Object#equals(Object) - * @see UnresolvedPermission#equals(Object) - */ - @Override - public int hashCode() { - if (hash == 0) { - hash = getName().hashCode(); - if (name != null) { - hash ^= name.hashCode(); - } - if (actions != null) { - hash ^= actions.hashCode(); - } - } - return hash; - } - - /** - * Returns an empty string since there are no actions allowed for {@code - * UnresolvedPermission}. The actions, specified in the constructor, are - * used when the concrete permission is resolved and created. - * - * @return an empty string, indicating that there are no actions. - */ - @Override - public String getActions() { - return ""; - } - - /** - * Returns the name of the permission this {@code UnresolvedPermission} is - * resolved to. - * - * @return the name of the permission this {@code UnresolvedPermission} is - * resolved to. - */ - public String getUnresolvedName() { - return name; - } - - /** - * Returns the actions of the permission this {@code UnresolvedPermission} - * is resolved to. - * - * @return the actions of the permission this {@code UnresolvedPermission} - * is resolved to. - */ - public String getUnresolvedActions() { - return actions; - } - - /** - * Returns the fully qualified class name of the permission this {@code - * UnresolvedPermission} is resolved to. - * - * @return the fully qualified class name of the permission this {@code - * UnresolvedPermission} is resolved to. - */ - public String getUnresolvedType() { - return super.getName(); - } - - /** - * Returns the certificates of the permission this {@code - * UnresolvedPermission} is resolved to. - * - * @return the certificates of the permission this {@code - * UnresolvedPermission} is resolved to. - */ - public Certificate[] getUnresolvedCerts() { - if (targetCerts != null) { - Certificate[] certs = new Certificate[targetCerts.length]; - System.arraycopy(targetCerts, 0, certs, 0, certs.length); - return certs; - } - return null; - } - - /** - * Indicates whether the specified permission is implied by this {@code - * UnresolvedPermission}. {@code UnresolvedPermission} objects imply nothing - * since nothing is known about them yet. - * <p> - * Before actual implication checking, this method tries to resolve - * UnresolvedPermissions (if any) against the passed instance. Successfully - * resolved permissions (if any) are taken into account during further - * processing. - * - * @param permission - * the permission to check. - * @return always {@code false} - */ - @Override - public boolean implies(Permission permission) { - return false; - } - - /** - * Returns a string containing a concise, human-readable description of this - * {@code UnresolvedPermission} including its target name and its target - * actions. - * - * @return a printable representation for this {@code UnresolvedPermission}. - */ - @Override - public String toString() { - return "(unresolved " + type + " " + name + " " - + actions + ")"; - } - - /** - * Returns a new {@code PermissionCollection} for holding {@code - * UnresolvedPermission} objects. - * - * @return a new PermissionCollection for holding {@code - * UnresolvedPermission} objects. - */ - @Override - public PermissionCollection newPermissionCollection() { - return new UnresolvedPermissionCollection(); - } - - /** - * Tries to resolve this permission into the specified class. - * <p> - * It is assumed that the class has a proper name (as returned by {@code - * getName()} of this unresolved permission), so no check is performed to - * verify this. However, the class must have all required certificates (as - * per {@code getUnresolvedCerts()}) among the passed collection of signers. - * If it does, a zero, one, and/or two-argument constructor is tried to - * instantiate a new permission, which is then returned. - * <p> - * If an appropriate constructor is not available or the class is improperly - * signed, {@code null} is returned. - * - * @param targetType - * - a target class instance, must not be {@code null} - * @return resolved permission or null - */ - Permission resolve(Class targetType) { - // check signers at first - if (PolicyUtils.matchSubset(targetCerts, targetType.getSigners())) { - try { - return PolicyUtils.instantiatePermission(targetType, - name, - actions); - } catch (Exception ignore) { - //TODO log warning? - } - } - return null; - } - - /** - * Outputs {@code type},{@code name},{@code actions} - * fields via default mechanism; next manually writes certificates in the - * following format: <br> - * - * <ol> - * <li> int : number of certs or zero </li> - * <li> each cert in the following format - * <ol> - * <li> String : certificate type </li> - * <li> int : length in bytes of certificate </li> - * <li> byte[] : certificate encoding </li> - * </ol> - * </li> - * </ol> - * - * @see <a href="http://java.sun.com/j2se/1.5.0/docs/api/serialized-form.html#java.security.UnresolvedPermission">Java Spec</a> - */ - private void writeObject(ObjectOutputStream out) throws IOException { - out.defaultWriteObject(); - if (targetCerts == null) { - out.writeInt(0); - } else { - out.writeInt(targetCerts.length); - for (int i = 0; i < targetCerts.length; i++) { - try { - byte[] enc = targetCerts[i].getEncoded(); - out.writeUTF(targetCerts[i].getType()); - out.writeInt(enc.length); - out.write(enc); - } catch (CertificateEncodingException cee) { - throw (IOException) new NotSerializableException("Cannot encode certificate: " + targetCerts[i]).initCause(cee); - } - } - } - } - - /** - * Reads the object from stream and checks target type for validity. - */ - private void readObject(ObjectInputStream in) throws IOException, - ClassNotFoundException { - in.defaultReadObject(); - checkType(getUnresolvedType()); - int certNumber = in.readInt(); - if (certNumber != 0) { - targetCerts = new Certificate[certNumber]; - for (int i = 0; i < certNumber; i++) { - try { - String type = in.readUTF(); - int length = in.readInt(); - byte[] enc = new byte[length]; - in.readFully(enc, 0, length); - targetCerts[i] = CertificateFactory.getInstance(type) - .generateCertificate(new ByteArrayInputStream(enc)); - } catch (CertificateException cee) { - throw (IOException) new IOException("Error decoding certificate").initCause(cee); - } - } - } - } + @Override public boolean implies(Permission permission) { return true; } } diff --git a/luni/src/main/java/java/security/UnresolvedPermissionCollection.java b/luni/src/main/java/java/security/UnresolvedPermissionCollection.java deleted file mode 100644 index 4a9dc19..0000000 --- a/luni/src/main/java/java/security/UnresolvedPermissionCollection.java +++ /dev/null @@ -1,193 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package java.security; - -import java.io.IOException; -import java.io.InvalidObjectException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.ObjectStreamField; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.Map; -import java.util.Vector; - -/** - * {@code UnresolvedPermissionCollection} represents a specific {@code - * PermissionCollection} for storing {@link UnresolvedPermission} instances. - * Contained elements are grouped by their target type. - */ -final class UnresolvedPermissionCollection extends PermissionCollection { - - private static final long serialVersionUID = -7176153071733132400L; - - private static final ObjectStreamField[] serialPersistentFields = { - new ObjectStreamField("permissions", Hashtable.class), - }; - - // elements of the collection. - private transient Map klasses = new HashMap(); - - /** - * Adds an unresolved permission to this {@code - * UnresolvedPermissionCollection}. - * - * @param permission - * the permission to be added. - * @throws SecurityException - * if this collection is read only. - * @throws IllegalArgumentException - * if {@code permission} is {@code null} or not an {@code - * UnresolvedPermission}. - */ - public void add(Permission permission) { - if (isReadOnly()) { - throw new SecurityException("collection is read-only"); - } - if (permission == null || permission.getClass() != UnresolvedPermission.class) { - throw new IllegalArgumentException("Invalid permission: " + permission); - } - synchronized (klasses) { - String klass = permission.getName(); - Collection klassMates = (Collection)klasses.get(klass); - if (klassMates == null) { - klassMates = new HashSet(); - klasses.put(klass, klassMates); - } - klassMates.add(permission); - } - } - - public Enumeration elements() { - Collection all = new ArrayList(); - for (Iterator iter = klasses.values().iterator(); iter.hasNext();) { - all.addAll((Collection)iter.next()); - } - return Collections.enumeration(all); - } - - /** - * Always returns {@code false}. - * - * @return always {@code false} - * @see UnresolvedPermission#implies(Permission). - */ - public boolean implies(Permission permission) { - return false; - } - - /** - * Returns true if this collection contains unresolved permissions - * with the same classname as argument permission. - */ - boolean hasUnresolved(Permission permission) { - return klasses.containsKey(permission.getClass().getName()); - } - - /** - * Resolves all permissions of the same class as the specified target - * permission and adds them to the specified collection. If passed - * collection is {@code null} and some unresolved permissions were resolved, - * an appropriate new collection is instantiated and used. All resolved - * permissions are removed from this unresolved collection, and collection - * with resolved ones is returned. - * - * @param target - * a kind of permissions to be resolved. - * @param holder - * an existing collection for storing resolved permissions. - * @return a collection containing resolved permissions (if any found) - */ - PermissionCollection resolveCollection(Permission target, - PermissionCollection holder) { - String klass = target.getClass().getName(); - if (klasses.containsKey(klass)) { - synchronized (klasses) { - Collection klassMates = (Collection)klasses.get(klass); - for (Iterator iter = klassMates.iterator(); iter.hasNext();) { - UnresolvedPermission element = (UnresolvedPermission)iter - .next(); - Permission resolved = element.resolve(target.getClass()); - if (resolved != null) { - if (holder == null) { - holder = target.newPermissionCollection(); - if (holder == null) { - holder = new PermissionsHash(); - } - } - holder.add(resolved); - iter.remove(); - } - } - if (klassMates.size() == 0) { - klasses.remove(klass); - } - } - } - return holder; - } - - /** - * Output fields via default mechanism. - */ - private void writeObject(java.io.ObjectOutputStream out) throws IOException { - Hashtable permissions = new Hashtable(); - for (Iterator iter = klasses.entrySet().iterator(); iter.hasNext();) { - Map.Entry entry = (Map.Entry) iter.next(); - String key = (String) entry.getKey(); - permissions.put(key, new Vector(((Collection) entry.getValue()))); - } - ObjectOutputStream.PutField fields = out.putFields(); - fields.put("permissions", permissions); - out.writeFields(); - } - - /** - * Reads the object from stream and checks elements grouping for validity. - */ - private void readObject(java.io.ObjectInputStream in) throws IOException, - ClassNotFoundException { - ObjectInputStream.GetField fields = in.readFields(); - Map permissions = (Map)fields.get("permissions", null); - klasses = new HashMap(); - synchronized (klasses) { - for (Iterator iter = permissions.entrySet().iterator(); iter - .hasNext();) { - Map.Entry entry = (Map.Entry) iter.next(); - String key = (String) entry.getKey(); - Collection values = (Collection) entry.getValue(); - - for (Iterator iterator = values.iterator(); iterator.hasNext();) { - UnresolvedPermission element = - (UnresolvedPermission) iterator.next(); - - if (!element.getName().equals(key)) { - throw new InvalidObjectException("collection is corrupted"); - } - } - klasses.put(key, new HashSet(values)); - } - } - } -} diff --git a/luni/src/main/java/java/security/acl/Permission.java b/luni/src/main/java/java/security/acl/Permission.java index 12391a9..d035a11 100644 --- a/luni/src/main/java/java/security/acl/Permission.java +++ b/luni/src/main/java/java/security/acl/Permission.java @@ -18,25 +18,9 @@ package java.security.acl; /** - * Legacy security code; this class exists for compatibility only. + * Legacy security code; do not use. */ public interface Permission { - - - /** - * Checks whether the specified object equals this permission. - * - * @param another - * the permission object to compare to this permission. - * @return true if the specified permission object is equal to this, false - * if not. - */ boolean equals(Object another); - - /** - * Returns the string representation of this permission. - * - * @return the string representation of this permission. - */ String toString(); } diff --git a/luni/src/main/java/java/security/security.properties b/luni/src/main/java/java/security/security.properties index d7a4890..361e2ad 100644 --- a/luni/src/main/java/java/security/security.properties +++ b/luni/src/main/java/java/security/security.properties @@ -13,9 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. -# This is the system security properties file -# It should be named: ${java.home}/lib/security/java.security - # # Providers @@ -31,74 +28,22 @@ security.provider.3=com.android.org.bouncycastle.jce.provider.BouncyCastleProvid security.provider.4=org.apache.harmony.security.provider.crypto.CryptoProvider security.provider.5=org.apache.harmony.xnet.provider.jsse.JSSEProvider -# -# Class to instantiate as a default Configuration implementation -# See specification for javax.security.auth.login.Configuration class. -# -login.configuration.provider=org.apache.harmony.auth.login.DefaultConfiguration - - -# -# Flag to enable/disable append/overwrite this properties file by the -# extra properties file passed on the command line with -# -Djava.security.properties=<file|url> or -Djava.security.properties==<file|url> -# Possible values: true/false. -# -security.allowCustomPropertiesFile=true - -# Class to instantiate as the default system Policy. -# The class should be available via bootclasspath. -# See specification for java.security.Policy class. -policy.provider=org.apache.harmony.security.fortress.DefaultPolicy -# The default is to have a single system-wide policy file, -# and an optional policy file in the user's home directory. -# It is possible to specify any number of policy files, via policy.url.n keys. -# See also: "JavaTM 2 Platform Security Architecture.", chapter 3. Permissions and Security Policy -policy.url.1=file:/${java.home}/lib/security/java.policy -policy.url.2=file:/${user.home}/.java.policy -# Flag to enable/disable properties expansion (${...}) in policy files. -# Possible values: true/false. -# See also: "JavaTM 2 Platform Security Architecture.", chapter 3. Permissions and Security Policy -policy.expandProperties=true - - -# Flag to enable/disable an extra policy to be passed on the command line -# with -Djava.security.policy=<file|url>. Possible values: true/false. -# See also: "JavaTM 2 Platform Security Architecture.", chapter 3. Permissions and Security Policy -policy.allowSystemProperty=true - - -# A comma-separated list of package prefixes that require -# extra protection at ClassLoader's level. -# See java/lang/SecurityManager#checkPackageAccess for more details. -package.access=org.apache.harmony.security.fortress.,com.intel.fortress.,com.ibm.oti. - - -# Class to instantiate as default JGSS manager. -jgss.spi.manager= - # The default SSLSocketFactory and SSLServerSocketFactory provider implementations. # See specification for # javax/net/ssl/SSLSocketFactory.html#getDefault() # javax/net/ssl/SSLServerSocketFactory.html#getDefault() -# BEGIN android-changed +# For regular SSLSockets, we have two implementations: ssl.SocketFactory.provider=org.apache.harmony.xnet.provider.jsse.OpenSSLSocketFactoryImpl -# END android-changed - -# BEGIN android-added -# Use the definition above to get the new, OpenSSL-based SSL implementation, -# or use this one to get the old, Android-based SSL implementation. -# ssl.SocketFactory.provider=javax.net.ssl.OldSSLSocketFactory -# END android-added +#ssl.SocketFactory.provider=org.apache.harmony.xnet.provider.jsse.SSLSocketFactoryImpl -# For SSL server sockets, there's only the new, OpenSSL-based implementation. +# For SSLServerSockets, there's only the new, OpenSSL-based implementation: ssl.ServerSocketFactory.provider=org.apache.harmony.xnet.provider.jsse.OpenSSLServerSocketFactoryImpl # Default KeyStore type. @@ -114,10 +59,7 @@ ssl.KeyManagerFactory.algorithm=X509 ssl.TrustManagerFactory.algorithm=X509 # system.scope is used to specify implementation class of IdentityScope -# this class should can be loaded by boot classloader system.scope=org.apache.harmony.security.SystemScope -# BEGIN android-added -# The following non-standard property controls peer certificate validation. +# The following Android-only property controls peer certificate validation. ssl.disablePeerCertificateChainVerification=false -# END android-added diff --git a/luni/src/main/java/java/sql/SQLPermission.java b/luni/src/main/java/java/sql/SQLPermission.java index 0418648..18065c6 100644 --- a/luni/src/main/java/java/sql/SQLPermission.java +++ b/luni/src/main/java/java/sql/SQLPermission.java @@ -20,35 +20,17 @@ package java.sql; import java.io.Serializable; import java.security.BasicPermission; import java.security.Guard; +import java.security.Permission; /** - * Legacy security code; this class exists for compatibility only. + * Legacy security code; do not use. */ -public final class SQLPermission extends BasicPermission implements Guard, - Serializable { +public final class SQLPermission extends BasicPermission implements Guard, Serializable { + public SQLPermission(String name) { super(""); } - private static final long serialVersionUID = -1439323187199563495L; + public SQLPermission(String name, String actions) { super("", ""); } - /** - * Creates a new {@code SQLPermission} object with the specified name. - * - * @param name - * the name to use for this {@code SQLPermission}. - */ - public SQLPermission(String name) { - super(name); - } + @Override public String getActions() { return null; } - /** - * Creates a new {@code SQLPermission} object with the specified name. - * - * @param name - * is the name of the {@code SQLPermission}. Currently only - * {@code "setLog"} is allowed. - * @param actions - * is currently unused and should be set to {@code null}. - */ - public SQLPermission(String name, String actions) { - super(name, null); - } + @Override public boolean implies(Permission permission) { return true; } } diff --git a/luni/src/main/java/java/util/PropertyPermission.java b/luni/src/main/java/java/util/PropertyPermission.java index b33a1a7..6287b91 100644 --- a/luni/src/main/java/java/util/PropertyPermission.java +++ b/luni/src/main/java/java/util/PropertyPermission.java @@ -26,135 +26,12 @@ import java.security.Permission; import java.security.PermissionCollection; /** - * Legacy security code; this class exists for compatibility only. + * Legacy security code; do not use. */ public final class PropertyPermission extends BasicPermission { - private static final long serialVersionUID = 885438825399942851L; + public PropertyPermission(String name, String actions) { super(""); } - transient private boolean read, write; + @Override public String getActions() { return null; } - /** - * Constructs a new instance of this class. - * - * @param name - * the (possibly wildcarded) name of the property. - * @param actions - * the actions which are applicable to it. Possible actions are - * "read", "write", or "read,write"/"write,read". Anything else - * will result in an {@code IllegalArgumentException}. - */ - public PropertyPermission(String name, String actions) { - super(name); - decodeActions(actions); - } - - private void decodeActions(String actions) { - StringTokenizer tokenizer = new StringTokenizer(actions.toLowerCase(Locale.US), " \t\n\r,"); - while (tokenizer.hasMoreTokens()) { - String token = tokenizer.nextToken(); - if (token.equals("read")) { - read = true; - } else if (token.equals("write")) { - write = true; - } else { - throw new IllegalArgumentException(); - } - } - if (!read && !write) { - throw new IllegalArgumentException(); - } - } - - /** - * Compares the argument to the receiver, and returns true if they represent - * the <em>same</em> object using a class specific comparison. In this - * case, the receiver must be a {@code PropertyPermission} for the same - * property as the argument, and must have the same actions. - * If {@code o} is a permission that is not a {@code PropertyPermission}, - * this method may throw a {@code ClassCastException}. - * - * @param o - * the {@code Object} to compare with this {@code Object}. - * @return {@code true} if the {@code Object} is the same as this {@code Object}, - * {@code false} if it is different from this {@code Object}. - * @see #hashCode - */ - @Override - public boolean equals(Object o) { - if (super.equals(o)) { - PropertyPermission pp = (PropertyPermission) o; - return read == pp.read && write == pp.write; - } - return false; - } - - /** - * Returns the actions associated with the receiver. The result will be - * either "read", "write", or "read,write". - * - * @return the actions associated with the receiver. - */ - @Override - public String getActions() { - return read ? (write ? "read,write" : "read") : "write"; - } - - /** - * Returns an integer hash code for the receiver. Any two objects which - * return {@code true} when passed to {@code equals} must return the same - * value for this method. - * - * @return the receiver's hash. - * @see #equals - */ - @Override - public int hashCode() { - return super.hashCode(); - } - - /** - * Indicates whether the argument permission is implied by the receiver. - * - * @return boolean {@code true} if the argument permission is implied by the - * receiver, and {@code false} if it is not. - * @param permission - * the permission to check. - */ - @Override - public boolean implies(Permission permission) { - if (super.implies(permission)) { - PropertyPermission pp = (PropertyPermission) permission; - return (read || !pp.read) && (write || !pp.write); - } - return false; - } - - /** - * Returns a new {@code PermissionCollection} for holding permissions of this class. - * Returns {@code null} if any {@code PermissionCollection} can be used. - * - * @return a new {@code PermissionCollection} or {@code null}. - * @see java.security.PermissionCollection - */ - @Override - public PermissionCollection newPermissionCollection() { - return new PropertyPermissionCollection(); - } - - private static final ObjectStreamField[] serialPersistentFields = { - new ObjectStreamField("actions", String.class), - }; - - private void writeObject(ObjectOutputStream stream) throws IOException { - ObjectOutputStream.PutField fields = stream.putFields(); - fields.put("actions", getActions()); - stream.writeFields(); - } - - private void readObject(ObjectInputStream stream) throws IOException, - ClassNotFoundException { - ObjectInputStream.GetField fields = stream.readFields(); - String actions = (String) fields.get("actions", ""); - decodeActions(actions); - } + @Override public boolean implies(Permission permission) { return true; } } diff --git a/luni/src/main/java/java/util/PropertyPermissionCollection.java b/luni/src/main/java/java/util/PropertyPermissionCollection.java deleted file mode 100644 index 6736d32..0000000 --- a/luni/src/main/java/java/util/PropertyPermissionCollection.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package java.util; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.ObjectStreamField; -import java.security.Permission; -import java.security.PermissionCollection; - -/** - * A {@code PermissionCollection} for holding {@code PropertyPermission}s. - */ -class PropertyPermissionCollection extends PermissionCollection { - - private static final long serialVersionUID = 7015263904581634791L; - - Hashtable<String, Permission> permissions = new Hashtable<String, Permission>( - 30); - - @Override - public void add(Permission perm) { - if (!isReadOnly()) { - Permission prev = permissions.put(perm.getName(), perm); - /* - * If the permission already existed but with only "read" or "write" - * set, then replace with both set. - */ - if (prev != null && !prev.getActions().equals(perm.getActions())) { - Permission np = new PropertyPermission(perm.getName(), - "read,write"); - permissions.put(perm.getName(), np); - } - } else { - throw new IllegalStateException(); - } - } - - @Override - public Enumeration<Permission> elements() { - return permissions.elements(); - } - - @Override - public boolean implies(Permission perm) { - Enumeration<Permission> elemEnum = elements(); - while (elemEnum.hasMoreElements()) { - if ((elemEnum.nextElement()).implies(perm)) { - return true; - } - } - /* - * At this point, the only way it can succeed is if both read and write - * are set, and these are separately granted by two different - * permissions with one representing a parent directory. - */ - return perm.getActions().equals("read,write") - && implies(new PropertyPermission(perm.getName(), "read")) - && implies(new PropertyPermission(perm.getName(), "write")); - } - - private static final ObjectStreamField[] serialPersistentFields = { - new ObjectStreamField("permissions", Hashtable.class), - new ObjectStreamField("all_allowed", boolean.class), - }; - - private void writeObject(ObjectOutputStream stream) throws IOException { - ObjectOutputStream.PutField fields = stream.putFields(); - fields.put("permissions", permissions); - fields.put("all_allowed", false); - stream.writeFields(); - } - - @SuppressWarnings("unchecked") - private void readObject(ObjectInputStream stream) throws IOException, - ClassNotFoundException { - ObjectInputStream.GetField fields = stream.readFields(); - permissions = (Hashtable<String, Permission>) fields.get( - "permissions", null); - } -} diff --git a/luni/src/main/java/java/util/logging/LoggingPermission.java b/luni/src/main/java/java/util/logging/LoggingPermission.java index 0f06154..3a55e26 100644 --- a/luni/src/main/java/java/util/logging/LoggingPermission.java +++ b/luni/src/main/java/java/util/logging/LoggingPermission.java @@ -20,25 +20,15 @@ package java.util.logging; import java.io.Serializable; import java.security.BasicPermission; import java.security.Guard; +import java.security.Permission; /** - * Legacy security code; this class exists for compatibility only. + * Legacy security code; do not use. */ public final class LoggingPermission extends BasicPermission implements Guard, Serializable { + public LoggingPermission(String name, String actions) { super("", ""); } - // for serialization compatibility with J2SE 1.4.2 - private static final long serialVersionUID = 63564341580231582L; + @Override public String getActions() { return null; } - /** - * Legacy security code; this class exists for compatibility only. - */ - public LoggingPermission(String name, String actions) { - super(name, actions); - if (!"control".equals(name)) { - throw new IllegalArgumentException("name must be \"control\""); - } - if (actions != null && !actions.isEmpty()) { - throw new IllegalArgumentException("actions != null && !actions.isEmpty()"); - } - } + @Override public boolean implies(Permission permission) { return true; } } diff --git a/luni/src/main/java/javax/net/ssl/SSLPermission.java b/luni/src/main/java/javax/net/ssl/SSLPermission.java index e881cc4..b937be0 100644 --- a/luni/src/main/java/javax/net/ssl/SSLPermission.java +++ b/luni/src/main/java/javax/net/ssl/SSLPermission.java @@ -18,33 +18,17 @@ package javax.net.ssl; import java.security.BasicPermission; +import java.security.Permission; /** - * Legacy security code; this class exists for compatibility only. + * Legacy security code; do not use. */ public final class SSLPermission extends BasicPermission { + public SSLPermission(String name) { super(""); } - private static final long serialVersionUID = -3456898025505876775L; + public SSLPermission(String name, String actions) { super("", ""); } - /** - * Creates a new {@code SSLPermission} with the specified name. - * - * @param name - * the permission name. - */ - public SSLPermission(String name) { - super(name); - } + @Override public String getActions() { return null; } - /** - * Creates a new {@code SSLPermission} with the specified name. - * - * @param name - * the permission name. - * @param actions - * is ignored and should be {@code null}. - */ - public SSLPermission(String name, String actions) { - super(name, actions); - } + @Override public boolean implies(Permission permission) { return true; } } diff --git a/luni/src/main/java/javax/security/auth/AuthPermission.java b/luni/src/main/java/javax/security/auth/AuthPermission.java index 173f679..3bf621a 100644 --- a/luni/src/main/java/javax/security/auth/AuthPermission.java +++ b/luni/src/main/java/javax/security/auth/AuthPermission.java @@ -18,49 +18,17 @@ package javax.security.auth; import java.security.BasicPermission; +import java.security.Permission; /** - * Legacy security code; this class exists for compatibility only. + * Legacy security code; do not use. */ public final class AuthPermission extends BasicPermission { + public AuthPermission(String name) { super(""); } - private static final long serialVersionUID = 5806031445061587174L; + public AuthPermission(String name, String actions) { super("", ""); } - private static final String CREATE_LOGIN_CONTEXT = "createLoginContext"; + @Override public String getActions() { return null; } - private static final String CREATE_LOGIN_CONTEXT_ANY = "createLoginContext.*"; - - // inits permission name. - private static String init(String name) { - if (name == null) { - throw new NullPointerException("name == null"); - } - - if (CREATE_LOGIN_CONTEXT.equals(name)) { - return CREATE_LOGIN_CONTEXT_ANY; - } - return name; - } - - /** - * Creates an authentication permission with the specified target name. - * - * @param name - * the target name of this authentication permission. - */ - public AuthPermission(String name) { - super(init(name)); - } - - /** - * Creates an authentication permission with the specified target name. - * - * @param name - * the target name of this authentication permission. - * @param actions - * this parameter is ignored and should be {@code null}. - */ - public AuthPermission(String name, String actions) { - super(init(name), actions); - } + @Override public boolean implies(Permission permission) { return true; } } diff --git a/luni/src/main/java/javax/security/auth/PrivateCredentialPermission.java b/luni/src/main/java/javax/security/auth/PrivateCredentialPermission.java index 7a9903d..0b6bebc 100644 --- a/luni/src/main/java/javax/security/auth/PrivateCredentialPermission.java +++ b/luni/src/main/java/javax/security/auth/PrivateCredentialPermission.java @@ -26,355 +26,16 @@ import java.security.Principal; import java.util.Set; /** - * Legacy security code; this class exists for compatibility only. + * Legacy security code; do not use. */ public final class PrivateCredentialPermission extends Permission { + public PrivateCredentialPermission(String name, String action) { super(""); } - private static final long serialVersionUID = 5284372143517237068L; + public String[][] getPrincipals() { return null; } - // allowed action - private static final String READ = "read"; + public String getCredentialClass() { return null; } - private String credentialClass; + @Override public String getActions() { return null; } - // current offset - private transient int offset; - - // owners set - private transient CredOwner[] set; - - /** - * Creates a new permission for private credentials specified by the target - * name {@code name} and an {@code action}. The action is always - * {@code "read"}. - * - * @param name - * the target name of the permission. - * @param action - * the action {@code "read"}. - */ - public PrivateCredentialPermission(String name, String action) { - super(name); - if (READ.equalsIgnoreCase(action)) { - initTargetName(name); - } else { - throw new IllegalArgumentException("Action must be \"read\""); - } - } - - /** - * Creates a {@code PrivateCredentialPermission} from the {@code Credential} - * class and set of principals. - * - * @param credentialClass - * the credential class name. - * @param principals - * the set of principals. - */ - PrivateCredentialPermission(String credentialClass, Set<Principal> principals) { - super(credentialClass); - this.credentialClass = credentialClass; - - set = new CredOwner[principals.size()]; - for (Principal p : principals) { - CredOwner element = new CredOwner(p.getClass().getName(), p.getName()); - // check for duplicate elements - boolean found = false; - for (int ii = 0; ii < offset; ii++) { - if (set[ii].equals(element)) { - found = true; - break; - } - } - if (!found) { - set[offset++] = element; - } - } - } - - /** - * Initialize a PrivateCredentialPermission object and checks that a target - * name has a correct format: CredentialClass 1*(PrincipalClass - * "PrincipalName") - */ - private void initTargetName(String name) { - - if (name == null) { - throw new NullPointerException("name == null"); - } - - // check empty string - name = name.trim(); - if (name.isEmpty()) { - throw new IllegalArgumentException("name is empty"); - } - - // get CredentialClass - int beg = name.indexOf(' '); - if (beg == -1) { - throw badSyntax(); - } - credentialClass = name.substring(0, beg); - - // get a number of pairs: PrincipalClass "PrincipalName" - beg++; - int count = 0; - int nameLength = name.length(); - for (int i, j = 0; beg < nameLength; beg = j + 2, count++) { - i = name.indexOf(' ', beg); - j = name.indexOf('"', i + 2); - - if (i == -1 || j == -1 || name.charAt(i + 1) != '"') { - throw badSyntax(); - } - } - - // name MUST have one pair at least - if (count < 1) { - throw badSyntax(); - } - - beg = name.indexOf(' '); - beg++; - - // populate principal set with instances of CredOwner class - String principalClass; - String principalName; - - set = new CredOwner[count]; - for (int index = 0, i, j; index < count; beg = j + 2, index++) { - i = name.indexOf(' ', beg); - j = name.indexOf('"', i + 2); - - principalClass = name.substring(beg, i); - principalName = name.substring(i + 2, j); - - CredOwner element = new CredOwner(principalClass, principalName); - // check for duplicate elements - boolean found = false; - for (int ii = 0; ii < offset; ii++) { - if (set[ii].equals(element)) { - found = true; - break; - } - } - if (!found) { - set[offset++] = element; - } - } - } - - private IllegalArgumentException badSyntax() { - throw new IllegalArgumentException("Target name MUST have the following syntax: " + - "CredentialClass 1*(PrincipalClass \"PrincipalName\")"); - } - - private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { - ois.defaultReadObject(); - initTargetName(getName()); - } - - /** - * Returns the principal's classes and names associated with this {@code - * PrivateCredentialPermission} as a two dimensional array. The first - * dimension of the array corresponds to the number of principals. The - * second dimension defines either the name of the {@code PrincipalClass} - * [x][0] or the value of {@code PrincipalName} [x][1]. - * <p> - * This corresponds to the the target name's syntax: - * - * <pre> - * targetName = CredentialClass {PrincipalClass "PrincipalName"}* - * </pre> - * - * @return the principal classes and names associated with this {@code - * PrivateCredentialPermission}. - */ - public String[][] getPrincipals() { - - String[][] s = new String[offset][2]; - - for (int i = 0; i < s.length; i++) { - s[i][0] = set[i].principalClass; - s[i][1] = set[i].principalName; - } - return s; - } - - @Override - public String getActions() { - return READ; - } - - /** - * Returns the class name of the credential associated with this permission. - * - * @return the class name of the credential associated with this permission. - */ - public String getCredentialClass() { - return credentialClass; - } - - @Override - public int hashCode() { - int hash = 0; - for (int i = 0; i < offset; i++) { - hash = hash + set[i].hashCode(); - } - return getCredentialClass().hashCode() + hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - - if (obj == null || this.getClass() != obj.getClass()) { - return false; - } - - PrivateCredentialPermission that = (PrivateCredentialPermission) obj; - - return credentialClass.equals(that.credentialClass) && (offset == that.offset) - && sameMembers(set, that.set, offset); - } - - @Override - public boolean implies(Permission permission) { - - if (permission == null || this.getClass() != permission.getClass()) { - return false; - } - - PrivateCredentialPermission that = (PrivateCredentialPermission) permission; - - if (!("*".equals(credentialClass) || credentialClass - .equals(that.getCredentialClass()))) { - return false; - } - - if (that.offset == 0) { - return true; - } - - CredOwner[] thisCo = set; - CredOwner[] thatCo = that.set; - int thisPrincipalsSize = offset; - int thatPrincipalsSize = that.offset; - for (int i = 0, j; i < thisPrincipalsSize; i++) { - for (j = 0; j < thatPrincipalsSize; j++) { - if (thisCo[i].implies(thatCo[j])) { - break; - } - } - if (j == thatCo.length) { - return false; - } - } - return true; - } - - @Override - public PermissionCollection newPermissionCollection() { - return null; - } - - /** - * Returns true if the two arrays have the same length, and every member of - * one array is contained in another array - */ - private boolean sameMembers(Object[] ar1, Object[] ar2, int length) { - if (ar1 == null && ar2 == null) { - return true; - } - if (ar1 == null || ar2 == null) { - return false; - } - boolean found; - for (int i = 0; i < length; i++) { - found = false; - for (int j = 0; j < length; j++) { - if (ar1[i].equals(ar2[j])) { - found = true; - break; - } - } - if (!found) { - return false; - } - } - return true; - } - - private static final class CredOwner implements Serializable { - - private static final long serialVersionUID = -5607449830436408266L; - - String principalClass; - - String principalName; - - // whether class name contains wildcards - private transient boolean isClassWildcard; - - // whether pname contains wildcards - private transient boolean isPNameWildcard; - - // Creates a new CredOwner with the specified Principal Class and Principal Name - CredOwner(String principalClass, String principalName) { - if ("*".equals(principalClass)) { - isClassWildcard = true; - } - - if ("*".equals(principalName)) { - isPNameWildcard = true; - } - - if (isClassWildcard && !isPNameWildcard) { - throw badPrincipal(); - } - - this.principalClass = principalClass; - this.principalName = principalName; - } - - private IllegalArgumentException badPrincipal() { - throw new IllegalArgumentException("invalid syntax: Principal Class can not be a " + - "wildcard (*) value if Principal Name is not a wildcard (*) value"); - } - - // Checks if this CredOwner implies the specified Object. - boolean implies(Object obj) { - if (obj == this) { - return true; - } - - CredOwner co = (CredOwner) obj; - - if (isClassWildcard || principalClass.equals(co.principalClass)) { - if (isPNameWildcard || principalName.equals(co.principalName)) { - return true; - } - } - return false; - } - - // Checks two CredOwner objects for equality. - @Override - public boolean equals(Object o) { - if (!(o instanceof CredOwner)) { - return false; - } - CredOwner lhs = (CredOwner) o; - return principalClass.equals(lhs.principalClass) && - principalName.equals(lhs.principalName); - } - - // Returns the hash code value for this object. - @Override - public int hashCode() { - return principalClass.hashCode() + principalName.hashCode(); - } - } + @Override public boolean implies(Permission permission) { return true; } } diff --git a/luni/src/main/java/org/apache/harmony/security/DefaultPolicyScanner.java b/luni/src/main/java/org/apache/harmony/security/DefaultPolicyScanner.java deleted file mode 100644 index f2cc0d2..0000000 --- a/luni/src/main/java/org/apache/harmony/security/DefaultPolicyScanner.java +++ /dev/null @@ -1,516 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** -* @author Alexey V. Varlamov -* @version $Revision$ -*/ - -package org.apache.harmony.security; - -import java.io.IOException; -import java.io.Reader; -import java.io.StreamTokenizer; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; - -/** - * This is a basic high-level tokenizer of policy files. It takes in a stream, - * analyzes data read from it and returns a set of structured tokens. <br> - * This implementation recognizes text files, consisting of clauses with the - * following syntax: - * - * <pre> - * - * keystore "some_keystore_url", "keystore_type"; - * - * </pre> - * <pre> - * - * grant [SignedBy "signer_names"] [, CodeBase "URL"] - * [, Principal [principal_class_name] "principal_name"] - * [, Principal [principal_class_name] "principal_name"] ... { - * permission permission_class_name [ "target_name" ] [, "action"] - * [, SignedBy "signer_names"]; - * permission ... - * }; - * - * </pre> - * - * For semantical details of this format, see the - * {@link org.apache.harmony.security.fortress.DefaultPolicy default policy description}. - * <br> - * Keywords are case-insensitive in contrast to quoted string literals. - * Comma-separation rule is quite forgiving, most commas may be just omitted. - * Whitespaces, line- and block comments are ignored. Symbol-level tokenization - * is delegated to java.io.StreamTokenizer. <br> - * <br> - * This implementation is effectively thread-safe, as it has no field references - * to data being processed (that is, passes all the data as method parameters). - * - * @see org.apache.harmony.security.fortress.DefaultPolicyParser - */ -public class DefaultPolicyScanner { - - /** - * Specific exception class to signal policy file syntax error. - * - */ - public static class InvalidFormatException extends Exception { - - /** - * @serial - */ - private static final long serialVersionUID = 5789786270390222184L; - - /** - * Constructor with detailed message parameter. - */ - public InvalidFormatException(String arg0) { - super(arg0); - } - } - - /** - * Configures passed tokenizer accordingly to supported syntax. - */ - protected StreamTokenizer configure(StreamTokenizer st) { - st.slashSlashComments(true); - st.slashStarComments(true); - st.wordChars('_', '_'); - st.wordChars('$', '$'); - return st; - } - - /** - * Performs the main parsing loop. Starts with creating and configuring a - * StreamTokenizer instance; then tries to recognize <i>keystore </i> or - * <i>grant </i> keyword. When found, invokes read method corresponding to - * the clause and collects result to the passed collection. - * - * @param r - * policy stream reader - * @param grantEntries - * a collection to accumulate parsed GrantEntries - * @param keystoreEntries - * a collection to accumulate parsed KeystoreEntries - * @throws IOException - * if stream reading failed - * @throws InvalidFormatException - * if unexpected or unknown token encountered - */ - public void scanStream(Reader r, Collection<GrantEntry> grantEntries, - List<KeystoreEntry> keystoreEntries) throws IOException, - InvalidFormatException { - StreamTokenizer st = configure(new StreamTokenizer(r)); - //main parsing loop - parsing: while (true) { - switch (st.nextToken()) { - case StreamTokenizer.TT_EOF: //we've done the job - break parsing; - - case StreamTokenizer.TT_WORD: - if (st.sval.equalsIgnoreCase("keystore")) { - keystoreEntries.add(readKeystoreEntry(st)); - } else if (st.sval.equalsIgnoreCase("grant")) { - grantEntries.add(readGrantEntry(st)); - } else { - handleUnexpectedToken(st, "Expected entries are \"grant\" or \"keystore\""); - } - break; - - case ';': //just delimiter of entries - break; - - default: - handleUnexpectedToken(st); - break; - } - } - } - - /** - * Tries to read <i>keystore </i> clause fields. The expected syntax is - * - * <pre> - * - * "some_keystore_url"[, "keystore_type"]; - * - * </pre> - * - * @return successfully parsed KeystoreEntry - * @throws IOException - * if stream reading failed - * @throws InvalidFormatException - * if unexpected or unknown token encountered - */ - protected KeystoreEntry readKeystoreEntry(StreamTokenizer st) - throws IOException, InvalidFormatException { - KeystoreEntry ke = new KeystoreEntry(); - if (st.nextToken() == '"') { - ke.url = st.sval; - if ((st.nextToken() == '"') - || ((st.ttype == ',') && (st.nextToken() == '"'))) { - ke.type = st.sval; - } else { // handle token in the main loop - st.pushBack(); - } - } else { - handleUnexpectedToken(st, "Expected syntax is : keystore \"url\"[, \"type\"]"); - } - return ke; - } - - /** - * Tries to read <i>grant </i> clause. <br> - * First, it reads <i>codebase </i>, <i>signedby </i>, <i>principal </i> - * entries till the '{' (opening curly brace) symbol. Then it calls - * readPermissionEntries() method to read the permissions of this clause. - * <br> - * Principal entries (if any) are read by invoking readPrincipalEntry() - * method, obtained PrincipalEntries are accumulated. <br> - * The expected syntax is - * - * <pre> - * - * [ [codebase "url"] | [signedby "name1,...,nameN"] | - * principal ...] ]* { ... } - * - * </pre> - * - * @return successfully parsed GrantEntry - * @throws IOException - * if stream reading failed - * @throws InvalidFormatException - * if unexpected or unknown token encountered - */ - protected GrantEntry readGrantEntry(StreamTokenizer st) throws IOException, - InvalidFormatException { - GrantEntry ge = new GrantEntry(); - parsing: while (true) { - switch (st.nextToken()) { - - case StreamTokenizer.TT_WORD: - if (st.sval.equalsIgnoreCase("signedby")) { - if (st.nextToken() == '"') { - ge.signers = st.sval; - } else { - handleUnexpectedToken(st, "Expected syntax is signedby \"name1,...,nameN\""); - } - } else if (st.sval.equalsIgnoreCase("codebase")) { - if (st.nextToken() == '"') { - ge.codebase = st.sval; - } else { - handleUnexpectedToken(st, "Expected syntax is codebase \"url\""); - } - } else if (st.sval.equalsIgnoreCase("principal")) { - ge.addPrincipal(readPrincipalEntry(st)); - } else { - handleUnexpectedToken(st); - } - break; - - case ',': //just delimiter of entries - break; - - case '{': - ge.permissions = readPermissionEntries(st); - break parsing; - - default: // handle token in the main loop - st.pushBack(); - break parsing; - } - } - - return ge; - } - - /** - * Tries to read <i>Principal </i> entry fields. The expected syntax is - * - * <pre> - * - * [ principal_class_name ] "principal_name" - * - * </pre> - * - * Both class and name may be wildcards, wildcard names should not - * surrounded by quotes. - * - * @return successfully parsed PrincipalEntry - * @throws IOException - * if stream reading failed - * @throws InvalidFormatException - * if unexpected or unknown token encountered - */ - protected PrincipalEntry readPrincipalEntry(StreamTokenizer st) - throws IOException, InvalidFormatException { - PrincipalEntry pe = new PrincipalEntry(); - if (st.nextToken() == StreamTokenizer.TT_WORD) { - pe.klass = st.sval; - st.nextToken(); - } else if (st.ttype == '*') { - pe.klass = PrincipalEntry.WILDCARD; - st.nextToken(); - } - if (st.ttype == '"') { - pe.name = st.sval; - } else if (st.ttype == '*') { - pe.name = PrincipalEntry.WILDCARD; - } else { - handleUnexpectedToken(st, "Expected syntax is principal [class_name] \"principal_name\""); - } - return pe; - } - - /** - * Tries to read a list of <i>permission </i> entries. The expected syntax - * is - * - * <pre> - * - * permission permission_class_name - * [ "target_name" ] [, "action_list"] - * [, signedby "name1,name2,..."]; - * - * </pre> - * - * List is terminated by '}' (closing curly brace) symbol. - * - * @return collection of successfully parsed PermissionEntries - * @throws IOException - * if stream reading failed - * @throws InvalidFormatException - * if unexpected or unknown token encountered - */ - protected Collection<PermissionEntry> readPermissionEntries( - StreamTokenizer st) throws IOException, InvalidFormatException { - Collection<PermissionEntry> permissions = new HashSet<PermissionEntry>(); - parsing: while (true) { - switch (st.nextToken()) { - - case StreamTokenizer.TT_WORD: - if (st.sval.equalsIgnoreCase("permission")) { - PermissionEntry pe = new PermissionEntry(); - if (st.nextToken() == StreamTokenizer.TT_WORD) { - pe.klass = st.sval; - if (st.nextToken() == '"') { - pe.name = st.sval; - st.nextToken(); - } - if (st.ttype == ',') { - st.nextToken(); - } - if (st.ttype == '"') { - pe.actions = st.sval; - if (st.nextToken() == ',') { - st.nextToken(); - } - } - if (st.ttype == StreamTokenizer.TT_WORD - && st.sval.equalsIgnoreCase("signedby")) { - if (st.nextToken() == '"') { - pe.signers = st.sval; - } else { - handleUnexpectedToken(st); - } - } else { // handle token in the next iteration - st.pushBack(); - } - permissions.add(pe); - continue parsing; - } - } - handleUnexpectedToken(st, "Expected syntax is permission permission_class_name [\"target_name\"] [, \"action_list\"] [, signedby \"name1,...,nameN\"]"); - break; - - case ';': //just delimiter of entries - break; - - case '}': //end of list - break parsing; - - default: // invalid token - handleUnexpectedToken(st); - break; - } - } - - return permissions; - } - - /** - * Formats a detailed description of tokenizer status: current token, - * current line number, etc. - */ - protected String composeStatus(StreamTokenizer st) { - return st.toString(); - } - - /** - * Throws InvalidFormatException with detailed diagnostics. - * - * @param st - * a tokenizer holding the erroneous token - * @param message - * a user-friendly comment, probably explaining expected syntax. - * Should not be <code>null</code>- use the overloaded - * single-parameter method instead. - */ - protected final void handleUnexpectedToken(StreamTokenizer st, String message) - throws InvalidFormatException { - throw new InvalidFormatException("Unexpected token encountered: " + - composeStatus(st) + ". " + message); - } - - /** - * Throws InvalidFormatException with error status: which token is - * unexpected on which line. - * - * @param st - * a tokenizer holding the erroneous token - */ - protected final void handleUnexpectedToken(StreamTokenizer st) throws InvalidFormatException { - throw new InvalidFormatException("Unexpected token encountered: " + composeStatus(st)); - } - - /** - * Compound token representing <i>keystore </i> clause. See policy format - * {@link org.apache.harmony.security.fortress.DefaultPolicy description}for details. - * - * @see org.apache.harmony.security.fortress.DefaultPolicyParser - * @see org.apache.harmony.security.DefaultPolicyScanner - */ - public static class KeystoreEntry { - - /** - * The URL part of keystore clause. - */ - public String url; - - /** - * The typename part of keystore clause. - */ - public String type; - } - - /** - * Compound token representing <i>grant </i> clause. See policy format - * {@link org.apache.harmony.security.fortress.DefaultPolicy description}for details. - * - * @see org.apache.harmony.security.fortress.DefaultPolicyParser - * @see org.apache.harmony.security.DefaultPolicyScanner - */ - public static class GrantEntry { - - /** - * The signers part of grant clause. This is a comma-separated list of - * certificate aliases. - */ - public String signers; - - /** - * The codebase part of grant clause. This is an URL from which code - * originates. - */ - public String codebase; - - /** - * Collection of PrincipalEntries of grant clause. - */ - public Collection<PrincipalEntry> principals; - - /** - * Collection of PermissionEntries of grant clause. - */ - public Collection<PermissionEntry> permissions; - - /** - * Adds specified element to the <code>principals</code> collection. - * If collection does not exist yet, creates a new one. - */ - public void addPrincipal(PrincipalEntry pe) { - if (principals == null) { - principals = new HashSet<PrincipalEntry>(); - } - principals.add(pe); - } - - } - - /** - * Compound token representing <i>principal </i> entry of a <i>grant </i> - * clause. See policy format - * {@link org.apache.harmony.security.fortress.DefaultPolicy description}for details. - * - * @see org.apache.harmony.security.fortress.DefaultPolicyParser - * @see org.apache.harmony.security.DefaultPolicyScanner - */ - public static class PrincipalEntry { - - /** - * Wildcard value denotes any class and/or any name. - * Must be asterisk, for proper general expansion and - * PrivateCredentialsPermission wildcarding - */ - public static final String WILDCARD = "*"; - - /** - * The classname part of principal clause. - */ - public String klass; - - /** - * The name part of principal clause. - */ - public String name; - } - - /** - * Compound token representing <i>permission </i> entry of a <i>grant </i> - * clause. See policy format - * {@link org.apache.harmony.security.fortress.DefaultPolicy description}for details. - * - * @see org.apache.harmony.security.fortress.DefaultPolicyParser - * @see org.apache.harmony.security.DefaultPolicyScanner - */ - public static class PermissionEntry { - - /** - * The classname part of permission clause. - */ - public String klass; - - /** - * The name part of permission clause. - */ - public String name; - - /** - * The actions part of permission clause. - */ - public String actions; - - /** - * The signers part of permission clause. This is a comma-separated list - * of certificate aliases. - */ - public String signers; - } -} diff --git a/luni/src/main/java/org/apache/harmony/security/PolicyEntry.java b/luni/src/main/java/org/apache/harmony/security/PolicyEntry.java deleted file mode 100644 index 32f15a3..0000000 --- a/luni/src/main/java/org/apache/harmony/security/PolicyEntry.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** -* @author Alexey V. Varlamov -* @version $Revision$ -*/ - -package org.apache.harmony.security; - -import java.net.URL; -import java.security.CodeSigner; -import java.security.CodeSource; -import java.security.Permission; -import java.security.Principal; -import java.util.Collection; -import java.util.Collections; -import org.apache.harmony.security.fortress.PolicyUtils; - -/** - * This class represents an elementary block of a security policy. It associates - * a CodeSource of an executable code, Principals allowed to execute the code, - * and a set of granted Permissions. - * - * @see org.apache.harmony.security.fortress.DefaultPolicy - */ -public class PolicyEntry { - - // Store CodeSource - private final CodeSource cs; - - // Array of principals - private final Principal[] principals; - - // Permissions collection - private final Collection<Permission> permissions; - - /** - * Constructor with initialization parameters. Passed collections are not - * referenced directly, but copied. - */ - public PolicyEntry(CodeSource cs, Collection<? extends Principal> prs, - Collection<? extends Permission> permissions) { - this.cs = (cs != null) ? normalizeCodeSource(cs) : null; - this.principals = (prs == null || prs.isEmpty()) ? null - : prs.toArray(new Principal[prs.size()]); - this.permissions = (permissions == null || permissions.isEmpty()) ? null - : Collections.unmodifiableCollection(permissions); - } - - /** - * Checks if passed CodeSource matches this PolicyEntry. Null CodeSource of - * PolicyEntry implies any CodeSource; non-null CodeSource forwards to its - * imply() method. - */ - public boolean impliesCodeSource(CodeSource codeSource) { - if (cs == null) { - return true; - } - - if (codeSource == null) { - return false; - } - return cs.implies(normalizeCodeSource(codeSource)); - } - - private CodeSource normalizeCodeSource(CodeSource codeSource) { - URL codeSourceURL = PolicyUtils.normalizeURL(codeSource.getLocation()); - CodeSource result = codeSource; - - if (codeSourceURL != codeSource.getLocation()) { - // URL was normalized - recreate codeSource with new URL - CodeSigner[] signers = codeSource.getCodeSigners(); - if (signers == null) { - result = new CodeSource(codeSourceURL, codeSource - .getCertificates()); - } else { - result = new CodeSource(codeSourceURL, signers); - } - } - return result; - } - - /** - * Checks if specified Principals match this PolicyEntry. Null or empty set - * of Principals of PolicyEntry implies any Principals; otherwise specified - * array must contain all Principals of this PolicyEntry. - */ - public boolean impliesPrincipals(Principal[] prs) { - return PolicyUtils.matchSubset(principals, prs); - } - - /** - * Returns unmodifiable collection of permissions defined by this - * PolicyEntry, may be <code>null</code>. - */ - public Collection<Permission> getPermissions() { - return permissions; - } - - /** - * Returns true if this PolicyEntry defines no Permissions, false otherwise. - */ - public boolean isVoid() { - return permissions == null || permissions.size() == 0; - } -} diff --git a/luni/src/main/java/org/apache/harmony/security/UnresolvedPrincipal.java b/luni/src/main/java/org/apache/harmony/security/UnresolvedPrincipal.java deleted file mode 100644 index 1094aed..0000000 --- a/luni/src/main/java/org/apache/harmony/security/UnresolvedPrincipal.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** -* @author Alexey V. Varlamov -* @version $Revision$ -*/ - -package org.apache.harmony.security; - -import java.security.Principal; - -/** - * Descriptive implementation of Principal, which holds a name and a classname - * of unresolved principal. It is used to define an arbitrary Principal which - * may be not yet instantiated and authenticated. - * <br> - * This concept is somewhat similar to UnresolvedPermission. A principal-based - * policy may grant permissions depending on what Principals own the current - * execution thread. So the policy refers to this model definition of - * acceptable principal and compares it with the actual principal. - * - * @see org.apache.harmony.security.PolicyEntry - * @see org.apache.harmony.security.fortress.DefaultPolicy - */ -public final class UnresolvedPrincipal implements Principal { - - /** - * Wildcard value denotes any class and/or any name. - */ - public static final String WILDCARD = DefaultPolicyScanner.PrincipalEntry.WILDCARD; - - // Class name - private final String klass; - - // Principal name - private final String name; - - /** - * Constructs a a new definition of a Principal with specified - * parameters. - * @param klass fully qualified class name, may be wildcard - * @param name name of principal, may be wildcard - * @throws IllegalArgumentException if <code>klass</code> value - * is <code>null </code> or is empty string - */ - public UnresolvedPrincipal(String klass, String name) { - if (klass == null || klass.isEmpty()) { - throw new IllegalArgumentException(); - } - - this.klass = klass; - this.name = name; - } - - /** - * Returns name of a modeled Principal, or wildcard - * if any name is acceptable. - */ - public String getName() { - return name; - } - - /** - * Returns fully qualified class name of a modeled Principal, - * or wildcard if any class is acceptable. - */ - public String getClassName() { - return klass; - } - - /** - * Returns <code>true</code> if compared object is a Principal - * matching this definition, or if it is an UnresolvedPrincipal, - * which defines the same Principal; <code>false</code> otherwise. - */ - public boolean equals(Object that) { - if (that instanceof UnresolvedPrincipal) { - UnresolvedPrincipal up = (UnresolvedPrincipal) that; - return klass.equals(up.klass) - && (name == null ? up.name == null : name.equals(up.name)); - } - if (that instanceof Principal) { - return implies((Principal) that); - } - return false; - } - - /** - * Returns <code>true</code> if compared object is a Principal - * exactly matching this definition. Namely, if the fully qualified name - * of class of passed Principal is equal to the class name value - * of this definition and the name of passed Principal is equal to - * the name value of this definition, or if this definition allows - * any class or name, respectively. - * Otherwise returns <code>false</code> . - */ - public boolean implies(Principal another) { - return (another != null) - && (WILDCARD.equals(klass) - || klass.equals(another.getClass().getName()) - && (WILDCARD.equals(name) - || (name == null ? another.getName() == null - : name.equals(another.getName())))); - } - - /** - * Returns the hash code value for this object. - */ - public int hashCode() { - int hash = 0; - if (name != null) { - hash ^= name.hashCode(); - } - if (klass != null) { - hash ^= klass.hashCode(); - } - return hash; - } - - /** - * Returns a string describing this model of Principal. - * The format is 'Principal classname "name"'. - */ - public String toString() { - return "Principal " + klass + " \"" + name + "\""; - } -} diff --git a/luni/src/main/java/org/apache/harmony/security/fortress/DefaultPolicy.java b/luni/src/main/java/org/apache/harmony/security/fortress/DefaultPolicy.java deleted file mode 100644 index 8d07013..0000000 --- a/luni/src/main/java/org/apache/harmony/security/fortress/DefaultPolicy.java +++ /dev/null @@ -1,307 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** -* @author Alexey V. Varlamov -* @version $Revision$ -*/ - -package org.apache.harmony.security.fortress; - -import java.io.File; -import java.net.URL; -import java.security.CodeSource; -import java.security.Permission; -import java.security.PermissionCollection; -import java.security.Policy; -import java.security.ProtectionDomain; -import java.util.Collection; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Map; -import java.util.Properties; -import java.util.Set; -import java.util.WeakHashMap; -import org.apache.harmony.security.PolicyEntry; - - -/** - * Default Policy implementation based on policy configuration files. This - * implementation recognizes text files, consisting of clauses with the - * following syntax: - * - * <pre> - * keystore "some_keystore_url" [, "keystore_type"]; - * </pre> - <pre> - * grant [SignedBy "signer_names"] [, CodeBase "URL"] - * [, Principal [principal_class_name] "principal_name"] - * [, Principal [principal_class_name] "principal_name"] ... { - * permission permission_class_name [ "target_name" ] [, "action"] - * [, SignedBy "signer_names"]; - * permission ... - * }; - * - * </pre> - * - * The <i>keystore </i> clause specifies reference to a keystore, which is a - * database of private keys and their associated digital certificates. The - * keystore is used to look up the certificates of signers specified in the - * <i>grant </i> entries of the file. The policy file can contain any number of - * <i>keystore </i> entries which can appear at any ordinal position. However, - * only the first successfully loaded keystore is used, others are ignored. The - * keystore must be specified if some grant clause refers to a certificate's - * alias. <br> - * The <i>grant </i> clause associates a CodeSource (consisting of an URL and a - * set of certificates) of some executable code with a set of Permissions which - * should be granted to the code. So, the CodeSource is defined by values of - * <i>CodeBase </i> and <i>SignedBy </i> fields. The <i>CodeBase </i> value must - * be in URL format, while <i>SignedBy </i> value is a (comma-separated list of) - * alias(es) to keystore certificates. These fields can be omitted to denote any - * codebase and any signers (including case of unsigned code), respectively. - * <br> - * Also, the code may be required to be executed on behalf of some Principals - * (in other words, code's ProtectionDomain must have the array of Principals - * associated) in order to possess the Permissions. This fact is indicated by - * specifying one or more <i>Principal </i> fields in the <i>grant </i> clause. - * Each Principal is specified as class/name pair; name and class can be either - * concrete value or wildcard <i>* </i>. As a special case, the class value may - * be omitted and then the name is treated as an alias to X.509 Certificate, and - * the Principal is assumed to be javax.security.auth.x500.X500Principal with a - * name of subject's distinguished name from the certificate. <br> - * The order between the <i>CodeBase </i>, <i>SignedBy </i>, and <i>Principal - * </i> fields does not matter. The policy file can contain any number of grant - * clauses. <br> - * Each <i>grant </i> clause must contain one or more <i>permission </i> entry. - * The permission entry consist of a fully qualified class name along with - * optional <i>name </i>, <i>actions </i> and <i>signedby </i> values. Name and - * actions are arguments to the corresponding constructor of the permission - * class. SignedBy value represents the keystore alias(es) to certificate(s) - * used to sign the permission class. That is, this permission entry is - * effective (i.e., access control permission will be granted based on this - * entry) only if the bytecode implementation of permission class is verified to - * be correctly signed by the said alias(es). <br> - * <br> - * The policy content may be parameterized via property expansion. Namely, - * expressions like <i>${key} </i> are replaced by values of corresponding - * system properties. Also, the special <i>slash </i> key (i.e. ${/}) is - * supported, it is a shortcut to "file.separator" key. Property - * expansion is performed anywhere a double quoted string is allowed in the - * policy file. However, this feature is controlled by security properties and - * should be turned on by setting "policy.expandProperties" property - * to <i>true </i>. <br> - * If property expansion fails (due to a missing key), a corresponding entry is - * ignored. For fields of <i>keystore </i> and <i>grant </i> clauses, the whole - * clause is ignored, and for <i>permission </i> entry, only that entry is - * ignored. <br> - * <br> - * The policy also supports generalized expansion in permissions names, of - * expressions like <i>${{protocol:data}} </i>. Currently the following - * protocols supported: - * <dl> - * <dt>self - * <dd>Denotes substitution to a principal information of the parental Grant - * entry. Replaced by a space-separated list of resolved Principals (including - * wildcarded), each formatted as <i>class "name" </i>. If parental - * Grant entry has no Principals, the permission is ignored. - * <dt>alias: <i>name </i> - * <dd>Denotes substitution of a KeyStore alias. Namely, if a KeyStore has an - * X.509 certificate associated with the specified name, then replaced by - * <i>javax.security.auth.x500.X500Principal " <i>DN </i>" </i> - * string, where <i>DN </i> is a certificate's subject distinguished name. - * </dl> - * <br> - * <br> - * This implementation is thread-safe. The policy caches sets of calculated - * permissions for the requested objects (ProtectionDomains and CodeSources) via - * WeakHashMap; the cache is cleaned either explicitly during refresh() - * invocation, or naturally by garbage-collecting the corresponding objects. - * - * @see org.apache.harmony.security.fortress.PolicyUtils#getPolicyURLs( - * Properties, String, String) - */ - -public class DefaultPolicy extends Policy { - - /** - * System property for dynamically added policy location. - */ - public static final String JAVA_SECURITY_POLICY = "java.security.policy"; - - /** - * Prefix for numbered Policy locations specified in security.properties. - */ - public static final String POLICY_URL_PREFIX = "policy.url."; - - // A set of PolicyEntries constituting this Policy. - private final Set<PolicyEntry> grants = new HashSet<PolicyEntry>(); - - // Calculated Permissions cache, organized as - // Map{Object->Collection<Permission>}. - // The Object is a ProtectionDomain, a CodeSource or - // any other permissions-granted entity. - private final Map<Object, Collection<Permission>> cache = new WeakHashMap<Object, Collection<Permission>>(); - - // A specific parser for a particular policy file format. - private final DefaultPolicyParser parser; - - // A flag indicating brand new instance which needs to be loaded - // on the first appeal to it's data. - private boolean initialized; - - /** - * Default constructor, equivalent to - * <code>DefaultPolicy(new DefaultPolicyParser())</code>. - */ - public DefaultPolicy() { - this(new DefaultPolicyParser()); - } - - /** - * Extension constructor for plugging-in a custom parser. Defers policy data - * initialization before the first <code>getPermissions()</code> call - * (though policy may be refreshed explicitly, as well). - */ - public DefaultPolicy(DefaultPolicyParser dpr) { - parser = dpr; - initialized = false; - refresh(); - } - - /** - * Returns collection of permissions allowed for the domain - * according to the policy. The evaluated characteristics of the - * domain are it's codesource and principals; they are assumed - * to be <code>null</code> if the domain is <code>null</code>. - */ - public PermissionCollection getPermissions(ProtectionDomain pd) { - if (!initialized) { - synchronized (this) { - if (!initialized) { - refresh(); - } - } - } - Collection<Permission> pc = cache.get(pd); - if (pc == null) { - //have to synchronize to exclude cache pollution after refresh - synchronized (cache) { - - // double check in case value has been put to cache - // while we've been awaiting monitor - pc = cache.get(pd); - if (pc == null) { - pc = new HashSet<Permission>(); - Iterator<PolicyEntry> it = grants.iterator(); - while (it.hasNext()) { - PolicyEntry ge = it.next(); - if (ge.impliesPrincipals(pd == null ? null : pd.getPrincipals()) - && ge.impliesCodeSource(pd == null ? null : pd.getCodeSource())) { - pc.addAll(ge.getPermissions()); - } - } - cache.put(pd, pc); - } - } - } - return PolicyUtils.toPermissionCollection(pc); - - } - - /** - * Returns collection of permissions allowed for the codesource - * according to the policy. - * The evaluation assumes that current principals are undefined. - */ - public PermissionCollection getPermissions(CodeSource cs) { - if (!initialized) { - synchronized (this) { - if (!initialized) { - refresh(); - } - } - } - Collection<Permission> pc = cache.get(cs); - if (pc == null) { - //have to synchronize to exclude cache pollution after refresh - synchronized (cache) { - - // double check in case value has been put to cache - // while we've been awaiting monitor - pc = cache.get(cs); - if (pc == null) { - pc = new HashSet<Permission>(); - Iterator<PolicyEntry> it = grants.iterator(); - while (it.hasNext()) { - PolicyEntry ge = it.next(); - if (ge.impliesPrincipals(null) && ge.impliesCodeSource(cs)) { - pc.addAll(ge.getPermissions()); - } - } - cache.put(cs, pc); - } - } - } - return PolicyUtils.toPermissionCollection(pc); - } - - /** - * Gets fresh list of locations and tries to load all of them in sequence; - * failed loads are ignored. After processing all locations, old policy - * settings are discarded and new ones come into force. <br> - * This method is declared synchronized to avoid concurrent reloading. - * - * @see PolicyUtils#getPolicyURLs(Properties, String, String) - */ - public synchronized void refresh() { - Set<PolicyEntry> fresh = new HashSet<PolicyEntry>(); - Properties system = System.getProperties(); - system.setProperty("/", File.separator); - URL[] policyLocations = PolicyUtils.getPolicyURLs(system, - JAVA_SECURITY_POLICY, - POLICY_URL_PREFIX); - for (int i = 0; i < policyLocations.length; i++) { - try { - //TODO debug log - //System.err.println("Parsing policy file: " + policyLocations[i]); - fresh.addAll(parser.parse(policyLocations[i], system)); - } catch (Exception e) { - // TODO log warning - //System.err.println("Ignoring policy file: " - // + policyLocations[i] + ". Reason:\n"+ e); - } - } - // XXX: what if new policy is empty - provide some default?? - - // we could safely replace references instead of - // synchronizing access: - // <pre> - // grants = fresh; - // cache = new WeakHashMap(); - // </pre> - // but there is possibility that concurrent thread will put - // old data to cache right after we finish refresh(), - // thus synchronization is added in getPermissions() methods... - synchronized (cache) { - grants.clear(); - grants.addAll(fresh); - - cache.clear(); - } - initialized = true; - } -} diff --git a/luni/src/main/java/org/apache/harmony/security/fortress/DefaultPolicyParser.java b/luni/src/main/java/org/apache/harmony/security/fortress/DefaultPolicyParser.java deleted file mode 100644 index 7f55e6f..0000000 --- a/luni/src/main/java/org/apache/harmony/security/fortress/DefaultPolicyParser.java +++ /dev/null @@ -1,464 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** -* @author Alexey V. Varlamov -* @version $Revision$ -*/ - -package org.apache.harmony.security.fortress; - -import java.io.BufferedReader; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.net.URL; -import java.security.CodeSource; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.Permission; -import java.security.Principal; -import java.security.UnresolvedPermission; -import java.security.cert.Certificate; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Properties; -import java.util.Set; -import org.apache.harmony.security.DefaultPolicyScanner; -import org.apache.harmony.security.DefaultPolicyScanner.GrantEntry; -import org.apache.harmony.security.DefaultPolicyScanner.KeystoreEntry; -import org.apache.harmony.security.DefaultPolicyScanner.PermissionEntry; -import org.apache.harmony.security.DefaultPolicyScanner.PrincipalEntry; -import org.apache.harmony.security.PolicyEntry; -import org.apache.harmony.security.UnresolvedPrincipal; - -/** - * This is a basic loader of policy files. It delegates lexical analysis to - * a pluggable scanner and converts received tokens to a set of - * {@link org.apache.harmony.security.PolicyEntry PolicyEntries}. - * For details of policy format, see the - * {@link org.apache.harmony.security.DefaultPolicy default policy description}. - * <br> - * For ordinary uses, this class has just one public method <code>parse()</code>, - * which performs the main task. - * Extensions of this parser may redefine specific operations separately, - * by overriding corresponding protected methods. - * <br> - * This implementation is effectively thread-safe, as it has no field references - * to data being processed (that is, passes all the data as method parameters). - * - * @see org.apache.harmony.security.DefaultPolicy - * @see org.apache.harmony.security.DefaultPolicyScanner - * @see org.apache.harmony.security.PolicyEntry - */ -public class DefaultPolicyParser { - - // Pluggable scanner for a specific file format - private final DefaultPolicyScanner scanner; - - /** - * Default constructor, - * {@link org.apache.harmony.security.DefaultPolicyScanner DefaultPolicyScanner} - * is used. - */ - public DefaultPolicyParser() { - scanner = new DefaultPolicyScanner(); - } - - /** - * Extension constructor for plugging-in custom scanner. - */ - public DefaultPolicyParser(DefaultPolicyScanner s) { - this.scanner = s; - } - - /** - * This is the main business method. It manages loading process as follows: - * the associated scanner is used to parse the stream to a set of - * {@link org.apache.harmony.security.DefaultPolicyScanner.GrantEntry composite tokens}, - * then this set is iterated and each token is translated to a PolicyEntry. - * Semantically invalid tokens are ignored, the same as void PolicyEntries. - * <br> - * A policy file may refer to some KeyStore(s), and in this case the first - * valid reference is initialized and used in processing tokens. - * - * @param location an URL of a policy file to be loaded - * @param system system properties, used for property expansion - * @return a collection of PolicyEntry objects, may be empty - * @throws Exception IO error while reading location or file syntax error - */ - public Collection<PolicyEntry>parse(URL location, Properties system) throws Exception { - boolean resolve = PolicyUtils.canExpandProperties(); - Reader r = new BufferedReader(new InputStreamReader(location.openStream())); - - Collection<GrantEntry> grantEntries = new HashSet<GrantEntry>(); - List<KeystoreEntry> keystores = new ArrayList<KeystoreEntry>(); - - try { - scanner.scanStream(r, grantEntries, keystores); - } - finally { - r.close(); - } - - //XXX KeyStore could be loaded lazily... - KeyStore ks = initKeyStore(keystores, location, system, resolve); - - Collection<PolicyEntry> result = new HashSet<PolicyEntry>(); - for (Iterator<GrantEntry> iter = grantEntries.iterator(); iter.hasNext();) { - DefaultPolicyScanner.GrantEntry ge = iter - .next(); - try { - PolicyEntry pe = resolveGrant(ge, ks, system, resolve); - if (!pe.isVoid()) { - result.add(pe); - } - } - catch (Exception e) { - // TODO: log warning - } - } - - return result; - } - - /** - * Translates GrantEntry token to PolicyEntry object. It goes step by step, - * trying to resolve each component of the GrantEntry: - * <ul> - * <li> If <code>codebase</code> is specified, expand it and construct an URL. - * <li> If <code>signers</code> is specified, expand it and obtain - * corresponding Certificates. - * <li> If <code>principals</code> collection is specified, iterate over it. - * For each PrincipalEntry, expand name and if no class specified, - * resolve actual X500Principal from a KeyStore certificate; otherwise keep it - * as UnresolvedPrincipal. - * <li> Iterate over <code>permissions</code> collection. For each PermissionEntry, - * try to resolve (see method - * {@link #resolvePermission(DefaultPolicyScanner.PermissionEntry, DefaultPolicyScanner.GrantEntry, KeyStore, Properties, boolean) resolvePermission()}) - * a corresponding permission. If resolution failed, ignore the PermissionEntry. - * </ul> - * In fact, property expansion in the steps above is conditional and is ruled by - * the parameter <i>resolve</i>. - * <br> - * Finally a new PolicyEntry is created, which associates the trinity - * of resolved URL, Certificates and Principals to a set of granted Permissions. - * - * @param ge GrantEntry token to be resolved - * @param ks KeyStore for resolving Certificates, may be <code>null</code> - * @param system system properties, used for property expansion - * @param resolve flag enabling/disabling property expansion - * @return resolved PolicyEntry - * @throws Exception if unable to resolve codebase, signers or principals - * of the GrantEntry - * @see DefaultPolicyScanner.PrincipalEntry - * @see DefaultPolicyScanner.PermissionEntry - * @see org.apache.harmony.security.PolicyUtils - */ - protected PolicyEntry resolveGrant(DefaultPolicyScanner.GrantEntry ge, - KeyStore ks, Properties system, boolean resolve) throws Exception { - - URL codebase = null; - Certificate[] signers = null; - Set<Principal>principals = new HashSet<Principal>(); - Set<Permission>permissions = new HashSet<Permission>(); - if (ge.codebase != null) { - codebase = new URL(resolve ? PolicyUtils.expandURL(ge.codebase, - system) : ge.codebase); - } - if (ge.signers != null) { - if (resolve) { - ge.signers = PolicyUtils.expand(ge.signers, system); - } - signers = resolveSigners(ks, ge.signers); - } - if (ge.principals != null) { - for (Iterator<PrincipalEntry> iter = ge.principals.iterator(); iter.hasNext();) { - DefaultPolicyScanner.PrincipalEntry pe = iter - .next(); - if (resolve) { - pe.name = PolicyUtils.expand(pe.name, system); - } - if (pe.klass == null) { - principals.add(getPrincipalByAlias(ks, pe.name)); - } else { - principals.add(new UnresolvedPrincipal(pe.klass, pe.name)); - } - } - } - if (ge.permissions != null) { - for (Iterator<PermissionEntry> iter = ge.permissions.iterator(); iter.hasNext();) { - DefaultPolicyScanner.PermissionEntry pe = iter - .next(); - try { - permissions.add(resolvePermission(pe, ge, ks, system, - resolve)); - } - catch (Exception e) { - // TODO: log warning - } - } - } - return new PolicyEntry(new CodeSource(codebase, signers), principals, - permissions); - } - - /** - * Translates PermissionEntry token to Permission object. - * First, it performs general expansion for non-null <code>name</code> and - * properties expansion for non-null <code>name</code>, <code>action</code> - * and <code>signers</code>. - * Then, it obtains signing Certificates(if any), tries to find a class specified by - * <code>klass</code> name and instantiate a corresponding permission object. - * If class is not found or it is signed improperly, returns UnresolvedPermission. - * - * @param pe PermissionEntry token to be resolved - * @param ge parental GrantEntry of the PermissionEntry - * @param ks KeyStore for resolving Certificates, may be <code>null</code> - * @param system system properties, used for property expansion - * @param resolve flag enabling/disabling property expansion - * @return resolved Permission object, either of concrete class or UnresolvedPermission - * @throws Exception if failed to expand properties, - * or to get a Certificate, - * or to create an instance of a successfully found class - */ - protected Permission resolvePermission( - DefaultPolicyScanner.PermissionEntry pe, - DefaultPolicyScanner.GrantEntry ge, KeyStore ks, Properties system, - boolean resolve) throws Exception { - if (pe.name != null) { - pe.name = PolicyUtils.expandGeneral(pe.name, - new PermissionExpander().configure(ge, ks)); - } - if (resolve) { - if (pe.name != null) { - pe.name = PolicyUtils.expand(pe.name, system); - } - if (pe.actions != null) { - pe.actions = PolicyUtils.expand(pe.actions, system); - } - if (pe.signers != null) { - pe.signers = PolicyUtils.expand(pe.signers, system); - } - } - Certificate[] signers = (pe.signers == null) ? null : resolveSigners( - ks, pe.signers); - try { - Class<?> klass = Class.forName(pe.klass); - if (PolicyUtils.matchSubset(signers, klass.getSigners())) { - return PolicyUtils.instantiatePermission(klass, pe.name, - pe.actions); - } - } - catch (ClassNotFoundException cnfe) {} - //maybe properly signed class will be loaded later - return new UnresolvedPermission(pe.klass, pe.name, pe.actions, signers); - } - - /** - * Specific handler for expanding <i>self</i> and <i>alias</i> protocols. - */ - class PermissionExpander implements PolicyUtils.GeneralExpansionHandler { - - // Store KeyStore - private KeyStore ks; - - // Store GrantEntry - private DefaultPolicyScanner.GrantEntry ge; - - /** - * Combined setter of all required fields. - */ - public PermissionExpander configure(DefaultPolicyScanner.GrantEntry ge, - KeyStore ks) { - this.ge = ge; - this.ks = ks; - return this; - } - - /** - * Resolves the following protocols: - * <dl> - * <dt>self - * <dd>Denotes substitution to a principal information of the parental - * GrantEntry. Returns a space-separated list of resolved Principals - * (including wildcarded), formatting each as <b>class "name"</b>. - * If parental GrantEntry has no Principals, throws ExpansionFailedException. - * <dt>alias:<i>name</i> - * <dd>Denotes substitution of a KeyStore alias. Namely, if a KeyStore has - * an X.509 certificate associated with the specified name, then returns - * <b>javax.security.auth.x500.X500Principal "<i>DN</i>"</b> string, - * where <i>DN</i> is a certificate's subject distinguished name. - * </dl> - * @throws ExpansionFailedException - if protocol is other than - * <i>self</i> or <i>alias</i>, or if data resolution failed - */ - public String resolve(String protocol, String data) - throws PolicyUtils.ExpansionFailedException { - - if ("self".equals(protocol)) { - //need expanding to list of principals in grant clause - if (ge.principals != null && ge.principals.size() != 0) { - StringBuilder sb = new StringBuilder(); - for (Iterator<PrincipalEntry> iter = ge.principals.iterator(); iter - .hasNext();) { - DefaultPolicyScanner.PrincipalEntry pr = iter - .next(); - if (pr.klass == null) { - // aliased X500Principal - try { - sb.append(pc2str(getPrincipalByAlias(ks, - pr.name))); - } - catch (Exception e) { - throw new PolicyUtils.ExpansionFailedException("Error expanding alias: " + pr.name, e); - } - } else { - sb.append(pr.klass).append(" \"").append(pr.name) - .append("\" "); - } - } - return sb.toString(); - } else { - throw new PolicyUtils.ExpansionFailedException("Self protocol is valid only in context of Principal-based grant entries"); - } - } - if ("alias".equals(protocol)) { - try { - return pc2str(getPrincipalByAlias(ks, data)); - } catch (Exception e) { - throw new PolicyUtils.ExpansionFailedException("Error expanding alias: " + data, e); - } - } - throw new PolicyUtils.ExpansionFailedException("Unknown expansion protocol: " + protocol); - } - - // Formats a string describing the passed Principal. - private String pc2str(Principal pc) { - String klass = pc.getClass().getName(); - String name = pc.getName(); - StringBuilder sb = new StringBuilder(klass.length() + name.length() - + 5); - return sb.append(klass).append(" \"").append(name).append("\"") - .toString(); - } - } - - /** - * Takes a comma-separated list of aliases and obtains corresponding - * certificates. - * @param ks KeyStore for resolving Certificates, may be <code>null</code> - * @param signers comma-separated list of certificate aliases, - * must be not <code>null</code> - * @return an array of signing Certificates - * @throws Exception if KeyStore is <code>null</code> - * or if it failed to provide a certificate - */ - protected Certificate[] resolveSigners(KeyStore ks, String signers) throws Exception { - if (ks == null) { - throw new KeyStoreException("No KeyStore to resolve signers: " + signers); - } - - Collection<Certificate> certs = new HashSet<Certificate>(); - for (String signer : signers.split(",")) { - //XXX cache found certs ?? - certs.add(ks.getCertificate(signer.trim())); - } - return certs.toArray(new Certificate[certs.size()]); - } - - /** - * Returns a subject's X500Principal of an X509Certificate, - * which is associated with the specified keystore alias. - * @param ks KeyStore for resolving Certificate, may be <code>null</code> - * @param alias alias to a certificate - * @return X500Principal with a subject distinguished name - * @throws KeyStoreException if KeyStore is <code>null</code> - * or if it failed to provide a certificate - * @throws CertificateException if found certificate is not - * an X509Certificate - */ - protected Principal getPrincipalByAlias(KeyStore ks, String alias) - throws KeyStoreException, CertificateException { - - if (ks == null) { - throw new KeyStoreException("No KeyStore to resolve principal by alias: " + alias); - } - //XXX cache found certs ?? - Certificate x509 = ks.getCertificate(alias); - if (x509 instanceof X509Certificate) { - return ((X509Certificate) x509).getSubjectX500Principal(); - } else { - throw new CertificateException("Invalid certificate for alias '" + alias + "': " + - x509 + ". Only X509Certificate should be aliased to principals."); - } - } - - /** - * Returns the first successfully loaded KeyStore, from the specified list of - * possible locations. This method iterates over the list of KeystoreEntries; - * for each entry expands <code>url</code> and <code>type</code>, - * tries to construct instances of specified URL and KeyStore and to load - * the keystore. If it is loaded, returns the keystore, otherwise proceeds to - * the next KeystoreEntry. - * <br> - * <b>Note:</b> an url may be relative to the policy file location or absolute. - * @param keystores list of available KeystoreEntries - * @param base the policy file location - * @param system system properties, used for property expansion - * @param resolve flag enabling/disabling property expansion - * @return the first successfully loaded KeyStore or <code>null</code> - */ - protected KeyStore initKeyStore(List<KeystoreEntry>keystores, - URL base, Properties system, boolean resolve) { - - for (int i = 0; i < keystores.size(); i++) { - try { - DefaultPolicyScanner.KeystoreEntry ke = keystores - .get(i); - if (resolve) { - ke.url = PolicyUtils.expandURL(ke.url, system); - if (ke.type != null) { - ke.type = PolicyUtils.expand(ke.type, system); - } - } - if (ke.type == null || ke.type.length() == 0) { - ke.type = KeyStore.getDefaultType(); - } - KeyStore ks = KeyStore.getInstance(ke.type); - URL location = new URL(base, ke.url); - InputStream is = location.openStream(); - try { - ks.load(is, null); - } - finally { - is.close(); - } - return ks; - } - catch (Exception e) { - // TODO: log warning - } - } - return null; - } -} diff --git a/luni/src/main/java/org/apache/harmony/security/fortress/PolicyUtils.java b/luni/src/main/java/org/apache/harmony/security/fortress/PolicyUtils.java deleted file mode 100644 index c22314b..0000000 --- a/luni/src/main/java/org/apache/harmony/security/fortress/PolicyUtils.java +++ /dev/null @@ -1,461 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** -* @author Alexey V. Varlamov -* @version $Revision$ -*/ - -package org.apache.harmony.security.fortress; - -import java.io.File; -import java.io.InputStream; -import java.lang.reflect.Constructor; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; -import java.security.Permission; -import java.security.PermissionCollection; -import java.security.Permissions; -import java.security.Security; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.Properties; - -/** - * This class consist of a number of static methods, which provide a common functionality - * for various policy and configuration providers. - * - */ -public class PolicyUtils { - - // No reason to instantiate - private PolicyUtils() {} - - /** - * Specific exception to signal that property expansion failed - * due to unknown key. - */ - public static class ExpansionFailedException extends Exception { - - /** - * @serial - */ - private static final long serialVersionUID = 2869748055182612000L; - - /** - * Constructor with user-friendly message parameter. - */ - public ExpansionFailedException(String message) { - super(message); - } - - /** - * Constructor with user-friendly message and causing error. - */ - public ExpansionFailedException(String message, Throwable cause) { - super(message, cause); - } - } - - /** - * Substitutes all entries like ${some.key}, found in specified string, - * for specified values. - * If some key is unknown, throws ExpansionFailedException. - * @param str the string to be expanded - * @param properties available key-value mappings - * @return expanded string - * @throws ExpansionFailedException - */ - public static String expand(String str, Properties properties) - throws ExpansionFailedException { - final String START_MARK = "${"; - final String END_MARK = "}"; - final int START_OFFSET = START_MARK.length(); - final int END_OFFSET = END_MARK.length(); - - StringBuilder result = new StringBuilder(str); - int start = result.indexOf(START_MARK); - while (start >= 0) { - int end = result.indexOf(END_MARK, start); - if (end >= 0) { - String key = result.substring(start + START_OFFSET, end); - String value = properties.getProperty(key); - if (value != null) { - result.replace(start, end + END_OFFSET, value); - start += value.length(); - } else { - throw new ExpansionFailedException("Unknown key: " + key); - } - } - start = result.indexOf(START_MARK, start); - } - return result.toString(); - } - - /** - * Handy shortcut for - * <code>expand(str, properties).replace(File.separatorChar, '/')</code>. - * @see #expand(String, Properties) - */ - public static String expandURL(String str, Properties properties) - throws ExpansionFailedException { - return expand(str, properties).replace(File.separatorChar, '/'); - } - - /** - * Normalizes URLs to standard ones, eliminating pathname symbols. - * - * @param codebase - - * the original URL. - * @return - the normalized URL. - */ - public static URL normalizeURL(URL codebase) { - if (codebase != null && "file".equals(codebase.getProtocol())) { - try { - if (codebase.getHost().length() == 0) { - String path = codebase.getFile(); - - if (path.length() == 0) { - // codebase is "file:" - path = "*"; - } - return filePathToURI(new File(path) - .getAbsolutePath()).normalize().toURL(); - } else { - // codebase is "file://<smth>" - return codebase.toURI().normalize().toURL(); - } - } catch (Exception e) { - // Ignore - } - } - return codebase; - } - - /** - * Converts a file path to URI without accessing file system - * (like {File#toURI()} does). - * - * @param path - - * file path. - * @return - the resulting URI. - * @throw URISyntaxException - */ - public static URI filePathToURI(String path) throws URISyntaxException { - path = path.replace(File.separatorChar, '/'); - - if (!path.startsWith("/")) { - return new URI("file", null, - new StringBuilder(path.length() + 1).append('/') - .append(path).toString(), null, null); - } - return new URI("file", null, path, null, null); - } - - /** - * Instances of this interface are intended for resolving - * generalized expansion expressions, of the form ${{protocol:data}}. - * Such functionality is applicable to security policy files, for example. - * @see #expandGeneral(String, GeneralExpansionHandler) - */ - public static interface GeneralExpansionHandler { - - /** - * Resolves general expansion expressions of the form ${{protocol:data}}. - * @param protocol denotes type of resolution - * @param data data to be resolved, optional (may be null) - * @return resolved value, must not be null - * @throws PolicyUtils.ExpansionFailedException if expansion is impossible - */ - String resolve(String protocol, String data) - throws ExpansionFailedException; - } - - /** - * Substitutes all entries like ${{protocol:data}}, found in specified string, - * for values resolved by passed handler. - * The data part may be empty, and in this case expression - * may have simplified form, as ${{protocol}}. - * If some entry cannot be resolved, throws ExpansionFailedException; - * @param str the string to be expanded - * @param handler the handler to resolve data denoted by protocol - * @return expanded string - * @throws ExpansionFailedException - */ - public static String expandGeneral(String str, - GeneralExpansionHandler handler) throws ExpansionFailedException { - final String START_MARK = "${{"; - final String END_MARK = "}}"; - final int START_OFFSET = START_MARK.length(); - final int END_OFFSET = END_MARK.length(); - - StringBuilder result = new StringBuilder(str); - int start = result.indexOf(START_MARK); - while (start >= 0) { - int end = result.indexOf(END_MARK, start); - if (end >= 0) { - String key = result.substring(start + START_OFFSET, end); - int separator = key.indexOf(':'); - String protocol = (separator >= 0) ? key - .substring(0, separator) : key; - String data = (separator >= 0) ? key.substring(separator + 1) - : null; - String value = handler.resolve(protocol, data); - result.replace(start, end + END_OFFSET, value); - start += value.length(); - } - start = result.indexOf(START_MARK, start); - } - return result.toString(); - } - - /** - * A key to security properties, deciding whether usage of - * dynamic policy location via system properties is allowed. - * @see #getPolicyURLs(Properties, String, String) - */ - public static final String POLICY_ALLOW_DYNAMIC = "policy.allowSystemProperty"; - - /** - * A key to security properties, deciding whether expansion of - * system properties is allowed - * (in security properties values, policy files, etc). - * @see #expand(String, Properties) - */ - public static final String POLICY_EXPAND = "policy.expandProperties"; - - /** - * Positive value of switching properties. - */ - public static final String TRUE = "true"; - - /** - * Negative value of switching properties. - */ - public static final String FALSE = "false"; - - /** - * Returns false if current security settings disable to perform - * properties expansion, true otherwise. - * @see #expand(String, Properties) - */ - public static boolean canExpandProperties() { - return !Security.getProperty(POLICY_EXPAND).equalsIgnoreCase(FALSE); - } - - /** - * Obtains a list of locations for a policy or configuration provider. - * The search algorithm is as follows: - * <ol> - * <li> Look in security properties for keys of form <code>prefix + n</code>, - * where <i>n</i> is an integer and <i>prefix</i> is a passed parameter. - * Sequence starts with <code>n=1</code>, and keeps incrementing <i>n</i> - * until next key is not found. <br> - * For each obtained key, try to construct an URL instance. On success, - * add the URL to the list; otherwise ignore it. - * <li> - * If security settings do not prohibit (through - * {@link #POLICY_ALLOW_DYNAMIC the "policy.allowSystemProperty" property}) - * to use additional policy location, read the system property under the - * passed key parameter. If property exists, it may designate a file or - * an absolute URL. Thus, first check if there is a file with that name, - * and if so, convert the pathname to URL. Otherwise, try to instantiate - * an URL directly. If succeeded, append the URL to the list - * <li> - * If the additional location from the step above was specified to the - * system via "==" (i.e. starts with '='), discard all URLs above - * and use this only URL. - * </ol> - * <b>Note:</b> all property values (both security and system) related to URLs are - * subject to {@link #expand(String, Properties) property expansion}, regardless - * of the "policy.expandProperties" security setting. - * - * @param system system properties - * @param systemUrlKey key to additional policy location - * @param securityUrlPrefix prefix to numbered locations in security properties - * @return array of URLs to provider's configuration files, may be empty. - */ - public static URL[] getPolicyURLs(final Properties system, - final String systemUrlKey, final String securityUrlPrefix) { - - final List<URL> urls = new ArrayList<URL>(); - boolean dynamicOnly = false; - URL dynamicURL = null; - - //first check if policy is set via system properties - if (!Security.getProperty(POLICY_ALLOW_DYNAMIC).equalsIgnoreCase(FALSE)) { - String location = system.getProperty(systemUrlKey); - if (location != null) { - if (location.startsWith("=")) { - //overrides all other urls - dynamicOnly = true; - location = location.substring(1); - } - try { - location = expandURL(location, system); - // location can be a file, but we need an url... - final File f = new File(location); - dynamicURL = null; - if (f.exists()) { - dynamicURL = f.toURI().toURL(); - } - if (dynamicURL == null) { - dynamicURL = new URL(location); - } - } - catch (Exception e) { - // TODO: log error - // System.err.println("Error detecting system policy location: "+e); - } - } - } - //next read urls from security.properties - if (!dynamicOnly) { - int i = 1; - while (true) { - String location = Security.getProperty(securityUrlPrefix + (i++)); - if (location == null) { - break; - } - try { - location = expandURL(location, system); - URL anURL = new URL(location); - if (anURL != null) { - urls.add(anURL); - } - } - catch (Exception e) { - // TODO: log error - // System.err.println("Error detecting security policy location: "+e); - } - } - } - if (dynamicURL != null) { - urls.add(dynamicURL); - } - return urls.toArray(new URL[urls.size()]); - } - - /** - * Converts common-purpose collection of Permissions to PermissionCollection. - * - * @param perms a collection containing arbitrary permissions, may be null - * @return mutable heterogeneous PermissionCollection containing all Permissions - * from the specified collection - */ - public static PermissionCollection toPermissionCollection( - Collection<Permission> perms) { - Permissions pc = new Permissions(); - if (perms != null) { - for (Iterator<Permission> iter = perms.iterator(); iter.hasNext();) { - Permission element = iter.next(); - pc.add(element); - } - } - return pc; - } - - // Empty set of arguments to default constructor of a Permission. - private static final Class[] NO_ARGS = {}; - - // One-arg set of arguments to default constructor of a Permission. - private static final Class[] ONE_ARGS = { String.class }; - - // Two-args set of arguments to default constructor of a Permission. - private static final Class[] TWO_ARGS = { String.class, String.class }; - - /** - * Tries to find a suitable constructor and instantiate a new Permission - * with specified parameters. - * - * @param targetType class of expected Permission instance - * @param targetName name of expected Permission instance - * @param targetActions actions of expected Permission instance - * @return a new Permission instance - * @throws IllegalArgumentException if no suitable constructor found - * @throws Exception any exception thrown by Constructor.newInstance() - */ - public static Permission instantiatePermission(Class<?> targetType, - String targetName, String targetActions) throws Exception { - - // let's guess the best order for trying constructors - Class[][] argTypes = null; - Object[][] args = null; - if (targetActions != null) { - argTypes = new Class[][] { TWO_ARGS, ONE_ARGS, NO_ARGS }; - args = new Object[][] { { targetName, targetActions }, - { targetName }, {} }; - } else if (targetName != null) { - argTypes = new Class[][] { ONE_ARGS, TWO_ARGS, NO_ARGS }; - args = new Object[][] { { targetName }, - { targetName, targetActions }, {} }; - } else { - argTypes = new Class[][] { NO_ARGS, ONE_ARGS, TWO_ARGS }; - args = new Object[][] { {}, { targetName }, - { targetName, targetActions } }; - } - - // finally try to instantiate actual permission - for (int i = 0; i < argTypes.length; i++) { - try { - Constructor<?> ctor = targetType.getConstructor(argTypes[i]); - return (Permission)ctor.newInstance(args[i]); - } - catch (NoSuchMethodException ignore) {} - } - throw new IllegalArgumentException("No suitable constructors found in permission class " + - targetType + ". Zero, one or two-argument constructor is expected"); - } - - /** - * Checks whether the objects from <code>what</code> array are all - * presented in <code>where</code> array. - * - * @param what first array, may be <code>null</code> - * @param where second array, may be <code>null</code> - * @return <code>true</code> if the first array is <code>null</code> - * or if each and every object (ignoring null values) - * from the first array has a twin in the second array; <code>false</code> otherwise - */ - public static boolean matchSubset(Object[] what, Object[] where) { - if (what == null) { - return true; - } - - for (int i = 0; i < what.length; i++) { - if (what[i] != null) { - if (where == null) { - return false; - } - boolean found = false; - for (int j = 0; j < where.length; j++) { - if (what[i].equals(where[j])) { - found = true; - break; - } - } - if (!found) { - return false; - } - } - } - return true; - } -} diff --git a/luni/src/main/java/org/apache/harmony/security/fortress/SecurityUtils.java b/luni/src/main/java/org/apache/harmony/security/fortress/SecurityUtils.java deleted file mode 100644 index c63a57d..0000000 --- a/luni/src/main/java/org/apache/harmony/security/fortress/SecurityUtils.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** -* @author Alexander V. Astapchuk -* @version $Revision$ -*/ - -package org.apache.harmony.security.fortress; - -import java.security.AccessControlContext; -import java.util.WeakHashMap; - -/** - * The class is used to perform an exchange of information between - * java.lang.Thread and java.security.AccessController.<br> - * The data to exchange is inherited contexts for the Threads. - */ -public final class SecurityUtils { - - // A map used to store inherited contexts.<br> - // A thread is used as a key for the map and AccessControlContext - // passed to the putContext is used as a value. - private static final WeakHashMap<Thread, AccessControlContext> ACC_CACHE = new WeakHashMap<Thread, AccessControlContext>(); - - /** - * This method to be invoked in the Thread's constructor. The first argument - * (thread) must be Thread's this and the second must be a snapshot of the - * current AccessControlContext: - * <p> - * <code> - * Thread() {<br> - * SecurityUtils.putContext(this,AccessController.getContext());<br> - * ...do the stuff you need...<br> - * }<br> - * </code> - * - * The method throws SecurityException if the method is called more than - * once for a given thread. The first call to <code>putContext</code> is - * always performed in the Thread's constructor so this effectively means - * that no one can replace the snapshot taken. - * - * @throws SecurityException if a context for the passed - * <code>thread</code> already exists in the map. - * @throws NullPointerException if thread is null - * @throws Error if context is null AND if null context is already stored - * in the map - */ - public static void putContext(Thread thread, AccessControlContext context) - throws SecurityException { - if (thread == null) { - throw new NullPointerException(); - } - synchronized (ACC_CACHE) { - if (ACC_CACHE.containsKey(thread)) { - throw new SecurityException("You can not modify this map"); - } - if (context == null) { - // this only allowed once - for the very first thread. - if (ACC_CACHE.containsValue(null)) { - throw new Error("null context may be stored only once"); - } - } - ACC_CACHE.put(thread, context); - } - } - - /** - * Returns the AccessControlContext stored for a given thread.<br> - * The method may return null - for the very first thread created - * by the VM which does not have inherited context.<br> - * It may also return null if no Thread found in the map - that seems - * possible during VM startup process. - */ - public static AccessControlContext getContext(Thread thread) throws SecurityException { - synchronized (ACC_CACHE) { - return ACC_CACHE.get(thread); - } - } -} diff --git a/luni/src/test/java/org/apache/harmony/security/tests/java/security/PermissionCollectionTest.java b/luni/src/test/java/org/apache/harmony/security/tests/java/security/PermissionCollectionTest.java deleted file mode 100644 index 86b1705..0000000 --- a/luni/src/test/java/org/apache/harmony/security/tests/java/security/PermissionCollectionTest.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** -* @author Alexey V. Varlamov -* @version $Revision$ -*/ - -package org.apache.harmony.security.tests.java.security; - -import java.security.Permission; -import java.security.PermissionCollection; -import java.util.*; - -import junit.framework.TestCase; - -/** - * Tests for <code>PermissionCollection</code> - * - */ -public class PermissionCollectionTest extends TestCase { - - // Bare extension to instantiate abstract PermissionCollection class - private static final class RealPermissionCollection extends PermissionCollection - { - final private Set <Permission> setCol = new HashSet<Permission>(); - public RealPermissionCollection(Set <Permission> col) - { - if (col != null) { - setCol.addAll(col); - } - } - - public void add(Permission permission) { - if (!setCol.add(permission)) { - throw new IllegalArgumentException("permission is not added"); - } - } - - public Enumeration elements() - { - return setCol == null ? null : Collections.enumeration(setCol); - } - - public boolean implies(Permission permission) - { - return false; - } - } - - /** Test read-only flag. Should be false by default and can be set once forever. */ - public void testReadOnly() - { - PermissionCollection pc = new RealPermissionCollection(null); - assertFalse("should not be read-only by default", pc.isReadOnly()); - pc.setReadOnly(); - assertTrue("explicitly set read-only", pc.isReadOnly()); - pc.setReadOnly(); - assertTrue("more calls to setReadOnly() should not harm", pc.isReadOnly()); - } - - public void testToString() { - Set<Permission> perm = new HashSet<Permission>(); - Permission p = new RealPermission("TestPermission"); - perm.add(p); - PermissionCollection pc = new RealPermissionCollection(perm); - try { - String str = pc.toString(); - assertNotNull("toString return null", str); - } catch (Exception e) { - fail("Unexpected exception " + e); - } - } -} - -class RealPermission extends Permission { - - public RealPermission(String name) { - super(name); - } - - public boolean equals(Object obj) { - return false; - } - - public String getActions() { - return null; - } - public int hashCode() { - return 0; - } - - public boolean implies(Permission permission) { - return false; - } -} diff --git a/luni/src/test/java/tests/api/java/security/PermissionCollectionTest.java b/luni/src/test/java/tests/api/java/security/PermissionCollectionTest.java deleted file mode 100644 index edbc2f5..0000000 --- a/luni/src/test/java/tests/api/java/security/PermissionCollectionTest.java +++ /dev/null @@ -1,248 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package tests.api.java.security; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.InputStream; -import java.net.URL; -import java.security.CodeSource; -import java.security.PermissionCollection; -import java.security.ProtectionDomain; -import java.security.SecurityPermission; -import java.util.StringTokenizer; - -import tests.support.Support_Exec; -import static tests.support.Support_Exec.javaProcessBuilder; -import static tests.support.Support_Exec.execAndGetOutput; -import tests.support.Support_GetLocal; -import tests.support.resource.Support_Resources; -import dalvik.annotation.KnownFailure; - -public class PermissionCollectionTest extends junit.framework.TestCase { - - // The below test is known to fail. Haven't got to the bottom of - // it yet but here is what has been determined :- - // - // * the Support_PermissionCollection application that is forked off - // near the end of this test needs to verify a signed jar (signedBKS.jar). - // This means that com.ibm.oti.util.JarUtils.verifySignature() ends up - // getting called. But at present that exists as just a lightweight/stub - // implementation which simply returns NULL. That behaviour causes a - // security exception inside java.util.jar.JarVerifier. - // - // * the above problem was fixed by rebuilding Harmony with the STUB - // IMPLEMENTATION of com.ibm.oti.util.JarUtils.verifySignature() replaced - // with one that delegates to - // org.apache.harmony.security.utils.JarUtils.verifySignature(). - // - // * unfortunately, a NPE is raised in line 103 of Harmony's JarUtils class. - // - // * the cause of that NPE has still not been determined. Could it be - // related to Harmony's current stub implementation of BigInteger ? - /** - * java.security.PermissionCollection#implies(java.security.Permission) - */ - @KnownFailure("Android doesn't support protection domains.") - public void test_impliesLjava_security_Permission() throws Exception{ - - // Look for the tests classpath - ProtectionDomain protectionDomain = getClass().getProtectionDomain(); - assertNotNull("ProtectionDomain is null", protectionDomain); - - CodeSource codeSource = protectionDomain.getCodeSource(); - - assertNotNull("CodeSource is null", codeSource); - - URL classURL = codeSource.getLocation(); - assertNotNull("Could not get this class' location", classURL); - - File policyFile = Support_GetLocal.createTempFile(".policy"); - policyFile.deleteOnExit(); - - URL signedBKS = getResourceURL("PermissionCollection/signedBKS.jar"); - URL keystoreBKS = getResourceURL("PermissionCollection/keystore.bks"); - - // Create the policy file (and save the existing one if any) - FileOutputStream fileOut = null; - try { - fileOut = new FileOutputStream(policyFile); - String linebreak = System.getProperty("line.separator"); - StringBuilder towrite = new StringBuilder(); - towrite.append("grant {"); - towrite.append(linebreak); - towrite.append("permission java.io.FilePermission \""); - towrite.append(signedBKS.getFile()); - towrite.append("\", \"read\";"); - towrite.append(linebreak); - towrite.append("permission java.lang.RuntimePermission \"getProtectionDomain\";"); - towrite.append(linebreak); - towrite.append("permission java.security.SecurityPermission \"getPolicy\";"); - towrite.append(linebreak); - towrite.append("};"); - towrite.append(linebreak); - towrite.append("grant codeBase \""); - towrite.append(signedBKS.toExternalForm()); - towrite.append("\" signedBy \"eleanor\" {"); - towrite.append(linebreak); - towrite.append("permission java.io.FilePermission \"test1.txt\", \"write\";"); - towrite.append(linebreak); - towrite.append("permission mypackage.MyPermission \"essai\", signedBy \"eleanor,dylan\";"); - towrite.append(linebreak); - towrite.append("};"); - towrite.append(linebreak); - towrite.append("grant codeBase \""); - towrite.append(signedBKS.toExternalForm()); - towrite.append("\" signedBy \"eleanor\" {"); - towrite.append(linebreak); - towrite.append("permission java.io.FilePermission \"test2.txt\", \"write\";"); - towrite.append(linebreak); - towrite.append("};"); - towrite.append(linebreak); - towrite.append("grant codeBase \""); - towrite.append(classURL.toExternalForm()); - towrite.append("\" {"); - towrite.append(linebreak); - towrite.append("permission java.security.AllPermission;"); - towrite.append(linebreak); - towrite.append("};"); - towrite.append(linebreak); - towrite.append("keystore \""); - towrite.append(keystoreBKS.toExternalForm()); - towrite.append("\",\"BKS\";"); - fileOut.write(towrite.toString().getBytes()); - fileOut.flush(); - } finally { - if (fileOut != null) { - fileOut.close(); - } - } - - // Copy mypermissionBKS.jar to the user directory so that it can be put - // in - // the classpath - File jarFile = null; - FileOutputStream fout = null; - InputStream jis = null; - try { - jis = Support_Resources - .getResourceStream("PermissionCollection/mypermissionBKS.jar"); - jarFile = Support_GetLocal.createTempFile(".jar"); - jarFile.deleteOnExit(); - fout = new FileOutputStream(jarFile); - int c = jis.read(); - while (c != -1) { - fout.write(c); - c = jis.read(); - } - fout.flush(); - } finally { - if (fout != null) { - fout.close(); - } - if (jis != null) { - jis.close(); - } - } - - ProcessBuilder builder = javaProcessBuilder(); - builder.command().add("-cp"); - builder.command().add(Support_Exec.createPath( - new File(classURL.getFile()).getPath(), jarFile.getPath())); - builder.command().add("-Djava.security.policy=" + policyFile.toURL()); - builder.command().add("tests.support.Support_PermissionCollection"); - builder.command().add(signedBKS.toExternalForm()); - String result = execAndGetOutput(builder); - - StringTokenizer resultTokenizer = new StringTokenizer(result, ","); - - // Check the test result from the new VM process - assertEquals("Permission should be granted", "false", resultTokenizer - .nextToken()); - assertEquals("signed Permission should be granted", "false", - resultTokenizer.nextToken()); - assertEquals("Permission should not be granted", "false", - resultTokenizer.nextToken()); - } - - /** - * java.security.PermissionCollection#PermissionCollection() - */ - public void test_Constructor() { - // test java.security.permissionCollection.PermissionCollection() - SecurityPermission permi = new SecurityPermission( - "testing permissionCollection-isReadOnly"); - PermissionCollection permCollect = permi.newPermissionCollection(); - assertNotNull("creat permissionCollection constructor returned a null", - permCollect); - } - - /** - * java.security.PermissionCollection#isReadOnly() - */ - public void test_isReadOnly() { - // test java.security.permissionCollection.isReadOnly() - SecurityPermission permi = new SecurityPermission( - "testing permissionCollection-isREadOnly"); - PermissionCollection permCollect = permi.newPermissionCollection(); - assertTrue("readOnly has not been set, but isReadOnly returned true", - !permCollect.isReadOnly()); - permCollect.setReadOnly(); - assertTrue("readOnly is set, but isReadonly returned false", - permCollect.isReadOnly()); - } - - /** - * java.security.PermissionCollection#setReadOnly() - */ - public void test_setReadOnly() { - // test java.security.permissionCollection.setReadOnly() - SecurityPermission permi = new SecurityPermission( - "testing permissionCollection-setReadOnly"); - PermissionCollection permCollect = permi.newPermissionCollection(); - assertTrue("readOnly has not been set, but isReadOnly returned true", - !permCollect.isReadOnly()); - permCollect.setReadOnly(); - assertTrue("readOnly is set, but isReadonly returned false", - permCollect.isReadOnly()); - } - - /** - * java.security.PermissionCollection#toString() - */ - public void test_toString() { - // test java.security.permissionCollection.toString() - SecurityPermission permi = new SecurityPermission( - "testing permissionCollection-isREadOnly"); - assertNotNull("toString should have returned a string of elements", - permi.newPermissionCollection().toString()); - assertTrue(permi.newPermissionCollection().toString().endsWith("\n")); - } - - // FIXME move me to Support_Resources - public static URL getResourceURL(String name) { - - URL url = ClassLoader.getSystemClassLoader().getResource(name); - - if (url == null) { - throw new RuntimeException("Failed to get resource url: " + name); - } - - return url; - } -} |