Java Code Examples for java.security.ProtectionDomain

The following examples show how to use java.security.ProtectionDomain. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
private static void checkMBeanTrustPermission(final Class<?> theClass)
    throws SecurityException {
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        Permission perm = new MBeanTrustPermission("register");
        PrivilegedAction<ProtectionDomain> act =
            new PrivilegedAction<ProtectionDomain>() {
                public ProtectionDomain run() {
                    return theClass.getProtectionDomain();
                }
            };
        ProtectionDomain pd = AccessController.doPrivileged(act);
        AccessControlContext acc =
            new AccessControlContext(new ProtectionDomain[] { pd });
        sm.checkPermission(perm, acc);
    }
}
 
Example 2
@Override
public PermissionCollection getPermissions(ProtectionDomain pd) {
  if (null==pd)
    return defaultPolicy.getPermissions(pd);

  final CodeSource cs = pd.getCodeSource();
  if (null==cs)
    return defaultPolicy.getPermissions(pd);

  final URL u = cs.getLocation();
  if (u != null && BundleURLStreamHandler.PROTOCOL.equals(u.getProtocol())) {
    return getPermissions(cs);
  } else {
    return defaultPolicy.getPermissions(pd);
  }
}
 
Example 3
private byte[]
transform(  ClassLoader         loader,
            String              classname,
            Class<?>            classBeingRedefined,
            ProtectionDomain    protectionDomain,
            byte[]              classfileBuffer,
            boolean             isRetransformer) {
    TransformerManager mgr = isRetransformer?
                                    mRetransfomableTransformerManager :
                                    mTransformerManager;
    if (mgr == null) {
        return null; // no manager, no transform
    } else {
        return mgr.transform(   loader,
                                classname,
                                classBeingRedefined,
                                protectionDomain,
                                classfileBuffer);
    }
}
 
Example 4
Source Project: pinpoint   Source File: RabbitMQClientPlugin.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
    InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);
    if (RabbitMQUtils.addConsumerHandleDeliveryInterceptor(target)) {
        InstrumentMethod nextDelivery = target.getDeclaredMethod("nextDelivery");
        if (nextDelivery != null) {
            nextDelivery.addScopedInterceptor(QueueingConsumerOnNextInterceptor.class, RabbitMQClientConstants.RABBITMQ_CONSUMER_SCOPE);
        }
        InstrumentMethod nextDeliveryTimeout = target.getDeclaredMethod("nextDelivery", "long");
        if (nextDeliveryTimeout != null) {
            nextDeliveryTimeout.addScopedInterceptor(QueueingConsumerOnNextInterceptor.class, RabbitMQClientConstants.RABBITMQ_CONSUMER_SCOPE);
        }
        InstrumentMethod handle = target.getDeclaredMethod("handle", "com.rabbitmq.client.QueueingConsumer$Delivery");
        if (handle != null) {
            handle.addInterceptor(QueueingConsumerHandleInterceptor.class);
        }
        return target.toBytecode();
    }
    return null;
}
 
Example 5
/**
 *
 */
public byte[]
transform(
    ClassLoader loader,
    String className,
    Class<?> classBeingRedefined,
    ProtectionDomain domain,
    byte[] classfileBuffer)
{
    if ( className.equals(TransformerManagementThreadAddTests.this.fDummyClassName) ) {
        checkInTransformer(ThreadTransformer.this);
    }
    return super.transform(    loader,
                                className,
                                classBeingRedefined,
                                domain,
                                classfileBuffer);
}
 
Example 6
/**
 * This test will run both with and without a security manager.
 *
 * The test starts a number of threads that will attempt to concurrently
 * set resource bundles on Logger, and verifies the consistency of the
 * obtained results.
 *
 * This is a best effort test.
 *
 * @param args the command line arguments
 */
public static void main(String[] args) throws Exception {

    try {
        // test without security
        System.out.println("No security");
        test();

        // test with security
        System.out.println("\nWith security");
        Policy.setPolicy(new Policy() {
            @Override
            public boolean implies(ProtectionDomain domain, Permission permission) {
                if (super.implies(domain, permission)) return true;
                // System.out.println("Granting " + permission);
                return true; // all permissions
            }
        });
        System.setSecurityManager(new SecurityManager());
        test();
    } finally {
        SetRB.executor.shutdownNow();
        SetRBName.executor.shutdownNow();
    }
}
 
Example 7
Source Project: kite   Source File: TaskUtil.java    License: Apache License 2.0 6 votes vote down vote up
private static File findJarForClass(Class<?> requiredClass) {
  ProtectionDomain domain = AccessController.doPrivileged(
      new GetProtectionDomain(requiredClass));
  CodeSource codeSource = domain.getCodeSource();
  if (codeSource != null) {
    try {
      return new File(codeSource.getLocation().toURI());
    } catch (URISyntaxException e) {
      throw new DatasetException(
          "Cannot locate " + requiredClass.getName() + " jar", e);
    }
  } else {
    // this should only happen for system classes
    throw new DatasetException(
        "Cannot locate " + requiredClass.getName() + " jar");
  }
}
 
Example 8
Source Project: pitest   Source File: CoverageTransformer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public byte[] transform(final ClassLoader loader, final String className,
    final Class<?> classBeingRedefined,
    final ProtectionDomain protectionDomain, final byte[] classfileBuffer)
        throws IllegalClassFormatException {
  final boolean include = shouldInclude(className);
  if (include) {
    try {
      return transformBytes(pickLoader(loader), className, classfileBuffer);
    } catch (final RuntimeException t) {
      System.err.println("RuntimeException while transforming  " + className);
      t.printStackTrace();
      throw t;
    }
  } else {
    return null;
  }
}
 
Example 9
Source Project: pinpoint   Source File: CommonsDbcpPlugin.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
    InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);

    if (isAvailableDataSourceMonitor(target)) {
        target.addField(DataSourceMonitorAccessor.class);

        // default constructor
        InstrumentMethod defaultConstructor = InstrumentUtils.findConstructor(target);
        defaultConstructor.addScopedInterceptor(DataSourceConstructorInterceptor.class, CommonsDbcpConstants.SCOPE);

        // closeMethod
        InstrumentMethod closeMethod = InstrumentUtils.findMethod(target, "close");
        closeMethod.addScopedInterceptor(DataSourceCloseInterceptor.class, CommonsDbcpConstants.SCOPE);
    }

    // getConnectionMethod
    InstrumentMethod getConnectionMethod1 = InstrumentUtils.findMethod(target, "getConnection");
    getConnectionMethod1.addScopedInterceptor(DataSourceGetConnectionInterceptor.class, CommonsDbcpConstants.SCOPE);

    InstrumentMethod getConnectionMethod2 = InstrumentUtils.findMethod(target, "getConnection", "java.lang.String", "java.lang.String");
    getConnectionMethod2.addScopedInterceptor(DataSourceGetConnectionInterceptor.class, CommonsDbcpConstants.SCOPE);

    return target.toBytecode();
}
 
Example 10
Source Project: pinpoint   Source File: HikariCpPlugin.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
    InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);

    // constructor
    InstrumentMethod constructor = target.getConstructor();
    if (constructor != null) {
        constructor.addScopedInterceptor(BasicMethodInterceptor.class, va(HikariCpConstants.SERVICE_TYPE), HikariCpConstants.SCOPE);
    }
    constructor = target.getConstructor("com.zaxxer.hikari.HikariConfig");
    if (constructor != null) {
        constructor.addScopedInterceptor(BasicMethodInterceptor.class, va(HikariCpConstants.SERVICE_TYPE), HikariCpConstants.SCOPE);
    }

    // getConnection method
    InstrumentMethod getConnectionMethod = InstrumentUtils.findMethod(target, "getConnection");
    getConnectionMethod.addScopedInterceptor(DataSourceGetConnectionInterceptor.class, HikariCpConstants.SCOPE);

    getConnectionMethod = InstrumentUtils.findMethod(target, "getConnection", new String[]{"java.lang.String", "java.lang.String"});
    getConnectionMethod.addScopedInterceptor(DataSourceGetConnectionInterceptor.class, HikariCpConstants.SCOPE_DEPRECATED);

    return target.toBytecode();
}
 
Example 11
Source Project: birt   Source File: BaseTestCase.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Get base folder
 * 
 * @return base folder
 */
private File getBaseFolder( )
{
	if ( classFolder == null )
	{
		String pathBase = null;

		ProtectionDomain domain = this.getClass( ).getProtectionDomain( );
		if ( domain != null )
		{
			CodeSource source = domain.getCodeSource( );
			if ( source != null )
			{
				URL url = source.getLocation( );
				pathBase = url.getPath( );

				if ( pathBase.endsWith( "bin/" ) ) //$NON-NLS-1$
					pathBase = pathBase.substring( 0,
							pathBase.length( ) - 4 );
				if ( pathBase.endsWith( "bin" ) ) //$NON-NLS-1$
					pathBase = pathBase.substring( 0,
							pathBase.length( ) - 3 );
			}
		}

		pathBase = pathBase + TEST_FOLDER + "/";
		classFolder = pathBase.substring( 1 );
	}

	String className = this.getClass( ).getName( );
	int lastDotIndex = className.lastIndexOf( "." ); //$NON-NLS-1$
	className = className.substring( 0, lastDotIndex );
	className = classFolder + className.replace( '.', '/' );

	return new File( className );
}
 
Example 12
private static String getSource(final Class<? extends MCRServletContainerInitializer> clazz) {
    if (clazz == null) {
        return null;
    }
    ProtectionDomain protectionDomain = clazz.getProtectionDomain();
    CodeSource codeSource = protectionDomain.getCodeSource();
    if (codeSource == null) {
        LogManager.getLogger().warn("Cannot get CodeSource.");
        return null;
    }
    URL location = codeSource.getLocation();
    String fileName = location.getFile();
    File sourceFile = new File(fileName);
    return sourceFile.getName();
}
 
Example 13
Source Project: jdk-1.7-annotated   Source File: ClassLoader.java    License: Apache License 2.0 5 votes vote down vote up
private String defineClassSourceLocation(ProtectionDomain pd)
{
    CodeSource cs = pd.getCodeSource();
    String source = null;
    if (cs != null && cs.getLocation() != null) {
        source = cs.getLocation().toString();
    }
    return source;
}
 
Example 14
private String defineClassSourceLocation(ProtectionDomain pd)
{
    CodeSource cs = pd.getCodeSource();
    String source = null;
    if (cs != null && cs.getLocation() != null) {
        source = cs.getLocation().toString();
    }
    return source;
}
 
Example 15
Source Project: pinpoint   Source File: HttpClient3Plugin.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public byte[] doInTransform(Instrumentor instrumenttor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
    InstrumentClass target = instrumenttor.getInstrumentClass(loader, className, classfileBuffer);

    injectHttpClientExecuteMethod(target, "org.apache.commons.httpclient.HttpMethod");
    injectHttpClientExecuteMethod(target, "org.apache.commons.httpclient.HostConfiguration", "org.apache.commons.httpclient.HttpMethod");
    injectHttpClientExecuteMethod(target, "org.apache.commons.httpclient.HostConfiguration", "org.apache.commons.httpclient.HttpMethod", "org.apache.commons.httpclient.HttpState");

    return target.toBytecode();
}
 
Example 16
Source Project: objenesis   Source File: DefineClassHelper.java    License: Apache License 2.0 5 votes vote down vote up
@Override
Class<?> defineClass(String className, byte[] b, int off, int len, Class<?> neighbor, ClassLoader loader, ProtectionDomain protectionDomain) {
   try {
      Object module = getModule.invokeWithArguments(DefineClassHelper.class);
      Object neighborModule = getModule.invokeWithArguments(neighbor);
      addReads.invokeWithArguments(module, neighborModule);
      MethodHandles.Lookup prvlookup = (MethodHandles.Lookup) privateLookupIn.invokeExact(neighbor, lookup);
      return (Class<?>) defineClass.invokeExact(prvlookup, b);
   } catch (Throwable e) {
      throw new ObjenesisException(neighbor.getName() + " has no permission to define the class", e);
   }
}
 
Example 17
Source Project: birt   Source File: BaseTestCase.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Locates the folder where the unit test java source file is saved.
 * 
 * @return the path name where the test java source file locates.
 */

protected String getClassFolder() {

	String pathBase = null;

	ProtectionDomain domain = this.getClass().getProtectionDomain();
	if (domain != null) {
		CodeSource source = domain.getCodeSource();
		if (source != null) {
			URL url = source.getLocation();
			pathBase = url.getPath();

			if (pathBase.endsWith("bin/")) //$NON-NLS-1$
				pathBase = pathBase.substring(0, pathBase.length() - 4);
			if (pathBase.endsWith("bin")) //$NON-NLS-1$
				pathBase = pathBase.substring(0, pathBase.length() - 3);
		}
	}

	pathBase = pathBase + TEST_FOLDER;
	String className = this.getClass().getName();
	int lastDotIndex = className.lastIndexOf("."); //$NON-NLS-1$
	className = className.substring(0, lastDotIndex);
	className = pathBase + className.replace('.', '/');

	return className;
}
 
Example 18
/**
 * Generate a layout class.
 * @param name       Name of class.
 * @param descriptor Layout descriptor.
 * @return Generated class.
 */
private Class<?> generateClass(final String name, final String descriptor) {
    final Context context = Context.getContextTrusted();

    final byte[] code = new ObjectClassGenerator(context).generate(descriptor);
    return defineClass(name, code, 0, code.length, new ProtectionDomain(null, getPermissions(null)));
}
 
Example 19
Source Project: jdk-1.7-annotated   Source File: ClassLoader.java    License: Apache License 2.0 5 votes vote down vote up
private Class defineTransformedClass(String name, byte[] b, int off, int len,
                                     ProtectionDomain pd,
                                     ClassFormatError cfe, String source)
  throws ClassFormatError
{
    // Class format error - try to transform the bytecode and
    // define the class again
    //
    ClassFileTransformer[] transformers =
        ClassFileTransformer.getTransformers();
    Class c = null;

    if (transformers != null) {
        for (ClassFileTransformer transformer : transformers) {
            try {
                // Transform byte code using transformer
                byte[] tb = transformer.transform(b, off, len);
                c = defineClass1(name, tb, 0, tb.length,
                                 pd, source);
                break;
            } catch (ClassFormatError cfe2)     {
                // If ClassFormatError occurs, try next transformer
            }
        }
    }

    // Rethrow original ClassFormatError if unable to transform
    // bytecode to well-formed
    //
    if (c == null)
        throw cfe;

    return c;
}
 
Example 20
@Test
public void testCtorWithClassLoaderThatDoesNotExposeAGetThrowawayClassLoaderMethodIsOkay() {
	JustAddTransformerClassLoader classLoader = new JustAddTransformerClassLoader();
	ReflectiveLoadTimeWeaver weaver = new ReflectiveLoadTimeWeaver(classLoader);
	weaver.addTransformer(new ClassFileTransformer() {
		@Override
		public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) {
			return "CAFEDEAD".getBytes();
		}
	});
	assertEquals(1, classLoader.getNumTimesGetThrowawayClassLoaderCalled());
}
 
Example 21
Source Project: pinpoint   Source File: CodeSourceUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static URL getCodeLocation(Class<?> clazz) {
    if (clazz == null) {
        throw new NullPointerException("clazz");
    }
    final ProtectionDomain protectionDomain = clazz.getProtectionDomain();
    return getCodeLocation(protectionDomain);
}
 
Example 22
Source Project: byte-buddy   Source File: ByteArrayClassLoader.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Loads a given set of class descriptions and their binary representations using a child-first class loader.
 *
 * @param classLoader               The parent class loader.
 * @param types                     The unloaded types to be loaded.
 * @param protectionDomain          The protection domain to apply where {@code null} references an implicit protection domain.
 * @param persistenceHandler        The persistence handler of the created class loader.
 * @param packageDefinitionStrategy The package definer to be queried for package definitions.
 * @param forbidExisting            {@code true} if the class loading should throw an exception if a class was already loaded by a parent class loader.
 * @param sealed                    {@code true} if the class loader should be sealed.
 * @return A map of the given type descriptions pointing to their loaded representations.
 */
@SuppressFBWarnings(value = "DP_CREATE_CLASSLOADER_INSIDE_DO_PRIVILEGED", justification = "Privilege is explicit user responsibility")
public static Map<TypeDescription, Class<?>> load(ClassLoader classLoader,
                                                  Map<TypeDescription, byte[]> types,
                                                  ProtectionDomain protectionDomain,
                                                  PersistenceHandler persistenceHandler,
                                                  PackageDefinitionStrategy packageDefinitionStrategy,
                                                  boolean forbidExisting,
                                                  boolean sealed) {
    Map<String, byte[]> typesByName = new HashMap<String, byte[]>();
    for (Map.Entry<TypeDescription, byte[]> entry : types.entrySet()) {
        typesByName.put(entry.getKey().getName(), entry.getValue());
    }
    classLoader = new ChildFirst(classLoader,
            sealed,
            typesByName,
            protectionDomain,
            persistenceHandler,
            packageDefinitionStrategy,
            NoOpClassFileTransformer.INSTANCE);
    Map<TypeDescription, Class<?>> result = new LinkedHashMap<TypeDescription, Class<?>>();
    for (TypeDescription typeDescription : types.keySet()) {
        try {
            Class<?> type = Class.forName(typeDescription.getName(), false, classLoader);
            if (forbidExisting && type.getClassLoader() != classLoader) {
                throw new IllegalStateException("Class already loaded: " + type);
            }
            result.put(typeDescription, type);
        } catch (ClassNotFoundException exception) {
            throw new IllegalStateException("Cannot load class " + typeDescription, exception);
        }
    }
    return result;
}
 
Example 23
@Override
public byte[] transform(final ClassLoader loader,
                        final String internalClassName,
                        final Class<?> classBeingRedefined,
                        final ProtectionDomain protectionDomain,
                        final byte[] srcByteCodeArray) {

    SandboxProtector.instance.enterProtecting();
    try {

        // 这里过滤掉Sandbox所需要的类|来自SandboxClassLoader所加载的类|来自ModuleJarClassLoader加载的类
        // 防止ClassCircularityError的发生
        if (SandboxClassUtils.isComeFromSandboxFamily(internalClassName, loader)) {
            return null;
        }

        return _transform(
                loader,
                internalClassName,
                classBeingRedefined,
                srcByteCodeArray
        );


    } catch (Throwable cause) {
        logger.warn("sandbox transform {} in loader={}; failed, module={} at watch={}, will ignore this transform.",
                internalClassName,
                loader,
                uniqueId,
                watchId,
                cause
        );
        return null;
    } finally {
        SandboxProtector.instance.exitProtecting();
    }
}
 
Example 24
@Override
public PermissionCollection getPermissions(ProtectionDomain domain) {
    return new PermissionsBuilder().addAll(
            allowAll.get().get() ? allPermissions :
            allowControl.get().get()
            ? withControlPermissions : permissions).toPermissions();
}
 
Example 25
Source Project: pinpoint   Source File: CxfPlugin.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className,
        Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer)
            throws InstrumentException {

    InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);

    // handleMessageMethod
    InstrumentMethod handleMessageMethod = InstrumentUtils.findMethod(target, "handleMessage", new String[]{"org.apache.cxf.message.Message"});
    handleMessageMethod.addInterceptor(BasicMethodInterceptor.class, va(CxfPluginConstants.CXF_SERVICE_INVOKER_SERVICE_TYPE));

    return target.toBytecode();
}
 
Example 26
Source Project: pinpoint   Source File: ReactorPlugin.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
    final InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);
    target.addField(AsyncContextAccessor.class);
    // Void call();
    addSchedulerAndWorkerTaskRunMethodInterceptor(target, "call");
    return target.toBytecode();
}
 
Example 27
Source Project: pinpoint   Source File: ReactorPlugin.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
    final InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);
    // Async Object
    target.addField(AsyncContextAccessor.class);

    final InstrumentMethod subscribeMethod = target.getDeclaredMethod("subscribe", "reactor.core.CoreSubscriber[]");
    if (subscribeMethod != null) {
        subscribeMethod.addInterceptor(CorePublisherInterceptor.class);
    }

    return target.toBytecode();
}
 
Example 28
public static void main (String argv[]) throws Exception {
    ProtectionDomain pd[] = new ProtectionDomain[1];

    try {
        (new AccessControlContext(pd)).checkPermission(null);
        throw new Exception("Expected NullPointerException not thrown");
    } catch (NullPointerException npe) {
    }
}
 
Example 29
Source Project: netbeans   Source File: AccController.java    License: Apache License 2.0 5 votes vote down vote up
static ProtectionDomain[] getDomains(AccessControlContext acc) throws Exception {
    Object o = getContextField().get(acc);
    if (o.getClass() == Object[].class) { // 1.2.1 fix
        Object[] array = (Object[]) o;
        ProtectionDomain[] domains = new ProtectionDomain[array.length];
        for (int i = 0; i < array.length; i++) {
            domains[i] = (ProtectionDomain) array[i];
        }
        return domains;
    }
    return (ProtectionDomain[]) o;
}
 
Example 30
Source Project: jdk8u-jdk   Source File: ClassLoader.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void postDefineClass(Class<?> c, ProtectionDomain pd)
{
    if (pd.getCodeSource() != null) {
        Certificate certs[] = pd.getCodeSource().getCertificates();
        if (certs != null)
            setSigners(c, certs);
    }
}