Example usage for java.security PrivilegedExceptionAction PrivilegedExceptionAction

List of usage examples for java.security PrivilegedExceptionAction PrivilegedExceptionAction

Introduction

In this page you can find the example usage for java.security PrivilegedExceptionAction PrivilegedExceptionAction.

Prototype

PrivilegedExceptionAction

Source Link

Usage

From source file:com.intel.hadoopRPCBenchmark.HadoopRPCBenchmarkEngine.java

private BenchmarkEngineProtocol getRPCProxy() throws Exception {
    final BenchmarkEngineProtocol proxy;
    final InetSocketAddress addr = NetUtils.getConnectAddress(server);

    if (clientUgi != null) {
        proxy = clientUgi.doAs(new PrivilegedExceptionAction<BenchmarkEngineProtocol>() {
            public BenchmarkEngineProtocol run() throws IOException {
                return new BenchmarkEngineProtocolClientSideTranslatorPB(addr, conf);
            }/*from w w  w . ja va 2  s.  com*/
        });
    } else {
        proxy = new BenchmarkEngineProtocolClientSideTranslatorPB(addr, conf);
    }

    return proxy;
}

From source file:org.apache.coheigea.bigdata.hdfs.ranger.HDFSRangerTest.java

@org.junit.Test
public void writeTest() throws Exception {

    FileSystem fileSystem = hdfsCluster.getFileSystem();

    // Write a file - the AccessControlEnforcer won't be invoked as we are the "superuser"
    final Path file = new Path("/tmp/tmpdir2/data-file3");
    FSDataOutputStream out = fileSystem.create(file);
    for (int i = 0; i < 1024; ++i) {
        out.write(("data" + i + "\n").getBytes("UTF-8"));
        out.flush();/*from  w ww.  j a  v  a2s.co m*/
    }
    out.close();

    // Now try to write to the file as "bob" - this should be allowed (by the policy - user)
    UserGroupInformation ugi = UserGroupInformation.createUserForTesting("bob", new String[] {});
    ugi.doAs(new PrivilegedExceptionAction<Void>() {

        public Void run() throws Exception {
            Configuration conf = new Configuration();
            conf.set("fs.defaultFS", defaultFs);

            FileSystem fs = FileSystem.get(conf);

            // Write to the file
            fs.append(file);

            fs.close();
            return null;
        }
    });

    // Now try to write to the file as "alice" - this should be allowed (by the policy - group)
    ugi = UserGroupInformation.createUserForTesting("alice", new String[] { "IT" });
    ugi.doAs(new PrivilegedExceptionAction<Void>() {

        public Void run() throws Exception {
            Configuration conf = new Configuration();
            conf.set("fs.defaultFS", defaultFs);

            FileSystem fs = FileSystem.get(conf);

            // Write to the file
            fs.append(file);

            fs.close();
            return null;
        }
    });

    // Now try to read the file as unknown user "eve" - this should not be allowed
    ugi = UserGroupInformation.createUserForTesting("eve", new String[] {});
    ugi.doAs(new PrivilegedExceptionAction<Void>() {

        public Void run() throws Exception {
            Configuration conf = new Configuration();
            conf.set("fs.defaultFS", defaultFs);

            FileSystem fs = FileSystem.get(conf);

            // Write to the file
            try {
                fs.append(file);
                Assert.fail("Failure expected on an incorrect permission");
            } catch (RemoteException ex) {
                // expected
                Assert.assertTrue(RangerAccessControlException.class.getName().equals(ex.getClassName()));
            }

            fs.close();
            return null;
        }
    });

    // Now try to read the file as known user "dave" - this should not be allowed, as he doesn't have the correct permissions
    ugi = UserGroupInformation.createUserForTesting("dave", new String[] {});
    ugi.doAs(new PrivilegedExceptionAction<Void>() {

        public Void run() throws Exception {
            Configuration conf = new Configuration();
            conf.set("fs.defaultFS", defaultFs);

            FileSystem fs = FileSystem.get(conf);

            // Write to the file
            try {
                fs.append(file);
                Assert.fail("Failure expected on an incorrect permission");
            } catch (RemoteException ex) {
                // expected
                Assert.assertTrue(RangerAccessControlException.class.getName().equals(ex.getClassName()));
            }

            fs.close();
            return null;
        }
    });
}

From source file:org.apache.falcon.hadoop.HadoopClientFactory.java

/**
 * This method validates if the execute url is able to reach the MR endpoint.
 *
 * @param executeUrl jt url or RM url//from  w ww  .jav a  2  s .co m
 * @throws IOException
 */
public void validateJobClient(String executeUrl) throws IOException {
    final JobConf jobConf = new JobConf();
    jobConf.set(MR_JT_ADDRESS_KEY, executeUrl);
    jobConf.set(YARN_RM_ADDRESS_KEY, executeUrl);

    UserGroupInformation loginUser = UserGroupInformation.getLoginUser();
    try {
        JobClient jobClient = loginUser.doAs(new PrivilegedExceptionAction<JobClient>() {
            public JobClient run() throws Exception {
                return new JobClient(jobConf);
            }
        });

        jobClient.getClusterStatus().getMapTasks();
    } catch (InterruptedException e) {
        throw new IOException("Exception creating job client:" + e.getMessage(), e);
    }
}

From source file:org.apache.hadoop.hdfs.server.namenode.TestSubtreeLockACL.java

@Test
public void testSubtreeDeleteBlockedByInheritedDefaultAcl() throws IOException, InterruptedException {
    try {/*from  w  w  w .j a v a  2s . com*/
        setup();

        //Deny access via default acl down subtree1
        setDenyUserDefaultAcl(user2.getShortUserName(), subtree1);

        //Try to delete subtree1. Should fail because of access acl down the tree.
        FileSystem user2fs = user2.doAs(new PrivilegedExceptionAction<FileSystem>() {
            @Override
            public FileSystem run() throws Exception {
                return FileSystem.get(conf);
            }
        });

        try {
            user2fs.delete(subtree1, true);
            fail("Acl should block delete");
        } catch (AccessControlException expected) {
            assertTrue("Wrong inode triggered access control exception.",
                    expected.getMessage().contains("projectedInode=\"level1folder1\""));
            //Operation should fail.
        }

    } finally {
        teardown();
    }
}

From source file:com.thinkbiganalytics.kerberos.TestKerberosKinit.java

private void testHdfsAsKerberosUser(final String configResources, final String keytab, final String principal,
        final String environment, final String hdfsUrl) {
    final String path = "/user";
    try {//w ww  . j av  a2  s.c  o m
        final Configuration configuration = TestKerberosKinit.createConfigurationFromList(configResources);
        UserGroupInformation realugi = TestKerberosKinit.generateKerberosTicket(configuration, keytab,
                principal);
        System.out.println(" ");
        System.out.println("Sucessfully got a kerberos ticket in the JVM");
        System.out.println("current user is: " + realugi.getUserName());

        realugi.doAs(new PrivilegedExceptionAction<Object>() {
            public Object run() {
                try {
                    searchHDFS(configuration, environment, path, hdfsUrl);
                } catch (Exception e) {
                    throw new RuntimeException("Error testing HDFS with Kerberos", e);
                }
                return null;
            }
        });

    } catch (Exception e) {
        System.out.println("Error testing HDFS\n\n");
        e.printStackTrace();
    }
}

From source file:org.apache.hadoop.hbase.LocalHBaseCluster.java

public JVMClusterUtil.MasterThread addMaster(final Configuration c, final int index, User user)
        throws IOException, InterruptedException {
    return user.runAs(new PrivilegedExceptionAction<JVMClusterUtil.MasterThread>() {
        public JVMClusterUtil.MasterThread run() throws Exception {
            return addMaster(c, index);
        }//from   www .  jav a 2 s .  co  m
    });
}

From source file:org.apache.hadoop.hdfs.server.namenode.TestFsck.java

/** Test fsck with permission set on inodes */
public void testFsckPermission() throws Exception {
    final DFSTestUtil util = new DFSTestUtil(getClass().getSimpleName(), 20, 3, 8 * 1024);
    final Configuration conf = new Configuration();
    conf.setLong("dfs.blockreport.intervalMsec", 10000L);

    MiniDFSCluster cluster = null;/*from   w  ww  .j  a  v  a 2s .  co m*/
    try {
        // Create a cluster with the current user, write some files
        cluster = new MiniDFSCluster(conf, 4, true, null);
        final MiniDFSCluster c2 = cluster;
        final String dir = "/dfsck";
        final Path dirpath = new Path(dir);
        final FileSystem fs = c2.getFileSystem();

        util.createFiles(fs, dir);
        util.waitReplication(fs, dir, (short) 3);
        fs.setPermission(dirpath, new FsPermission((short) 0700));

        // run DFSck as another user, should fail with permission issue
        UserGroupInformation fakeUGI = UserGroupInformation.createUserForTesting("ProbablyNotARealUserName",
                new String[] { "ShangriLa" });
        fakeUGI.doAs(new PrivilegedExceptionAction<Object>() {
            @Override
            public Object run() throws Exception {
                System.out.println(runFsck(conf, -1, true, dir));
                return null;
            }
        });

        //set permission and try DFSck again as the fake user, should succeed
        fs.setPermission(dirpath, new FsPermission((short) 0777));
        fakeUGI.doAs(new PrivilegedExceptionAction<Object>() {
            @Override
            public Object run() throws Exception {
                final String outStr = runFsck(conf, 0, true, dir);
                System.out.println(outStr);
                assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
                return null;
            }
        });

        util.cleanup(fs, dir);
    } finally {
        if (cluster != null) {
            cluster.shutdown();
        }
    }
}

From source file:org.apache.hadoop.hbase.security.visibility.TestVisibilityLabelsWithDeletes.java

@Test
public void testVisibilityLabelsWithDeleteColumns() throws Throwable {
    setAuths();//from w w w .j  av  a2  s  . c om
    final TableName tableName = TableName.valueOf(TEST_NAME.getMethodName());

    try (Table table = createTableAndWriteDataWithLabels(SECRET + "&" + TOPSECRET, SECRET)) {
        PrivilegedExceptionAction<Void> actiona = new PrivilegedExceptionAction<Void>() {
            @Override
            public Void run() throws Exception {
                try (Connection connection = ConnectionFactory.createConnection(conf);
                        Table table = connection.getTable(tableName)) {
                    Delete d = new Delete(row1);
                    d.setCellVisibility(new CellVisibility(TOPSECRET + "&" + SECRET));
                    d.addColumns(fam, qual);
                    table.delete(d);
                } catch (Throwable t) {
                    throw new IOException(t);
                }
                return null;
            }
        };
        SUPERUSER.runAs(actiona);

        TEST_UTIL.getAdmin().flush(tableName);
        Scan s = new Scan();
        s.setAuthorizations(new Authorizations(SECRET, PRIVATE, CONFIDENTIAL));
        ResultScanner scanner = table.getScanner(s);
        Result[] next = scanner.next(3);
        assertTrue(next.length == 1);
        CellScanner cellScanner = next[0].cellScanner();
        cellScanner.advance();
        Cell current = cellScanner.current();
        assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), current.getRowLength(), row2, 0,
                row2.length));

    }
}

From source file:main.client.http.KerberosAuthenticator2.java

/**
 * Implements the SPNEGO authentication sequence interaction using the
 * current default principal in the Kerberos cache (normally set via kinit).
 * /*from w  ww .  j a  v  a 2  s  .c  om*/
 * @param token
 *            the authentication token being used for the user.
 * 
 * @throws IOException
 *             if an IO error occurred.
 * @throws AuthenticationException
 *             if an authentication error occurred.
 */
private void doSpnegoSequence(AuthenticatedURL.Token token) throws IOException, AuthenticationException {
    try {

        /*      //   
                   AccessControlContext context = AccessController.getContext();
                 Subject subject = Subject.getSubject(context);
                 if (subject == null) {
                    subject = new Subject();
                    LoginContext login = new LoginContext("", subject, null,
          new KerberosConfiguration());
                    login.login();
                 }
        */

        LoginContext loginContext = new LoginContext("", null,
                new KerberosClientCallbackHandler(username, password), new LoginConfig(this.debug));
        loginContext.login();
        if (LOG.isDebugEnabled()) {
            LOG.debug("Kerberos authenticated user: " + loginContext.getSubject());
        }
        Subject subject = loginContext.getSubject();

        Subject.doAs(subject, new PrivilegedExceptionAction<Void>() {

            @Override
            public Void run() throws Exception {
                GSSContext gssContext = null;
                try {
                    GSSManager gssManager = GSSManager.getInstance();
                    String servicePrincipal = "HTTP/" + KerberosAuthenticator2.this.url.getHost();
                    Oid oid = KerberosUtil.getOidInstance("NT_GSS_KRB5_PRINCIPAL");
                    GSSName serviceName = gssManager.createName(servicePrincipal, oid);
                    oid = KerberosUtil.getOidInstance("GSS_KRB5_MECH_OID");
                    gssContext = gssManager.createContext(serviceName, oid, null, GSSContext.DEFAULT_LIFETIME);
                    gssContext.requestCredDeleg(true);
                    gssContext.requestMutualAuth(true);

                    byte[] inToken = new byte[0];
                    byte[] outToken;
                    boolean established = false;

                    // Loop while the context is still not established
                    while (!established) {
                        outToken = gssContext.initSecContext(inToken, 0, inToken.length);
                        if (outToken != null) {
                            sendToken(outToken);
                        }

                        if (!gssContext.isEstablished()) {
                            inToken = readToken();
                        } else {
                            established = true;
                        }
                    }
                } finally {
                    if (gssContext != null) {
                        gssContext.dispose();
                        gssContext = null;
                    }
                }
                return null;
            }
        });
    } catch (PrivilegedActionException ex) {
        throw new AuthenticationException(ex.getException());
    } catch (LoginException ex) {
        throw new AuthenticationException(ex);
    }
    AuthenticatedURL.extractToken(conn, token);
}

From source file:org.apache.catalina.security.SecurityUtil.java

/**
 * Perform work as a particular </code>Subject</code>. Here the work
 * will be granted to a <code>null</code> subject. 
 *
 * @param methodName the method to apply the security restriction
 * @param targetObject the <code>Servlet</code> on which the method will
 * be called./*from ww w . java  2s  .  com*/
 * @param targetType <code>Class</code> array used to instanciate a 
 * <code>Method</code> object.
 * @param targetArgumentst <code>Object</code> array contains the 
 * runtime parameters instance.
 * @param principal the <code>Principal</code> to which the security 
 * privilege apply..
 */
private static void execute(final Method method, final Object targetObject, final Object[] targetArguments,
        Principal principal) throws java.lang.Exception {

    try {
        Subject subject = null;
        PrivilegedExceptionAction pea = new PrivilegedExceptionAction() {
            public Object run() throws Exception {
                method.invoke(targetObject, targetArguments);
                return null;
            }
        };

        // The first argument is always the request object
        if (targetArguments != null && targetArguments[0] instanceof HttpServletRequest) {
            HttpServletRequest request = (HttpServletRequest) targetArguments[0];

            HttpSession session = request.getSession(false);
            if (session != null) {
                subject = (Subject) session.getAttribute(Globals.SUBJECT_ATTR);

                if (subject == null) {
                    subject = new Subject();
                    session.setAttribute(Globals.SUBJECT_ATTR, subject);
                }
            }
        }

        Subject.doAsPrivileged(subject, pea, null);
    } catch (PrivilegedActionException pe) {
        Throwable e = ((InvocationTargetException) pe.getException()).getTargetException();

        if (log.isDebugEnabled()) {
            log.debug(sm.getString("SecurityUtil.doAsPrivilege"), e);
        }

        if (e instanceof UnavailableException)
            throw (UnavailableException) e;
        else if (e instanceof ServletException)
            throw (ServletException) e;
        else if (e instanceof IOException)
            throw (IOException) e;
        else if (e instanceof RuntimeException)
            throw (RuntimeException) e;
        else
            throw new ServletException(e.getMessage(), e);
    }
}