OPENJPA-244. Committing Albert's changes for Java 2 Security (minus the white space).

git-svn-id: https://svn.apache.org/repos/asf/openjpa/trunk@564408 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Kevin W. Sutter 2007-08-09 22:27:17 +00:00
parent 60f59740f5
commit 5c9642d5f4
31 changed files with 644 additions and 138 deletions

View File

@ -179,7 +179,8 @@ public class ReverseMappingTool
private final Log _log;
private final Map _tables = new HashMap();
private final Project _project = new Project();
private final BCClassLoader _loader = new BCClassLoader(_project);
private final BCClassLoader _loader = (BCClassLoader) AccessController
.doPrivileged(J2DoPrivHelper.newBCClassLoaderAction(_project));
private StrategyInstaller _strat = null;
private String _package = null;
private File _dir = null;

View File

@ -19,6 +19,8 @@
package org.apache.openjpa.enhance;
import java.io.IOException;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.util.Map;
import java.util.HashMap;
import java.util.Collection;
@ -28,6 +30,7 @@ import java.util.ArrayList;
import java.util.Iterator;
import org.apache.openjpa.conf.OpenJPAConfiguration;
import org.apache.openjpa.lib.util.J2DoPrivHelper;
import org.apache.openjpa.lib.util.JavaVersions;
import org.apache.openjpa.lib.util.BytecodeWriter;
import org.apache.openjpa.lib.util.Localizer;
@ -169,14 +172,19 @@ public class ManagedClassSubclasser {
}
}
private static void write(BCClass bc, PCEnhancer enhancer,
private static void write(final BCClass bc, PCEnhancer enhancer,
Map<Class, byte[]> map, Class cls, List subs, List ints)
throws IOException {
// #####
java.io.File dir = org.apache.openjpa.lib.util.Files.getPackageFile(
new java.io.File("subs"), bc.getPackageName(), true);
bc.write(new java.io.File(dir, bc.getClassName() + ".class"));
try {
AccessController.doPrivileged(J2DoPrivHelper.bCClassWrite(bc,
new java.io.File(dir, bc.getClassName() + ".class")));
} catch (PrivilegedActionException pae) {
throw (IOException) pae.getException();
}
if (bc == enhancer.getManagedTypeBytecode()) {
// if it was already defined, don't put it in the map,

View File

@ -84,9 +84,11 @@ public class PCEnhancerAgent {
conf.setConnectionDriverName(null);
conf.setConnectionFactoryName(null);
// set single class resolver
final ClassLoader tmpLoader = new TemporaryClassLoader(
(ClassLoader) AccessController.doPrivileged(
J2DoPrivHelper.getContextClassLoaderAction()));
final ClassLoader tmpLoader = (ClassLoader) AccessController
.doPrivileged(J2DoPrivHelper
.newTemporaryClassLoaderAction((ClassLoader) AccessController
.doPrivileged(J2DoPrivHelper.getContextClassLoaderAction())
));
conf.setClassResolver(new ClassResolver() {
public ClassLoader getClassLoader(Class context, ClassLoader env) {
return tmpLoader;

View File

@ -1366,7 +1366,8 @@ public class ApplicationIdTool {
ApplicationIdTool tool;
Class cls;
ClassMetaData meta;
BCClassLoader bc = new BCClassLoader(new Project());
BCClassLoader bc = (BCClassLoader) AccessController
.doPrivileged(J2DoPrivHelper.newBCClassLoaderAction(new Project()));
for (Iterator itr = classes.iterator(); itr.hasNext();) {
cls = (Class) itr.next();
log.info(_loc.get("appid-running", cls));

View File

@ -96,9 +96,10 @@ public class DynamicStorageGenerator {
// the project/classloader for the classes.
private final Project _project = new Project();
private final BCClassLoader _loader = new BCClassLoader(_project,
(ClassLoader) AccessController.doPrivileged(
J2DoPrivHelper.getClassLoaderAction(DynamicStorage.class)));
private final BCClassLoader _loader = (BCClassLoader) AccessController
.doPrivileged(J2DoPrivHelper.newBCClassLoaderAction(_project,
(ClassLoader) AccessController.doPrivileged(J2DoPrivHelper
.getClassLoaderAction(DynamicStorage.class))));
/**
* Generate a generic {@link DynamicStorage} instance with the given

View File

@ -57,7 +57,6 @@ import org.apache.openjpa.lib.util.J2DoPrivHelper;
import org.apache.openjpa.lib.util.Localizer;
import org.apache.openjpa.lib.util.Options;
import org.apache.openjpa.lib.util.Services;
import org.apache.openjpa.lib.util.TemporaryClassLoader;
import org.apache.openjpa.lib.util.Localizer.Message;
import org.apache.openjpa.meta.ClassMetaData;
import org.apache.openjpa.meta.FieldMetaData;
@ -179,14 +178,17 @@ public class PCEnhancer {
* Constructor. Supply configuration and type to enhance.
*/
public PCEnhancer(OpenJPAConfiguration conf, Class type) {
this(conf, new Project().loadClass(type), (MetaDataRepository) null);
this(conf, (BCClass) AccessController.doPrivileged(J2DoPrivHelper
.loadProjectClassAction(new Project(), type)),
(MetaDataRepository) null);
}
/**
* Constructor. Supply configuration and type to enhance.
*/
public PCEnhancer(OpenJPAConfiguration conf, ClassMetaData type) {
this(conf, new Project().loadClass(type.getDescribedType()),
this(conf, (BCClass) AccessController.doPrivileged(J2DoPrivHelper
.loadProjectClassAction(new Project(), type.getDescribedType())),
type.getRepository());
}
@ -726,14 +728,19 @@ public class PCEnhancer {
// if the middle instruction was a getfield, then it's the
// field that's being accessed
if (!findAccessed && prevIns instanceof GetFieldInstruction)
cur = ((FieldInstruction) prevIns).getField();
if (!findAccessed && prevIns instanceof GetFieldInstruction) {
final FieldInstruction fPrevIns = (FieldInstruction) prevIns;
cur = (BCField) AccessController.doPrivileged(
J2DoPrivHelper.getFieldInstructionFieldAction(fPrevIns));
// if the middle instruction was an xload_1, then the
// matched instruction is the field that's being set.
else if (findAccessed && prevIns instanceof LoadInstruction
&& ((LoadInstruction) prevIns).getParam() == 0)
cur = ((FieldInstruction) templateIns).getField();
else
} else if (findAccessed && prevIns instanceof LoadInstruction
&& ((LoadInstruction) prevIns).getParam() == 0) {
final FieldInstruction fTemplateIns =
(FieldInstruction) templateIns;
cur = (BCField) AccessController.doPrivileged(J2DoPrivHelper
.getFieldInstructionFieldAction(fTemplateIns));
} else
return null;
if (field != null && cur != field)
@ -888,7 +895,10 @@ public class PCEnhancer {
// first load the old value for use in the
// StateManager.settingXXX method.
loadManagedInstance(code, false);
code.getfield().setField(fi.getField());
final FieldInstruction fFi = fi;
code.getfield().setField(
(BCField) AccessController.doPrivileged(J2DoPrivHelper
.getFieldInstructionFieldAction(fFi)));
int val = code.getNextLocalsIndex();
code.xstore().setLocal(val).setType(fi.getFieldType());
@ -3441,7 +3451,7 @@ public class PCEnhancer {
code.vreturn();
// inst.pcStateManager.setting<fieldType>Field (inst,
// pcInheritedFieldCount + <index>, inst.<field>, value, 0);
// pcInheritedFieldCount + <index>, inst.<field>, value, 0);
ifins.setTarget(loadManagedInstance(code, true));
code.getfield().setField(SM, SMTYPE);
loadManagedInstance(code, true);
@ -3569,7 +3579,9 @@ public class PCEnhancer {
String fieldName = toBackingFieldName(attrName);
// next, find the field in the managed type.
BCField[] fields = _managedType.getFields(fieldName);
BCField[] fields = (BCField[]) AccessController
.doPrivileged(J2DoPrivHelper.getBCClassFieldsAction(_managedType,
fieldName));
BCField field = null;
for (int i = 0; i < fields.length; i++) {
field = fields[i];
@ -4284,7 +4296,8 @@ public class PCEnhancer {
loader = conf.getClassResolverInstance().
getClassLoader(PCEnhancer.class, null);
if (flags.tmpClassLoader)
loader = new TemporaryClassLoader(loader);
loader = (ClassLoader) AccessController.doPrivileged(J2DoPrivHelper
.newTemporaryClassLoaderAction(loader));
if (repos == null) {
repos = conf.newMetaDataRepositoryInstance();

View File

@ -192,7 +192,8 @@ public class Reflection {
private static void makeAccessible(AccessibleObject ao, int mods) {
try {
if (!Modifier.isPublic(mods) && !ao.isAccessible())
ao.setAccessible(true);
AccessController.doPrivileged(J2DoPrivHelper
.setAccessibleAction(ao, true));
} catch (SecurityException se) {
throw new UserException(_loc.get("reflect-security", ao)).
setFatal(true);

View File

@ -77,7 +77,8 @@ public class BeanLifecycleCallbacks
throws Exception {
Method callback = getCallbackMethod();
if (!callback.isAccessible())
callback.setAccessible(true);
AccessController.doPrivileged(J2DoPrivHelper.setAccessibleAction(
callback, true));
if (requiresArgument())
callback.invoke(_listener, new Object[]{ obj, rel });
else

View File

@ -84,7 +84,8 @@ public class MethodLifecycleCallbacks
public void makeCallback(Object obj, Object arg, int eventType)
throws Exception {
if (!_callback.isAccessible())
_callback.setAccessible(true);
AccessController.doPrivileged(J2DoPrivHelper.setAccessibleAction(
_callback, true));
if (_arg)
_callback.invoke(obj, new Object[]{ arg });

View File

@ -31,6 +31,8 @@ import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
@ -46,6 +48,7 @@ import org.apache.commons.pool.PoolableObjectFactory;
import org.apache.commons.pool.impl.GenericObjectPool;
import org.apache.openjpa.lib.conf.Configurable;
import org.apache.openjpa.lib.log.Log;
import org.apache.openjpa.lib.util.J2DoPrivHelper;
import org.apache.openjpa.lib.util.Localizer;
import org.apache.openjpa.util.GeneralException;
import org.apache.openjpa.util.InternalException;
@ -235,7 +238,8 @@ public class TCPRemoteCommitProvider
hostname = host;
tmpPort = DEFAULT_PORT;
}
InetAddress tmpAddress = InetAddress.getByName(hostname);
InetAddress tmpAddress = (InetAddress) AccessController
.doPrivileged(J2DoPrivHelper.getByNameAction(hostname));
// bleair: For each address we would rather make use of
// the jdk1.4 isLinkLocalAddress () || isLoopbackAddress ().
@ -260,8 +264,9 @@ public class TCPRemoteCommitProvider
}
}
}
}
finally {
} catch (PrivilegedActionException pae) {
throw (UnknownHostException) pae.getException();
} finally {
_addressesLock.unlock();
}
}
@ -499,7 +504,12 @@ public class TCPRemoteCommitProvider
throws IOException {
_port = port;
_log = log;
_receiveSocket = new ServerSocket(_port);
try {
_receiveSocket = (ServerSocket) AccessController
.doPrivileged(J2DoPrivHelper.newServerSocketAction(_port));
} catch (PrivilegedActionException pae) {
throw (IOException) pae.getException();
}
_localhost = InetAddress.getLocalHost().getAddress();
if (_log.isTraceEnabled())
@ -566,7 +576,8 @@ public class TCPRemoteCommitProvider
try {
s = null;
// Block, waiting to accept new connection from a peer
s = _receiveSocket.accept();
s = (Socket) AccessController.doPrivileged(J2DoPrivHelper
.acceptAction(_receiveSocket));
if (_log.isTraceEnabled()) {
_log.trace(s_loc.get("tcp-received-connection",
s.getInetAddress().getHostAddress()
@ -578,6 +589,8 @@ public class TCPRemoteCommitProvider
receiverThread.start();
_receiverThreads.add(receiverThread);
} catch (Exception e) {
if (e instanceof PrivilegedActionException)
e = ((PrivilegedActionException) e).getException();
if (!(e instanceof SocketException) || _isRunning)
if (_log.isWarnEnabled())
_log.warn(s_loc.get("tcp-accept-error"), e);
@ -755,12 +768,19 @@ public class TCPRemoteCommitProvider
private HostAddress(String host)
throws UnknownHostException {
int colon = host.indexOf(':');
if (colon != -1) {
_address = InetAddress.getByName(host.substring(0, colon));
_port = Integer.parseInt(host.substring(colon + 1));
} else {
_address = InetAddress.getByName(host);
_port = DEFAULT_PORT;
try {
if (colon != -1) {
_address = (InetAddress) AccessController
.doPrivileged(J2DoPrivHelper.getByNameAction(host
.substring(0, colon)));
_port = Integer.parseInt(host.substring(colon + 1));
} else {
_address = (InetAddress) AccessController
.doPrivileged(J2DoPrivHelper.getByNameAction(host));
_port = DEFAULT_PORT;
}
} catch (PrivilegedActionException pae) {
throw (UnknownHostException) pae.getException();
}
// -1 max wait == as long as it takes
_socketPool = new GenericObjectPool
@ -884,12 +904,18 @@ public class TCPRemoteCommitProvider
public Object makeObject()
throws IOException {
Socket s = new Socket(_address, _port);
if (log.isTraceEnabled()) {
log.trace(s_loc.get("tcp-open-connection",
_address + ":" + _port, "" + s.getLocalPort()));
try {
Socket s = (Socket) AccessController
.doPrivileged(J2DoPrivHelper.newSocketAction(_address,
_port));
if (log.isTraceEnabled()) {
log.trace(s_loc.get("tcp-open-connection", _address
+ ":" + _port, "" + s.getLocalPort()));
}
return s;
} catch (PrivilegedActionException pae) {
throw (IOException) pae.getException();
}
return s;
}
public void destroyObject(Object obj) {

View File

@ -363,7 +363,8 @@ public abstract class AbstractCFMetaDataFactory
for (int i = 0; i < metas.length; i++) {
if (getSourceFile(metas[i]) == null)
setSourceFile(metas[i], defaultSourceFile(metas[i]));
if (getSourceFile(metas[i]).exists()) {
if (((Boolean) AccessController.doPrivileged(J2DoPrivHelper
.existsAction(getSourceFile(metas[i])))).booleanValue()) {
if (files == null)
files = new HashSet();
files.add(getSourceFile(metas[i]));
@ -490,7 +491,8 @@ public abstract class AbstractCFMetaDataFactory
for (Iterator itr = files.iterator(); itr.hasNext();) {
file = (File) itr.next();
if (Files.backup(file, false) != null)
file.delete();
AccessController
.doPrivileged(J2DoPrivHelper.deleteAction(file));
}
}
@ -628,7 +630,8 @@ public abstract class AbstractCFMetaDataFactory
File file;
for (Iterator itr = files.iterator(); itr.hasNext();) {
file = (File) itr.next();
if (file.isDirectory()) {
if (((Boolean) AccessController.doPrivileged(J2DoPrivHelper
.isDirectoryAction(file))).booleanValue()) {
if (log.isTraceEnabled())
log.trace(_loc.get("scanning-directory", file));
scan(new FileMetaDataIterator(file, newMetaDataFilter()),
@ -636,8 +639,15 @@ public abstract class AbstractCFMetaDataFactory
} else if (file.getName().endsWith(".jar")) {
if (log.isTraceEnabled())
log.trace(_loc.get("scanning-jar", file));
scan(new ZipFileMetaDataIterator(new ZipFile(file),
newMetaDataFilter()), cparser, names, true, file);
try {
ZipFile zFile = (ZipFile) AccessController
.doPrivileged(J2DoPrivHelper
.newZipFileAction(file));
scan(new ZipFileMetaDataIterator(zFile,
newMetaDataFilter()), cparser, names, true, file);
} catch (PrivilegedActionException pae) {
throw (IOException) pae.getException();
}
} else {
if (log.isTraceEnabled())
log.trace(_loc.get("scanning-file", file));
@ -646,8 +656,9 @@ public abstract class AbstractCFMetaDataFactory
if (log.isTraceEnabled())
log.trace(_loc.get("scan-found-names", clss, file));
names.addAll(Arrays.asList(clss));
mapPersistentTypeNames(file.getAbsoluteFile().toURL(),
clss);
mapPersistentTypeNames(((File) AccessController
.doPrivileged(J2DoPrivHelper
.getAbsoluteFileAction(file))).toURL(), clss);
}
}
}
@ -656,14 +667,19 @@ public abstract class AbstractCFMetaDataFactory
for (Iterator itr = urls.iterator(); itr.hasNext();) {
url = (URL) itr.next();
if ("file".equals(url.getProtocol())) {
File file = new File(url.getFile()).getAbsoluteFile();
File file = (File) AccessController
.doPrivileged(J2DoPrivHelper
.getAbsoluteFileAction(new File(url.getFile())));
if (files != null && files.contains(file)) {
continue;
} else if (file.isDirectory()) {
} else if (((Boolean) AccessController
.doPrivileged(J2DoPrivHelper.isDirectoryAction(file)))
.booleanValue()) {
if (log.isTraceEnabled())
log.trace(_loc.get("scanning-directory", file));
scan(new FileMetaDataIterator(file, newMetaDataFilter()),
cparser, names, true, file);
scan(
new FileMetaDataIterator(file, newMetaDataFilter()),
cparser, names, true, file);
continue;
}
}

View File

@ -79,17 +79,22 @@ class InterfaceImplGenerator {
ClassLoader parentLoader = (ClassLoader) AccessController.doPrivileged(
J2DoPrivHelper.getClassLoaderAction(iface));
BCClassLoader loader = new BCClassLoader(_project, parentLoader);
BCClassLoader enhLoader = new BCClassLoader(_enhProject, parentLoader);
BCClassLoader loader = (BCClassLoader) AccessController
.doPrivileged(J2DoPrivHelper.newBCClassLoaderAction(_project,
parentLoader));
BCClassLoader enhLoader = (BCClassLoader) AccessController
.doPrivileged(J2DoPrivHelper.newBCClassLoaderAction(_enhProject,
parentLoader));
BCClass bc = _project.loadClass(getClassName(meta));
bc.declareInterface(iface);
ClassMetaData sup = meta.getPCSuperclassMetaData();
if (sup != null) {
bc.setSuperclass(sup.getInterfaceImpl());
enhLoader = new BCClassLoader(_enhProject,
(ClassLoader) AccessController.doPrivileged(
J2DoPrivHelper.getClassLoaderAction(
sup.getInterfaceImpl())));
enhLoader = (BCClassLoader) AccessController
.doPrivileged(J2DoPrivHelper.newBCClassLoaderAction(
_enhProject, (ClassLoader) AccessController
.doPrivileged(J2DoPrivHelper.getClassLoaderAction(sup
.getInterfaceImpl()))));
}
FieldMetaData[] fields = meta.getDeclaredFields();

View File

@ -56,7 +56,8 @@ public class ClassResolverImpl
// construct a multi class loader that will delegate in the order
// described in section 12.5 of the spec
MultiClassLoader loader = new MultiClassLoader();
MultiClassLoader loader = (MultiClassLoader) AccessController
.doPrivileged(J2DoPrivHelper.newMultiClassLoaderAction());
if (contextLoader != null)
loader.addClassLoader(contextLoader);
loader.addClassLoader(threadLoader);

View File

@ -63,7 +63,9 @@ public class GeneratedClasses {
* Load the class represented by the given bytecode.
*/
public static Class loadBCClass(BCClass bc, ClassLoader loader) {
BCClassLoader bcloader = new BCClassLoader(bc.getProject(), loader);
BCClassLoader bcloader = (BCClassLoader) AccessController
.doPrivileged(J2DoPrivHelper.newBCClassLoaderAction(bc
.getProject(), loader));
try {
Class c = Class.forName(bc.getName(), true, bcloader);
bc.getProject().clear();

View File

@ -18,6 +18,9 @@
*/
package org.apache.openjpa.util;
import java.security.AccessController;
import org.apache.openjpa.lib.util.J2DoPrivHelper;
import org.apache.openjpa.lib.util.MultiClassLoader;
/**
@ -28,7 +31,8 @@ import org.apache.openjpa.lib.util.MultiClassLoader;
*/
public class MultiLoaderClassResolver implements ClassResolver {
final private MultiClassLoader _loader = new MultiClassLoader();
final private MultiClassLoader _loader = (MultiClassLoader) AccessController
.doPrivileged(J2DoPrivHelper.newMultiClassLoaderAction());
public MultiLoaderClassResolver() {
}

View File

@ -61,7 +61,6 @@ import serp.bytecode.BCMethod;
import serp.bytecode.Code;
import serp.bytecode.JumpInstruction;
import serp.bytecode.Project;
import serp.bytecode.BCClassLoader;
import serp.util.Strings;
/**
@ -87,10 +86,12 @@ public class ProxyManagerImpl
_stdCollections.put(List.class, ArrayList.class);
if (JavaVersions.VERSION >= 5) {
try {
Class queue = Class.forName("java.util.Queue", false,
(ClassLoader) AccessController.doPrivileged(
J2DoPrivHelper.getClassLoaderAction(
Collection.class)));
Class queue = (Class) AccessController
.doPrivileged(J2DoPrivHelper.getForNameAction(
"java.util.Queue", false,
(ClassLoader) AccessController
.doPrivileged(J2DoPrivHelper
.getClassLoaderAction(Collection.class))));
_stdCollections.put(queue, LinkedList.class);
} catch (Throwable t) {
// not really java 5 after all?

View File

@ -28,6 +28,7 @@ import java.io.ObjectStreamClass;
import java.io.OutputStream;
import java.io.Serializable;
import java.security.AccessController;
import java.security.PrivilegedAction;
import org.apache.openjpa.conf.OpenJPAConfiguration;
import org.apache.openjpa.kernel.StoreContext;
@ -104,7 +105,12 @@ public class Serialization {
throws IOException {
super(delegate);
_ctx = ctx;
enableReplaceObject(true);
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
enableReplaceObject(true);
return null;
}
});
}
protected Object replaceObject(Object obj) {
@ -123,7 +129,8 @@ public class Serialization {
protected Class resolveClass(ObjectStreamClass desc)
throws IOException, ClassNotFoundException {
MultiClassLoader loader = new MultiClassLoader();
MultiClassLoader loader = (MultiClassLoader) AccessController
.doPrivileged(J2DoPrivHelper.newMultiClassLoaderAction());
addContextClassLoaders(loader);
loader.addClassLoader(getClass().getClassLoader());
loader.addClassLoader(MultiClassLoader.SYSTEM_LOADER);
@ -153,7 +160,12 @@ public class Serialization {
throws IOException {
super(delegate);
_ctx = ctx;
enableResolveObject(true);
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
enableResolveObject(true);
return null;
}
});
}
protected void addContextClassLoaders(MultiClassLoader loader) {

View File

@ -189,7 +189,8 @@ public abstract class AbstractTask extends MatchingTask {
String[] dsFiles = ds.getIncludedFiles();
for (int j = 0; j < dsFiles.length; j++) {
File f = new File(dsFiles[j]);
if (!f.isFile())
if (!((Boolean) AccessController.doPrivileged(J2DoPrivHelper
.isFileAction(f))).booleanValue())
f = new File(ds.getBasedir(), dsFiles[j]);
files.add((String) AccessController.doPrivileged(
J2DoPrivHelper.getAbsolutePathAction(f)));

View File

@ -40,6 +40,7 @@ import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
@ -164,7 +165,8 @@ public class ConfigurationImpl
* {@link ProductDerivation}s, and from System properties.
*/
public boolean loadGlobals() {
MultiClassLoader loader = new MultiClassLoader();
MultiClassLoader loader = (MultiClassLoader) AccessController
.doPrivileged(J2DoPrivHelper.newMultiClassLoaderAction());
loader.addClassLoader((ClassLoader) AccessController.doPrivileged(
J2DoPrivHelper.getContextClassLoaderAction()));
loader.addClassLoader(getClass().getClassLoader());

View File

@ -294,11 +294,13 @@ public class Configurations {
}
File file = new File(path);
if (file.isFile())
if (((Boolean) AccessController.doPrivileged(J2DoPrivHelper
.isFileAction(file))).booleanValue())
provider = ProductDerivations.load(file, anchor, null);
else {
file = new File("META-INF" + File.separatorChar + path);
if (file.isFile())
if (((Boolean) AccessController.doPrivileged(J2DoPrivHelper
.isFileAction(file))).booleanValue())
provider = ProductDerivations.load(file, anchor, null);
else
provider = ProductDerivations.load(path, anchor, null);

View File

@ -75,7 +75,8 @@ public class ClassMetaDataIterator implements MetaDataIterator {
}
if (loader == null) {
MultiClassLoader multi = new MultiClassLoader();
MultiClassLoader multi = (MultiClassLoader) AccessController
.doPrivileged(J2DoPrivHelper.newMultiClassLoaderAction());
multi.addClassLoader(multi.SYSTEM_LOADER);
multi.addClassLoader(multi.THREAD_LOADER);
multi.addClassLoader(getClass().getClassLoader());

View File

@ -21,6 +21,7 @@ package org.apache.openjpa.lib.meta;
import java.io.File;
import java.io.IOException;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.util.Properties;
import java.util.zip.ZipFile;
@ -64,11 +65,18 @@ public class ClasspathMetaDataIterator extends MetaDataIteratorChain {
if (!((Boolean) AccessController.doPrivileged(
J2DoPrivHelper.existsAction(file))).booleanValue())
continue;
if (file.isDirectory())
if (((Boolean) AccessController.doPrivileged(J2DoPrivHelper
.isDirectoryAction(file))).booleanValue())
addIterator(new FileMetaDataIterator(file, filter));
else if (tokens[i].endsWith(".jar"))
addIterator(new ZipFileMetaDataIterator(new ZipFile(file),
filter));
else if (tokens[i].endsWith(".jar")) {
try {
ZipFile zFile = (ZipFile) AccessController
.doPrivileged(J2DoPrivHelper.newZipFileAction(file));
addIterator(new ZipFileMetaDataIterator(zFile, filter));
} catch (PrivilegedActionException pae) {
throw (IOException) pae.getException();
}
}
}
}

View File

@ -92,7 +92,8 @@ public class FileMetaDataIterator implements MetaDataIterator {
if (filter.matches(rsrc))
metas.add(file);
else {
File[] files = file.listFiles();
File[] files = (File[]) AccessController
.doPrivileged(J2DoPrivHelper.listFilesAction(file));
if (files != null)
for (int i = 0; i < files.length; i++)
scanned = scan(files[i], filter, rsrc, metas, scanned);
@ -110,7 +111,8 @@ public class FileMetaDataIterator implements MetaDataIterator {
throw new NoSuchElementException();
_file = (File) _itr.next();
return _file.getAbsoluteFile().toURL();
return ((File) AccessController.doPrivileged(J2DoPrivHelper
.getAbsoluteFileAction(_file))).toURL();
}
public InputStream getInputStream() throws IOException {

View File

@ -57,7 +57,8 @@ public class ResourceMetaDataIterator implements MetaDataIterator {
public ResourceMetaDataIterator(String rsrc, ClassLoader loader)
throws IOException {
if (loader == null) {
MultiClassLoader multi = new MultiClassLoader();
MultiClassLoader multi = (MultiClassLoader) AccessController
.doPrivileged(J2DoPrivHelper.newMultiClassLoaderAction());
multi.addClassLoader(multi.SYSTEM_LOADER);
multi.addClassLoader(multi.THREAD_LOADER);
multi.addClassLoader(getClass().getClassLoader());

View File

@ -271,7 +271,8 @@ public abstract class XMLMetaDataParser extends DefaultHandler
public void parse(File file) throws IOException {
if (file == null)
return;
if (!file.isDirectory())
if (!((Boolean) AccessController.doPrivileged(J2DoPrivHelper
.isDirectoryAction(file))).booleanValue())
parse(new FileMetaDataIterator(file));
else {
String suff = (_suffix == null) ? "" : _suffix;

View File

@ -23,19 +23,31 @@ import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.AccessibleObject;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedExceptionAction;
import java.util.zip.ZipFile;
import serp.bytecode.BCClass;
import serp.bytecode.BCClassLoader;
import serp.bytecode.Code;
import serp.bytecode.FieldInstruction;
import serp.bytecode.Project;
/**
* Helper class to obtain the Privilege(Exception)Action object to perform
* Java 2 doPrivilege security sensitive function call in the following
* methods:
* <ul>
* <li>AccessibleObject.setAccessible
* <li>Class.forName
* <li>Class.getClassLoader
* <li>Class.getDeclaredField
* <li>Class.getDeclaredFields
@ -47,21 +59,36 @@ import serp.bytecode.Code;
* <li>ClassLoader.getResource
* <li>ClassLoader.getResources
* <li>ClassLoader.getSystemClassLoader
* <li>File.delete
* <li>File.exists
* <li>File.getAbsoluteFile
* <li>File.getAbsolutePath
* <li>File.getCanonicalPath
* <li>File.listFiles
* <li>File.length
* <li>File.isDirectory
* <li>File.mkdirs
* <li>File.renameTo
* <li>FileInputStream new
* <li>FileOutputStream new
* <li>System.getProperties
* <li>InetAddress.getByName
* <li>MultiClassLoader new
* <li>ServerSocket new
* <li>Socket new
* <li>Socket.accept
* <li>System.getProperty
* <li>Thread.getContextClassLoader
* <li>TemporaryClassLoader new
* <li>URL.openStream
* <li>URLConnection.getContent
* <li>ZipFile new
* <li>serp.bytecode.Code new
* <li>serp.bytecode.BCClass.isInstanceOf
* <li>serp.bytecode.BCClassLoader new
* <li>serp.bytecode.BCClass.write
* <li>serp.bytecode.BCClass.getFields
* <li>serp.bytecode.FieldInstruction.getField
* <li>serp.bytecode.Project.loadClass
* </ul>
*
* If these methods are used, the following sample usage patterns should be
@ -144,6 +171,45 @@ public abstract class J2DoPrivHelper {
return pathSeparator;
}
/**
* Return a PrivilegeAction object for aObj.setAccessible().
*
* Requires security policy: 'permission java.lang.reflect.ReflectPermission
* "suppressAccessChecks";'
*/
public static final PrivilegedAction setAccessibleAction(
final AccessibleObject aObj, final boolean flag) {
return new PrivilegedAction() {
public Object run() {
aObj.setAccessible(flag);
return (Object) null;
}
};
}
/**
* Return a PrivilegeAction object for Class.forName().
*
* Notes: doPriv of Class.forName call is required only if the input
* classloader argument is null. E.g.
*
* Class.forName("x", false, Collection.class.getClassLoader());
*
* Requires security policy: 'permission java.lang.RuntimePermission
* "getClassLoader";'
*
* @return Classloader
*/
public static final PrivilegedExceptionAction getForNameAction(
final String className, final boolean initializeBoolean,
final ClassLoader classLoader) {
return new PrivilegedExceptionAction() {
public Object run() throws ClassNotFoundException {
return Class.forName(className, initializeBoolean, classLoader);
}
};
}
/**
* Return a PrivilegeAction object for clazz.getClassloader().
*
@ -344,6 +410,22 @@ public abstract class J2DoPrivHelper {
};
}
/**
* Return a PrivilegeAction object for f.delete().
*
* Requires security policy:
* 'permission java.io.FilePermission "delete";'
*
* @return Boolean
*/
public static final PrivilegedAction deleteAction(final File f) {
return new PrivilegedAction() {
public Object run() {
return f.delete() ? Boolean.TRUE : Boolean.FALSE;
}
};
}
/**
* Return a PrivilegeAction object for f.exists().
*
@ -364,6 +446,22 @@ public abstract class J2DoPrivHelper {
};
}
/**
* Return a PrivilegeAction object for f.getAbsoluteFile().
*
* Requires security policy:
* 'permission java.util.PropertyPermission "read";'
*
* @return File
*/
public static final PrivilegedAction getAbsoluteFileAction(final File f) {
return new PrivilegedAction() {
public Object run() {
return f.getAbsoluteFile();
}
};
}
/**
* Return a PrivilegeAction object for f.getAbsolutePath().
*
@ -398,6 +496,38 @@ public abstract class J2DoPrivHelper {
};
}
/**
* Return a PrivilegeAction object for f.isDirectory().
*
* Requires security policy:
* 'permission java.io.FilePermission "read";'
*
* @return Boolean
*/
public static final PrivilegedAction isDirectoryAction(final File f) {
return new PrivilegedAction() {
public Object run() {
return f.isDirectory() ? Boolean.TRUE : Boolean.FALSE;
}
};
}
/**
* Return a PrivilegeAction object for f.isFile().
*
* Requires security policy:
* 'permission java.io.FilePermission "read";'
*
* @return Boolean
*/
public static final PrivilegedAction isFileAction(final File f) {
return new PrivilegedAction() {
public Object run() {
return f.isFile() ? Boolean.TRUE : Boolean.FALSE;
}
};
}
/**
* Return a PrivilegeAction object for f.length().
*
@ -414,6 +544,22 @@ public abstract class J2DoPrivHelper {
};
}
/**
* Return a PrivilegeAction object for f.listFiles().
*
* Requires security policy:
* 'permission java.io.FilePermission "read";'
*
* @return File[]
*/
public static final PrivilegedAction listFilesAction(final File f) {
return new PrivilegedAction() {
public Object run() {
return f.listFiles();
}
};
}
/**
* Return a PrivilegeAction object for f.mkdirs().
*
@ -501,6 +647,78 @@ public abstract class J2DoPrivHelper {
};
}
/**
* Return a PrivilegedExceptionAction object for InetAdress.getByName().
*
* Requires security policy:
* 'permission java.net.SocketPermission "connect";'
*
* @return InetAddress
* @throws UnknownHostException
*/
public static final PrivilegedExceptionAction getByNameAction(
final String hostname) throws UnknownHostException {
return new PrivilegedExceptionAction() {
public Object run() throws UnknownHostException {
return InetAddress.getByName(hostname);
}
};
}
/**
* Return a PrivilegedExceptionAction object for new Socket().
*
* Requires security policy:
* 'permission java.net.SocketPermission "connect";'
*
* @return Socket
* @throws IOException
*/
public static final PrivilegedExceptionAction newSocketAction(
final InetAddress host, final int port) throws IOException {
return new PrivilegedExceptionAction() {
public Object run() throws IOException {
return new Socket(host, port);
}
};
}
/**
* Return a PrivilegedExceptionAction object for new ServerSocket().
*
* Requires security policy:
* 'permission java.net.SocketPermission "listen";'
*
* @return ServerSocket
* @throws IOException
*/
public static final PrivilegedExceptionAction newServerSocketAction(
final int port) throws IOException {
return new PrivilegedExceptionAction() {
public Object run() throws IOException {
return new ServerSocket(port);
}
};
}
/**
* Return a PrivilegedExceptionAction object for ServerSocket.accept().
*
* Requires security policy:
* 'permission java.net.SocketPermission "listen";'
*
* @return Socket
* @throws IOException
*/
public static final PrivilegedExceptionAction acceptAction(
final ServerSocket ss) throws IOException {
return new PrivilegedExceptionAction() {
public Object run() throws IOException {
return ss.accept();
}
};
}
/**
* Return a PrivilegeAction object for System.getProperties().
*
@ -586,6 +804,24 @@ public abstract class J2DoPrivHelper {
};
}
/**
* Return a PrivilegedExceptionAction object for new ZipFile().
*
* Requires security policy:
* 'permission java.io.FilePermission "read";'
*
* @return ZipFile
* @throws IOException
*/
public static final PrivilegedExceptionAction newZipFileAction(final File f)
throws IOException {
return new PrivilegedExceptionAction() {
public Object run() throws IOException {
return new ZipFile(f);
}
};
}
/**
* Return a PrivilegeAction object for new serp.bytecode.Code().
*
@ -601,4 +837,133 @@ public abstract class J2DoPrivHelper {
}
};
}
/**
* Return a PrivilegeAction object for new TemporaryClassLoader().
*
* Requires security policy:
* 'permission java.lang.RuntimePermission "createClassLoader";'
*
* @return TemporaryClassLoader
*/
public static final PrivilegedAction newTemporaryClassLoaderAction(
final ClassLoader parent) {
return new PrivilegedAction() {
public Object run() {
return new TemporaryClassLoader(parent);
}
};
}
/**
* Return a PrivilegeAction object for new MultiClassLoader().
*
* Requires security policy:
* 'permission java.lang.RuntimePermission "createClassLoader";'
*
* @return MultiClassLoader
*/
public static final PrivilegedAction newMultiClassLoaderAction() {
return new PrivilegedAction() {
public Object run() {
return new MultiClassLoader();
}
};
}
/**
* Return a PrivilegeAction object for new BCClassLoader().
*
* Requires security policy:
* 'permission java.lang.RuntimePermission "createClassLoader";'
*
* @return BCClassLoader
*/
public static final PrivilegedAction newBCClassLoaderAction(
final Project project, final ClassLoader parent) {
return new PrivilegedAction() {
public Object run() {
return new BCClassLoader(project, parent);
}
};
}
public static final PrivilegedAction newBCClassLoaderAction(
final Project project) {
return new PrivilegedAction() {
public Object run() {
return new BCClassLoader(project);
}
};
}
/**
* Return a PrivilegedExceptionAction object for BCClass.write().
*
* Requires security policy:
* 'permission java.io.FilePermission "write";'
*
* @return File
* @throws IOException
*/
public static final PrivilegedExceptionAction bCClassWrite(
final BCClass bc, final File f) throws IOException {
return new PrivilegedExceptionAction() {
public Object run() throws IOException {
bc.write(f);
return null;
}
};
}
/**
* Return a PrivilegeAction object for BCClass.getFields().
*
* Requires security policy:
* 'permission java.lang.RuntimePermission "getClassLoader";'
*
* @return BCField
*/
public static final PrivilegedAction getBCClassFieldsAction(
final BCClass bcClass, final String fieldName) {
return new PrivilegedAction() {
public Object run() {
return bcClass.getFields(fieldName);
}
};
}
/**
* Return a PrivilegeAction object for FieldInstruction.getField().
*
* Requires security policy:
* 'permission java.lang.RuntimePermission "getClassLoader";'
*
* @return BCField
*/
public static final PrivilegedAction getFieldInstructionFieldAction(
final FieldInstruction instruction) {
return new PrivilegedAction() {
public Object run() {
return instruction.getField();
}
};
}
/**
* Return a PrivilegeAction object for Project.loadClass().
*
* Requires security policy:
* 'permission java.lang.RuntimePermission "createClassLoader";'
*
* @return BCClass
*/
public static final PrivilegedAction loadProjectClassAction(
final Project project, final Class clazz) {
return new PrivilegedAction() {
public Object run() {
return project.loadClass(clazz);
}
};
}
}

View File

@ -0,0 +1,62 @@
// ================================================================
// Example JSE Java 2 security policy required by OpenJPA.
//
// -Djava.security.manager -Djava.security.policy=C:\j2.security.jse.policy
// ----------------------------------------------------------------
// Application: E.g.
// -Dapplication=file:///C:/com/my/appl/classes
grant CodeBase "${application}/-" {
// Allows Persistence.createEntityManagerFacotry() to read META-INF/*
permission java.io.FilePermission "<<ALL FILES>>", "read";
};
// ----------------------------------------------------------------
// Derby: E.g.
// -Dderby.base="file:///C:\.m2\repository\org\apache\derby\derby\10.2.2.0
grant CodeBase "${derby.base}/-" {
permission java.io.FilePermission "<<ALL FILES>>", "read,write,delete";
permission java.lang.RuntimePermission "createClassLoader";
permission java.util.PropertyPermission "*", "read";
};
// ----------------------------------------------------------------
// DB2: E.g.
// -db2.base=file:///C:/sqllib/java
grant CodeBase "${db2.base}/-" {
permission java.lang.RuntimePermission "loadLibrary.*";
permission java.util.PropertyPermission "*", "read";
};
// ================================================================
// The following permissions are required by OpenJPA implementation.
// ----------------------------------------------------------------
// Serp: E.g.
// -Dserp.base="file:///C:\.m2\repository\net\sourceforge\serp\serp\1.11.0"
grant CodeBase "${serp.base}/-" {
permission java.io.FilePermission "<<ALL FILES>>", "read,write";
permission java.lang.RuntimePermission "createClassLoader";
};
// ----------------------------------------------------------------
// OpeJPA: E.g.
// -Dopenjpa.base=file:///C:\openjpa.cur\openjpa-all\target
grant CodeBase "${openjpa.base}/-" {
permission java.io.FilePermission "<<ALL FILES>>", "read,write";
permission java.lang.RuntimePermission "createClassLoader";
permission java.lang.reflect.ReflectPermission "suppressAccessChecks";
permission java.util.PropertyPermission "*", "read";
};

View File

@ -35,48 +35,3 @@ grant CodeBase "file:///${user.home}/.m2/repository/-" {
permission java.util.PropertyPermission "*", "read,write";
};
// ================================================================
// The following permissions are required by OpenJPA implementation.
grant CodeBase "${application}/openjpa-1.0.0-SNAPSHOT.jar" {
// class.getClassLoader()
// thread.getContextClassLoader()
// classloader.getParent()
// classloader.getSystemClassLoader()
// new serp.bytecode.Code()
// serp.bytecode.BCClass.isInstanceOf()
// class.newInstance()
//
permission java.lang.RuntimePermission "getClassLoader";
// urlConnection.getContext()
// url.openStream()
// classloader.getResource()
// classloader.getResources()
// new FileInputStream()
// file.exists()
//
permission java.io.FilePermission "<<ALL FILES>>", "read";
// file.mkdirs()
// file.renameTo()
// new FileOutputStream()
//
permission java.io.FilePermission "<<ALL FILES>>", "write";
// class.getDeclaredField()
// class.getDeclaredFields()
// class.getDeclaredMethod()
// class.getDeclaredMethods()
//
permission java.lang.RuntimePermission "accessDeclaredMembers";
// System.getProperty()
// System.getPrperties()
// File.getAbsolutePath()
// File.getCanonicalPath()
//
permission java.util.PropertyPermission "*", "read";
};

View File

@ -19,6 +19,7 @@
package org.apache.openjpa.persistence;
import org.apache.openjpa.lib.meta.SourceTracker;
import org.apache.openjpa.lib.util.J2DoPrivHelper;
import org.apache.openjpa.lib.util.Localizer;
import org.apache.openjpa.lib.util.JavaVersions;
import org.apache.openjpa.lib.log.Log;
@ -29,6 +30,8 @@ import org.apache.openjpa.kernel.QueryLanguages;
import org.apache.openjpa.util.InternalException;
import org.apache.commons.lang.StringUtils;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.util.*;
import java.io.File;
import java.io.IOException;
@ -1194,10 +1197,15 @@ public class AnnotationPersistenceMetaDataSerializer
}
public void serialize(File file, int flags) throws IOException {
FileWriter out = new FileWriter(file.getCanonicalPath(),
(flags & APPEND) > 0);
serialize(out, flags);
out.close();
try {
FileWriter out = new FileWriter((String) AccessController
.doPrivileged(J2DoPrivHelper.getCanonicalPathAction(file)),
(flags & APPEND) > 0);
serialize(out, flags);
out.close();
} catch (PrivilegedActionException pae) {
throw (IOException) pae.getException();
}
}
public void serialize(Writer out, int flags) throws IOException {

View File

@ -204,7 +204,8 @@ public class PersistenceProductDerivation
String[] prefixes = ProductDerivations.getConfigurationPrefixes();
String rsrc = null;
for (int i = 0; i < prefixes.length && StringUtils.isEmpty(rsrc); i++)
rsrc = System.getProperty(prefixes[i] + ".properties");
rsrc = (String) AccessController.doPrivileged(J2DoPrivHelper
.getPropertyAction(prefixes[i] + ".properties"));
boolean explicit = !StringUtils.isEmpty(rsrc);
String anchor = null;
int idx = (!explicit) ? -1 : rsrc.lastIndexOf('#');

View File

@ -93,9 +93,9 @@ public class PersistenceUnitInfoImpl
}
public ClassLoader getNewTempClassLoader() {
return new TemporaryClassLoader(
(ClassLoader) AccessController.doPrivileged(
J2DoPrivHelper.getContextClassLoaderAction()));
return (ClassLoader) AccessController.doPrivileged(J2DoPrivHelper
.newTemporaryClassLoaderAction((ClassLoader) AccessController
.doPrivileged(J2DoPrivHelper.getContextClassLoaderAction())));
}
public String getPersistenceUnitName() {
@ -201,7 +201,8 @@ public class PersistenceUnitInfoImpl
}
public void addJarFileName(String name) {
MultiClassLoader loader = new MultiClassLoader();
MultiClassLoader loader = (MultiClassLoader) AccessController
.doPrivileged(J2DoPrivHelper.newMultiClassLoaderAction());
loader.addClassLoader(getClass().getClassLoader());
loader.addClassLoader(MultiClassLoader.THREAD_LOADER);
URL url = (URL) AccessController.doPrivileged(