Search in sources :

Example 6 with ProtectionDomain

use of java.security.ProtectionDomain in project elasticsearch by elastic.

the class BootstrapForTesting method getPluginPermissions.

/**
     * we don't know which codesources belong to which plugin, so just remove the permission from key codebases
     * like core, test-framework, etc. this way tests fail if accesscontroller blocks are missing.
     */
@SuppressForbidden(reason = "accesses fully qualified URLs to configure security")
static Map<String, Policy> getPluginPermissions() throws Exception {
    List<URL> pluginPolicies = Collections.list(BootstrapForTesting.class.getClassLoader().getResources(PluginInfo.ES_PLUGIN_POLICY));
    if (pluginPolicies.isEmpty()) {
        return Collections.emptyMap();
    }
    // compute classpath minus obvious places, all other jars will get the permission.
    Set<URL> codebases = new HashSet<>(Arrays.asList(parseClassPathWithSymlinks()));
    Set<URL> excluded = new HashSet<>(Arrays.asList(// es core
    Bootstrap.class.getProtectionDomain().getCodeSource().getLocation(), // es test framework
    BootstrapForTesting.class.getProtectionDomain().getCodeSource().getLocation(), // lucene test framework
    LuceneTestCase.class.getProtectionDomain().getCodeSource().getLocation(), // randomized runner
    RandomizedRunner.class.getProtectionDomain().getCodeSource().getLocation(), // junit library
    Assert.class.getProtectionDomain().getCodeSource().getLocation()));
    codebases.removeAll(excluded);
    // parse each policy file, with codebase substitution from the classpath
    final List<Policy> policies = new ArrayList<>();
    for (URL policyFile : pluginPolicies) {
        policies.add(Security.readPolicy(policyFile, codebases.toArray(new URL[codebases.size()])));
    }
    // consult each policy file for those codebases
    Map<String, Policy> map = new HashMap<>();
    for (URL url : codebases) {
        map.put(url.getFile(), new Policy() {

            @Override
            public boolean implies(ProtectionDomain domain, Permission permission) {
                // implements union
                for (Policy p : policies) {
                    if (p.implies(domain, permission)) {
                        return true;
                    }
                }
                return false;
            }
        });
    }
    return Collections.unmodifiableMap(map);
}
Also used : Policy(java.security.Policy) ProtectionDomain(java.security.ProtectionDomain) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) URL(java.net.URL) FilePermission(java.io.FilePermission) SocketPermission(java.net.SocketPermission) Permission(java.security.Permission) HashSet(java.util.HashSet) SuppressForbidden(org.elasticsearch.common.SuppressForbidden)

Example 7 with ProtectionDomain

use of java.security.ProtectionDomain in project elasticsearch by elastic.

the class ESPolicyTests method testRestrictPrivileges.

/** 
     * test restricting privileges to no permissions actually works
     */
public void testRestrictPrivileges() {
    assumeTrue("test requires security manager", System.getSecurityManager() != null);
    try {
        System.getProperty("user.home");
    } catch (SecurityException e) {
        fail("this test needs to be fixed: user.home not available by policy");
    }
    PermissionCollection noPermissions = new Permissions();
    AccessControlContext noPermissionsAcc = new AccessControlContext(new ProtectionDomain[] { new ProtectionDomain(null, noPermissions) });
    try {
        AccessController.doPrivileged(new PrivilegedAction<Void>() {

            public Void run() {
                System.getProperty("user.home");
                fail("access should have been denied");
                return null;
            }
        }, noPermissionsAcc);
    } catch (SecurityException expected) {
    // expected exception
    }
}
Also used : PermissionCollection(java.security.PermissionCollection) ProtectionDomain(java.security.ProtectionDomain) AccessControlContext(java.security.AccessControlContext) Permissions(java.security.Permissions)

Example 8 with ProtectionDomain

use of java.security.ProtectionDomain in project jersey by jersey.

the class PerfTestAgent method premain.

public static void premain(String agentArgs, Instrumentation instrumentation) {
    final String handlerClassName = (agentArgs != null && !agentArgs.isEmpty()) ? agentArgs.substring(0, agentArgs.lastIndexOf('.')) : HANDLER_CLASS_NAME;
    final String handlerMethodName = (agentArgs != null && !agentArgs.isEmpty()) ? agentArgs.substring(agentArgs.lastIndexOf('.') + 1) : HANDLER_METHOD_NAME;
    instrumentation.addTransformer(new ClassFileTransformer() {

        @Override
        public byte[] transform(ClassLoader loader, String className, Class<?> aClass, ProtectionDomain protectionDomain, byte[] bytes) throws IllegalClassFormatException {
            if (handlerClassName.replaceAll("\\.", "/").equals(className)) {
                try {
                    ClassPool cp = ClassPool.getDefault();
                    cp.appendSystemPath();
                    CtClass cc = cp.makeClass(new java.io.ByteArrayInputStream(bytes));
                    final CtField ctxField = CtField.make("public static final agent.metrics.Timer.Context agentTimerCtx;", cc);
                    final CtField registryField = CtField.make("public static final agent.metrics.MetricRegistry agentREG = new agent.metrics.MetricRegistry();", cc);
                    final CtField reporterField = CtField.make("public static final agent.metrics.JmxReporter agentReporter = agent.metrics.JmxReporter.forRegistry(agentREG).build();", cc);
                    final CtField timerField = CtField.make("public static final agent.metrics.Timer agentTimer = " + "agentREG.timer(agent.metrics.MetricRegistry.name(\"" + handlerClassName + "\", new String[] {\"" + handlerMethodName + "\"}));", cc);
                    cc.addField(registryField);
                    cc.addField(reporterField);
                    cc.addField(timerField);
                    cc.makeClassInitializer().insertAfter("agentReporter.start();");
                    CtMethod m = cc.getDeclaredMethod(handlerMethodName);
                    m.addLocalVariable("agentCtx", ctxField.getType());
                    m.insertBefore("agentCtx = agentTimer.time();");
                    m.insertAfter("agentCtx.stop();", true);
                    byte[] byteCode = cc.toBytecode();
                    cc.detach();
                    System.out.printf("Jersey Perf Agent Instrumentation Done! (instrumented method: %s)\n", m.getLongName());
                    return byteCode;
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            return null;
        }
    });
}
Also used : ProtectionDomain(java.security.ProtectionDomain) ClassFileTransformer(java.lang.instrument.ClassFileTransformer) ClassPool(javassist.ClassPool) IllegalClassFormatException(java.lang.instrument.IllegalClassFormatException) CtClass(javassist.CtClass) CtField(javassist.CtField) IllegalClassFormatException(java.lang.instrument.IllegalClassFormatException) CtMethod(javassist.CtMethod)

Example 9 with ProtectionDomain

use of java.security.ProtectionDomain in project hudson-2.x by hudson.

the class SystemServiceImpl method getInstallationDirectory.

public File getInstallationDirectory() {
    //securityService.checkPermission(Hudson.ADMINISTER);
    File dir;
    try {
        // verbose to help pinpoint any NPE at runtime
        ProtectionDomain pd = Hudson.class.getProtectionDomain();
        CodeSource cs = pd.getCodeSource();
        URL url = cs.getLocation();
        String path = url.getPath();
        dir = new File(path);
        // Jar containing Launcher is expected in <install>/lib/some.jar (so .jar file - lib dir - should get us the install dir)
        dir = dir.getParentFile().getParentFile();
        dir = FileUtil.canonicalize(dir);
    } catch (NullPointerException e) {
        throw new IllegalStateException("Could not reliably determine the installation directory", e);
    }
    return dir;
}
Also used : ProtectionDomain(java.security.ProtectionDomain) CodeSource(java.security.CodeSource) XmlFile(hudson.XmlFile) File(java.io.File) URL(java.net.URL)

Example 10 with ProtectionDomain

use of java.security.ProtectionDomain in project pinpoint by naver.

the class AccessorInjectionTest method addTraceValue.

@Test
public void addTraceValue() throws Exception {
    final TestClassLoader loader = getTestClassLoader();
    final String javassistClassName = "com.navercorp.pinpoint.test.javasssit.mock.TestObject";
    loader.addTransformer(javassistClassName, new TransformCallback() {

        @Override
        public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
            try {
                logger.info("modify cl:{}", loader);
                InstrumentClass aClass = instrumentor.getInstrumentClass(loader, javassistClassName, classfileBuffer);
                aClass.addField(ObjectTraceValue.class.getName());
                aClass.addField(IntTraceValue.class.getName());
                aClass.addField(IntArrayTraceValue.class.getName());
                aClass.addField(IntegerArrayTraceValue.class.getName());
                aClass.addField(DatabaseInfoTraceValue.class.getName());
                aClass.addField(BindValueTraceValue.class.getName());
                String methodName = "callA";
                aClass.getDeclaredMethod(methodName).addInterceptor("com.navercorp.pinpoint.test.javasssit.TestBeforeInterceptor");
                return aClass.toBytecode();
            } catch (InstrumentException e) {
                e.printStackTrace();
                throw new RuntimeException(e.getMessage(), e);
            }
        }
    });
    Class<?> testObjectClazz = loader.loadClass(javassistClassName);
    final String methodName = "callA";
    logger.info("class:{}", testObjectClazz.toString());
    final Object testObject = testObjectClazz.newInstance();
    Method callA = testObjectClazz.getMethod(methodName);
    callA.invoke(testObject);
    Class<?> objectTraceValue = loader.loadClass(ObjectTraceValue.class.getName());
    Assert.assertTrue("ObjectTraceValue implements fail", objectTraceValue.isInstance(testObject));
    objectTraceValue.getMethod("_$PINPOINT$_setTraceObject", Object.class).invoke(testObject, "a");
    Object get = objectTraceValue.getMethod("_$PINPOINT$_getTraceObject").invoke(testObject);
    Assert.assertEquals("a", get);
    Class<?> intTraceValue = loader.loadClass(IntTraceValue.class.getName());
    Assert.assertTrue("IntTraceValue implements fail", intTraceValue.isInstance(testObject));
    intTraceValue.getMethod("_$PINPOINT$_setTraceInt", int.class).invoke(testObject, 1);
    int a = (Integer) intTraceValue.getMethod("_$PINPOINT$_getTraceInt").invoke(testObject);
    Assert.assertEquals(1, a);
    Class<?> intArrayTraceValue = loader.loadClass(IntArrayTraceValue.class.getName());
    Assert.assertTrue("IntArrayTraceValue implements fail", intArrayTraceValue.isInstance(testObject));
    int[] expectedInts = { 1, 2, 3 };
    intArrayTraceValue.getMethod("_$PINPOINT$_setTraceIntArray", int[].class).invoke(testObject, expectedInts);
    int[] ints = (int[]) intArrayTraceValue.getMethod("_$PINPOINT$_getTraceIntArray").invoke(testObject);
    Assert.assertEquals(expectedInts, ints);
    Class<?> integerArrayTraceValue = loader.loadClass(IntegerArrayTraceValue.class.getName());
    Assert.assertTrue("IntegerArrayTraceValue implements fail", integerArrayTraceValue.isInstance(testObject));
    Integer[] expectedIntegers = { 1, 2 };
    // wrap due to vararg expansion
    Object[] wrappedExpectedIntegers = new Object[] { expectedIntegers };
    integerArrayTraceValue.getMethod("_$PINPOINT$_setTraceIntegerArray", Integer[].class).invoke(testObject, wrappedExpectedIntegers);
    Integer[] integers = (Integer[]) integerArrayTraceValue.getMethod("_$PINPOINT$_getTraceIntegerArray").invoke(testObject);
    Assert.assertArrayEquals(expectedIntegers, integers);
    Class<?> databaseTraceValue = loader.loadClass(DatabaseInfoTraceValue.class.getName());
    Assert.assertTrue("DatabaseInfoTraceValue implements fail", databaseTraceValue.isInstance(testObject));
    databaseTraceValue.getMethod("_$PINPOINT$_setTraceDatabaseInfo", DatabaseInfo.class).invoke(testObject, UnKnownDatabaseInfo.INSTANCE);
    Object databaseInfo = databaseTraceValue.getMethod("_$PINPOINT$_getTraceDatabaseInfo").invoke(testObject);
    Assert.assertSame(UnKnownDatabaseInfo.INSTANCE, databaseInfo);
}
Also used : ProtectionDomain(java.security.ProtectionDomain) Instrumentor(com.navercorp.pinpoint.bootstrap.instrument.Instrumentor) UnKnownDatabaseInfo(com.navercorp.pinpoint.bootstrap.plugin.jdbc.UnKnownDatabaseInfo) DatabaseInfo(com.navercorp.pinpoint.bootstrap.context.DatabaseInfo) TestClassLoader(com.navercorp.pinpoint.test.classloader.TestClassLoader) InstrumentException(com.navercorp.pinpoint.bootstrap.instrument.InstrumentException) Method(java.lang.reflect.Method) TransformCallback(com.navercorp.pinpoint.bootstrap.instrument.transformer.TransformCallback) InstrumentClass(com.navercorp.pinpoint.bootstrap.instrument.InstrumentClass) TestClassLoader(com.navercorp.pinpoint.test.classloader.TestClassLoader) Test(org.junit.Test) JavassistClassTest(com.navercorp.pinpoint.test.javasssit.JavassistClassTest)

Aggregations

ProtectionDomain (java.security.ProtectionDomain)122 InstrumentClass (com.navercorp.pinpoint.bootstrap.instrument.InstrumentClass)44 Instrumentor (com.navercorp.pinpoint.bootstrap.instrument.Instrumentor)44 TransformCallback (com.navercorp.pinpoint.bootstrap.instrument.transformer.TransformCallback)42 CodeSource (java.security.CodeSource)29 InstrumentException (com.navercorp.pinpoint.bootstrap.instrument.InstrumentException)28 Permissions (java.security.Permissions)21 InstrumentMethod (com.navercorp.pinpoint.bootstrap.instrument.InstrumentMethod)20 AccessControlContext (java.security.AccessControlContext)20 URL (java.net.URL)15 Policy (java.security.Policy)15 Test (org.junit.Test)15 Permission (java.security.Permission)14 PermissionCollection (java.security.PermissionCollection)11 File (java.io.File)10 IOException (java.io.IOException)6 Method (java.lang.reflect.Method)6 SocketPermission (java.net.SocketPermission)6 TestClassLoader (com.navercorp.pinpoint.test.classloader.TestClassLoader)5 FilePermission (java.io.FilePermission)5