下面列出了怎么用java.security.CodeSource的API类实例代码及写法,或者点击链接到github查看源代码。
@BeforeClass
public static void setupSharedState()
{
// Configure XMLUnit.
XMLUnit.setIgnoreWhitespace( true );
XMLUnit.setIgnoreAttributeOrder( true );
// Configure the TransformerFactory
try
{
factory = TransformerFactory.newInstance();
final CodeSource codeSource = factory.getClass().getProtectionDomain().getCodeSource();
System.out.println(
"-- Found TransformerFactory of type [" + factory.getClass().getName() + "] loaded from [" + codeSource.getLocation().toString() + "]" );
}
catch ( Exception ex )
{
ex.printStackTrace();
}
}
/**
* Initializes the loader.
*/
@PostConstruct
@Override
public void init()
throws ConfigException
{
try {
_codeSource = new CodeSource(new URL(_path.getURL()),
(Certificate []) null);
} catch (Exception e) {
log.log(Level.FINE, e.toString(), e);
}
super.init();
getClassLoader().addURL(_path, _isScanned);
}
/**
* create a context that can read any directories (recursively)
* mentioned in the class path. In the case of a jar, it has to
* be the directory containing the jar, not just the jar, as jar
* files might refer to other jar files.
*/
private static AccessControlContext getContext(File[] cp)
throws java.net.MalformedURLException
{
PathPermissions perms =
new PathPermissions(cp);
ProtectionDomain domain =
new ProtectionDomain(new CodeSource(perms.getCodeBase(),
(java.security.cert.Certificate[]) null),
perms);
AccessControlContext acc =
new AccessControlContext(new ProtectionDomain[] { domain });
return acc;
}
CodeSource[] getCodeSources(URL url) {
ensureInitialization();
if (jv != null) {
return jv.getCodeSources(this, url);
}
/*
* JAR file has no signed content. Is there a non-signing
* code source?
*/
Enumeration<String> unsigned = unsignedEntryNames();
if (unsigned.hasMoreElements()) {
return new CodeSource[]{JarVerifier.getUnsignedCS(url)};
} else {
return null;
}
}
private static PermissionCollection getExecPermissions() {
/*
* The approach used here is taken from the similar method
* getLoaderAccessControlContext() in the class
* sun.rmi.server.LoaderHandler.
*/
// obtain permissions granted to all code in current policy
PermissionCollection perms = AccessController.doPrivileged(
new PrivilegedAction<PermissionCollection>() {
public PermissionCollection run() {
CodeSource codesource =
new CodeSource(null, (Certificate[]) null);
Policy p = Policy.getPolicy();
if (p != null) {
return p.getPermissions(codesource);
} else {
return new Permissions();
}
}
});
return perms;
}
private static PermissionCollection getExecPermissions() {
/*
* The approach used here is taken from the similar method
* getLoaderAccessControlContext() in the class
* sun.rmi.server.LoaderHandler.
*/
// obtain permissions granted to all code in current policy
PermissionCollection perms = AccessController.doPrivileged(
new PrivilegedAction<PermissionCollection>() {
public PermissionCollection run() {
CodeSource codesource =
new CodeSource(null, (Certificate[]) null);
Policy p = Policy.getPolicy();
if (p != null) {
return p.getPermissions(codesource);
} else {
return new Permissions();
}
}
});
return perms;
}
private void checkCerts(String name, CodeSource cs) {
int i = name.lastIndexOf('.');
String pname = (i == -1) ? "" : name.substring(0, i);
Certificate[] certs = null;
if (cs != null) {
certs = cs.getCertificates();
}
Certificate[] pcerts = null;
if (parallelLockMap == null) {
synchronized (this) {
pcerts = package2certs.get(pname);
if (pcerts == null) {
package2certs.put(pname, (certs == null? nocerts:certs));
}
}
} else {
pcerts = ((ConcurrentHashMap<String, Certificate[]>)package2certs).
putIfAbsent(pname, (certs == null? nocerts:certs));
}
if (pcerts != null && !compareCerts(pcerts, certs)) {
throw new SecurityException("class \""+ name +
"\"'s signer information does not match signer information of other classes in the same package");
}
}
private static AccessControlContext getContext(File[] dirs)
throws IOException
{
PathPermissions perms =
new PathPermissions(dirs);
ProtectionDomain domain = new ProtectionDomain(
new CodeSource(perms.getCodeBase(),
(java.security.cert.Certificate[]) null),
perms);
AccessControlContext acc =
new AccessControlContext(new ProtectionDomain[] { domain });
return acc;
}
public static String getCodeBase(Class<?> cls) {
if (cls == null) {
return null;
}
ProtectionDomain domain = cls.getProtectionDomain();
if (domain == null) {
return null;
}
CodeSource source = domain.getCodeSource();
if (source == null) {
return null;
}
URL location = source.getLocation();
if (location == null) {
return null;
}
return location.getFile();
}
private static String findSource(Class<?> clazz) {
final CodeSource codeSource = clazz.getProtectionDomain().getCodeSource();
if (codeSource != null && codeSource.getLocation() != null) {
String src = codeSource.getLocation().toString();
if (src.startsWith("file:/")) {
src = src.substring("file:/".length());
} else if (src.startsWith("vfs:/")) {
// "vfs:/" pour jboss 6.0
src = src.substring("vfs:/".length());
} else if (src.startsWith("reference:file:/")) {
// "reference:file:/" pour les bundles osgi
src = src.substring("reference:file:/".length());
}
if (src.endsWith(".jar") || src.endsWith(".war")) {
src = src.intern();
}
return src;
}
return null;
}
public static String getCodeBase(Class<?> cls) {
if (cls == null) {
return null;
}
ProtectionDomain domain = cls.getProtectionDomain();
if (domain == null) {
return null;
}
CodeSource source = domain.getCodeSource();
if (source == null) {
return null;
}
URL location = source.getLocation();
if (location == null) {
return null;
}
return location.getFile();
}
@Test
public void canCreateFacadeAroundNoCertificates() throws Exception {
// Act:
final URL url = new URL("http://nem.com/foo/n.jar");
final CodeSourceFacade facade = new CodeSourceFacade(new CodeSource(url, new Certificate[] {}));
// Assert:
Assert.assertThat(facade.getLocation(), IsEqual.equalTo(url));
Assert.assertThat(facade.getFirstCertificate(), IsNull.nullValue());
}
Resource loadResource( String name ) throws IOException
{
URL url = new URL( baseUrl, name );
InputStream in = url.openStream( );
try
{
final byte[] bytes = loadStream( in );
return new Resource( ) {
byte[] getBytes( )
{
return bytes;
};
CodeSource getCodeSource( )
{
return codeSource;
}
Manifest getManifest( )
{
return null;
}
};
}
finally
{
in.close( );
}
}
/**
* Repeatedly load a class not found in classpath through RMIClassLoader.
* Arguments: <# reps>
*/
public long run(String[] args) throws Exception {
int reps = Integer.parseInt(args[0]);
CodeSource csrc = getClass().getProtectionDomain().getCodeSource();
String url = "jar:" + csrc.getLocation().toString() + ALTROOT;
long start = System.currentTimeMillis();
for (int i = 0; i < reps; i++)
RMIClassLoader.loadClass(url, CLASSNAME);
long time = System.currentTimeMillis() - start;
return time;
}
@Override
public PermissionCollection getPermissions(final Subject subject,
final CodeSource codesource) {
// 1) if code instantiates PolicyFile directly, then it will need
// all the permissions required for the PolicyFile initialization
// 2) if code calls Policy.getPolicy, then it simply needs
// AuthPermission(getPolicy), and the javax.security.auth.Policy
// implementation instantiates PolicyFile in a doPrivileged block
// 3) if after instantiating a Policy (either via #1 or #2),
// code calls getPermissions, PolicyFile wraps the call
// in a doPrivileged block.
return AccessController.doPrivileged
(new PrivilegedAction<PermissionCollection>() {
@Override public PermissionCollection run() {
SubjectCodeSource scs = new SubjectCodeSource(
subject, null,
codesource == null ? null : codesource.getLocation(),
codesource == null ? null : codesource.getCertificates());
if (initialized) {
return getPermissions(new Permissions(), scs);
} else {
return new PolicyPermissions(AuthPolicyFile.this, scs);
}
}
});
}
private static void testImplies(URL thisURL, URL thatURL, boolean result)
throws SecurityException
{
CodeSource thisCs =
new CodeSource(thisURL, (java.security.cert.Certificate[]) null);
CodeSource thatCs =
new CodeSource(thatURL, (java.security.cert.Certificate[]) null);
if (thisCs.implies(thatCs) != result) {
throw new SecurityException("test failed");
}
}
private Class<?> defineClass(String name, byte[] b) throws IOException {
CodeSource cs = new CodeSource(null, (java.security.cert.Certificate[]) null);
if (!name.equals(TRAMPOLINE)) {
throw new IOException("MethodUtil: bad name " + name);
}
return defineClass(name, b, 0, b.length, cs);
}
private String defineClassSourceLocation(ProtectionDomain pd) {
CodeSource cs = pd.getCodeSource();
String source = null;
if (cs != null && cs.getLocation() != null) {
source = cs.getLocation().toString();
}
return source;
}
/**
* allow any classes loaded from classpath to exit the VM.
*/
protected PermissionCollection getPermissions(CodeSource codesource)
{
PermissionCollection perms = super.getPermissions(codesource);
perms.add(new RuntimePermission("exitVM"));
return perms;
}
public static String getCodeBase(Class<?> cls) {
if (cls == null)
return null;
ProtectionDomain domain = cls.getProtectionDomain();
if (domain == null)
return null;
CodeSource source = domain.getCodeSource();
if (source == null)
return null;
URL location = source.getLocation();
if (location == null)
return null;
return location.getFile();
}
static URL urlFromCodeSource(Class aclass) {
try {
CodeSource codeSource = aclass.getProtectionDomain().getCodeSource();
URL url = codeSource != null ? codeSource.getLocation() : null;
// url is in one of two forms
// 1) ./build/classes/
// 2) jardir/JarName.jar
return url;
} catch (SecurityException ex) {
return null;
}
}
/**
* Generates an AccessControlContext with minimal permissions.
* The approach used here is taken from the similar method
* getAccessControlContext() in the sun.applet.AppletPanel class.
*/
private static AccessControlContext getAccessControlContext(int port) {
// begin with permissions granted to all code in current policy
PermissionCollection perms = AccessController.doPrivileged(
new java.security.PrivilegedAction<PermissionCollection>() {
public PermissionCollection run() {
CodeSource codesource = new CodeSource(null,
(java.security.cert.Certificate[]) null);
Policy p = java.security.Policy.getPolicy();
if (p != null) {
return p.getPermissions(codesource);
} else {
return new Permissions();
}
}
});
/*
* Anyone can connect to the registry and the registry can connect
* to and possibly download stubs from anywhere. Downloaded stubs and
* related classes themselves are more tightly limited by RMI.
*/
perms.add(new SocketPermission("*", "connect,accept"));
perms.add(new SocketPermission("localhost:"+port, "listen,accept"));
perms.add(new RuntimePermission("accessClassInPackage.sun.jvmstat.*"));
perms.add(new RuntimePermission("accessClassInPackage.sun.jvm.hotspot.*"));
perms.add(new FilePermission("<<ALL FILES>>", "read"));
/*
* Create an AccessControlContext that consists of a single
* protection domain with only the permissions calculated above.
*/
ProtectionDomain pd = new ProtectionDomain(
new CodeSource(null,
(java.security.cert.Certificate[]) null), perms);
return new AccessControlContext(new ProtectionDomain[] { pd });
}
private String defineClassSourceLocation(ProtectionDomain pd)
{
CodeSource cs = pd.getCodeSource();
String source = null;
if (cs != null && cs.getLocation() != null) {
source = cs.getLocation().toString();
}
return source;
}
protected AppletClassLoader(URL base) {
super(new URL[0]);
this.base = base;
this.codesource =
new CodeSource(base, (java.security.cert.Certificate[]) null);
acc = AccessController.getContext();
}
@Override
protected PermissionCollection getPermissions(final CodeSource codesource) {
final Permissions permCollection = new Permissions();
for (final Permission perm : SCRIPT_PERMISSIONS) {
permCollection.add(perm);
}
return permCollection;
}
public static String getCodeBase(Class<?> cls) {
if (cls == null)
return null;
ProtectionDomain domain = cls.getProtectionDomain();
if (domain == null)
return null;
CodeSource source = domain.getCodeSource();
if (source == null)
return null;
URL location = source.getLocation();
if (location == null)
return null;
return location.getFile();
}
public static void main(String[] args) throws Exception {
Policy policy = Policy.getPolicy();
PermissionCollection perms = policy.getPermissions((CodeSource)null);
if (perms.elements().hasMoreElements()) {
System.err.println(perms);
throw new Exception("PermissionCollection is not empty");
}
}
private String genSourceCacheKey(GroovyCodeSource codeSource) {
StringBuilder strToDigest;
String scriptText = codeSource.getScriptText();
if (null != scriptText) {
strToDigest = new StringBuilder((int) (scriptText.length() * 1.2));
strToDigest.append("scriptText:").append(scriptText);
CodeSource cs = codeSource.getCodeSource();
if (null != cs) {
strToDigest.append("/codeSource:").append(cs);
}
} else {
strToDigest = new StringBuilder(32);
// if the script text is null, i.e. the script content is invalid
// use the name as cache key for the time being to trigger the validation by `groovy.lang.GroovyClassLoader.validate`
// note: the script will not be cached due to the invalid script content,
// so it does not matter even if cache key is not the md5 value of script content
strToDigest.append("name:").append(codeSource.getName());
}
try {
return EncodingGroovyMethods.md5(strToDigest);
} catch (NoSuchAlgorithmException e) {
throw new GroovyRuntimeException(e); // should never reach here!
}
}
private String defineClassSourceLocation(ProtectionDomain pd)
{
CodeSource cs = pd.getCodeSource();
String source = null;
if (cs != null && cs.getLocation() != null) {
source = cs.getLocation().toString();
}
return source;
}
/**
* allow any classes loaded from classpath to exit the VM.
*/
protected PermissionCollection getPermissions(CodeSource codesource)
{
PermissionCollection perms = super.getPermissions(codesource);
perms.add(new RuntimePermission("exitVM"));
return perms;
}