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:org.apache.hadoop.mapred.TestJobACLs.java

private void verifyViewJobAsUnauthorizedUser(final JobConf myConf, final JobID jobId, String unauthorizedUser)
        throws IOException, InterruptedException {
    UserGroupInformation unauthorizedUGI = UserGroupInformation.createUserForTesting(unauthorizedUser,
            new String[] {});
    unauthorizedUGI.doAs(new PrivilegedExceptionAction<Object>() {
        @SuppressWarnings("null")
        @Override// w  w  w  .  j av  a 2 s .  c  o m
        public Object run() {
            RunningJob myJob = null;
            JobClient client = null;
            try {
                client = new JobClient(myConf);
                myJob = client.getJob(jobId);
            } catch (Exception e) {
                fail("Exception .." + e);
            }

            assertNotNull("Job " + jobId + " is not known to the JobTracker!", myJob);

            // Tests authorization failure with getCounters
            try {
                myJob.getCounters();
                fail("AccessControlException expected..");
            } catch (IOException ioe) {
                assertTrue(ioe.getMessage().contains("AccessControlException"));
            }

            // Tests authorization failure with getTaskReports
            try {
                client.getSetupTaskReports(jobId);
                fail("AccessControlException expected..");
            } catch (IOException ioe) {
                assertTrue(ioe.getMessage().contains("AccessControlException"));
            }

            return null;
        }
    });
}

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

@Override
protected void verifyGet(final byte[] row, final String visString, final int expected,
        final boolean nullExpected, final String... auths) throws IOException, InterruptedException {
    PrivilegedExceptionAction<Void> scanAction = new PrivilegedExceptionAction<Void>() {

        public Void run() throws Exception {
            try (Connection connection = ConnectionFactory.createConnection(conf1);
                    Table table2 = connection.getTable(TABLE_NAME)) {
                CellScanner cellScanner;
                Cell current;/*from   ww  w  .ja v  a  2 s. com*/
                Get get = new Get(row);
                get.setAuthorizations(new Authorizations(auths));
                Result result = table2.get(get);
                cellScanner = result.cellScanner();
                boolean advance = cellScanner.advance();
                if (nullExpected) {
                    assertTrue(!advance);
                    return null;
                }
                current = cellScanner.current();
                assertArrayEquals(CellUtil.cloneRow(current), row);
                assertEquals(expected, TestCoprocessorForTagsAtSink.tags.size());
                boolean foundNonVisTag = false;
                for (Tag t : TestCoprocessorForTagsAtSink.tags) {
                    if (t.getType() == NON_VIS_TAG_TYPE) {
                        assertEquals(TEMP, Bytes.toString(t.getValue()));
                        foundNonVisTag = true;
                        break;
                    }
                }
                doAssert(row, visString);
                assertTrue(foundNonVisTag);
                return null;
            }
        }
    };
    USER1.runAs(scanAction);
}

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

@Test
public void testListLabels() throws Throwable {
    PrivilegedExceptionAction<ListLabelsResponse> action = new PrivilegedExceptionAction<ListLabelsResponse>() {
        public ListLabelsResponse run() throws Exception {
            ListLabelsResponse response = null;
            try (Connection conn = ConnectionFactory.createConnection(conf)) {
                response = VisibilityClient.listLabels(conn, null);
            } catch (Throwable e) {
                fail("Should not have thrown exception");
            }/*from  w w w . j  av a2 s.  co  m*/
            // The addLabels() in setup added:
            // { SECRET, TOPSECRET, CONFIDENTIAL, PUBLIC, PRIVATE, COPYRIGHT, ACCENT,
            //  UNICODE_VIS_TAG, UC1, UC2 };
            // The previous tests added 2 more labels: ABC, XYZ
            // The 'system' label is excluded.
            List<ByteString> labels = response.getLabelList();
            assertEquals(12, labels.size());
            assertTrue(labels.contains(ByteString.copyFrom(SECRET.getBytes())));
            assertTrue(labels.contains(ByteString.copyFrom(TOPSECRET.getBytes())));
            assertTrue(labels.contains(ByteString.copyFrom(CONFIDENTIAL.getBytes())));
            assertTrue(labels.contains(ByteString.copyFrom("ABC".getBytes())));
            assertTrue(labels.contains(ByteString.copyFrom("XYZ".getBytes())));
            assertFalse(labels.contains(ByteString.copyFrom(SYSTEM_LABEL.getBytes())));
            return null;
        }
    };
    SUPERUSER.runAs(action);
}

From source file:org.apache.hadoop.hdfs.TestShortCircuitLocalRead.java

@Test
public void testGetBlockLocalPathInfo() throws IOException, InterruptedException {
    final Configuration conf = new Configuration();
    conf.set(DFSConfigKeys.DFS_BLOCK_LOCAL_PATH_ACCESS_USER_KEY, "alloweduser");
    MiniDFSCluster cluster = new MiniDFSCluster(conf, 1, true, null);
    cluster.waitActive();/*from w  ww. ja v  a 2s .c  om*/
    final DataNode dn = cluster.getDataNodes().get(0);
    FileSystem fs = cluster.getFileSystem();
    try {
        DFSTestUtil.createFile(fs, new Path("/tmp/x"), 16, (short) 1, 23);
        UserGroupInformation aUgi = UserGroupInformation.createRemoteUser("alloweduser");
        LocatedBlocks lb = cluster.getNameNode().getBlockLocations("/tmp/x", 0, 16);
        // Create a new block object, because the block inside LocatedBlock at
        // namenode is of type BlockInfo.
        Block blk = new Block(lb.get(0).getBlock());
        Token<BlockTokenIdentifier> token = lb.get(0).getBlockToken();
        final DatanodeInfo dnInfo = lb.get(0).getLocations()[0];
        ClientDatanodeProtocol proxy = aUgi.doAs(new PrivilegedExceptionAction<ClientDatanodeProtocol>() {
            @Override
            public ClientDatanodeProtocol run() throws Exception {
                return DFSClient.createClientDatanodeProtocolProxy(dnInfo, conf, 60000);
            }
        });

        //This should succeed
        BlockLocalPathInfo blpi = proxy.getBlockLocalPathInfo(blk, token);
        Assert.assertEquals(dn.data.getBlockLocalPathInfo(blk).getBlockPath(), blpi.getBlockPath());
        RPC.stopProxy(proxy);

        // Now try with a not allowed user.
        UserGroupInformation bUgi = UserGroupInformation.createRemoteUser("notalloweduser");
        proxy = bUgi.doAs(new PrivilegedExceptionAction<ClientDatanodeProtocol>() {
            @Override
            public ClientDatanodeProtocol run() throws Exception {
                return DFSClient.createClientDatanodeProtocolProxy(dnInfo, conf, 60000);
            }
        });
        try {
            proxy.getBlockLocalPathInfo(blk, token);
            Assert.fail("The call should have failed as " + bUgi.getShortUserName()
                    + " is not allowed to call getBlockLocalPathInfo");
        } catch (IOException ex) {
            Assert.assertTrue(ex.getMessage().contains("not allowed to call getBlockLocalPathInfo"));
        } finally {
            RPC.stopProxy(proxy);
        }
    } finally {
        fs.close();
        cluster.shutdown();
    }
}

From source file:org.apache.hadoop.ipc.MiniRPCBenchmark.java

void connectToServerAndGetDelegationToken(final Configuration conf, final InetSocketAddress addr)
        throws IOException {
    MiniProtocol client = null;/*from w  w w.ja  v a 2  s  .  com*/
    try {
        UserGroupInformation current = UserGroupInformation.getCurrentUser();
        UserGroupInformation proxyUserUgi = UserGroupInformation.createProxyUserForTesting(MINI_USER, current,
                GROUP_NAMES);

        try {
            client = proxyUserUgi.doAs(new PrivilegedExceptionAction<MiniProtocol>() {
                @Override
                public MiniProtocol run() throws IOException {
                    MiniProtocol p = RPC.getProxy(MiniProtocol.class, MiniProtocol.versionID, addr, conf);
                    Token<TestDelegationTokenIdentifier> token;
                    token = p.getDelegationToken(new Text(RENEWER));
                    currentUgi = UserGroupInformation.createUserForTesting(MINI_USER, GROUP_NAMES);
                    SecurityUtil.setTokenService(token, addr);
                    currentUgi.addToken(token);
                    return p;
                }
            });
        } catch (InterruptedException e) {
            Assert.fail(Arrays.toString(e.getStackTrace()));
        }
    } finally {
        RPC.stopProxy(client);
    }
}

From source file:org.apache.bsf.BSFManager.java

/**
 * Apply the given anonymous function of the given language to the given
 * parameters and return the resulting value.
 *
 * @param lang language identifier//  www .jav a 2  s.c  om
 * @param source (context info) the source of this expression
 (e.g., filename)
 * @param lineNo (context info) the line number in source for expr
 * @param columnNo (context info) the column number in source for expr
 * @param funcBody the multi-line, value returning script to evaluate
 * @param paramNames the names of the parameters above assumes
 * @param arguments values of the above parameters
 *
 * @exception BSFException if anything goes wrong while running the script
 */
public Object apply(String lang, String source, int lineNo, int columnNo, Object funcBody, Vector paramNames,
        Vector arguments) throws BSFException {
    logger.debug("BSFManager:apply");

    final BSFEngine e = loadScriptingEngine(lang);
    final String sourcef = source;
    final int lineNof = lineNo, columnNof = columnNo;
    final Object funcBodyf = funcBody;
    final Vector paramNamesf = paramNames;
    final Vector argumentsf = arguments;
    Object result = null;

    try {
        final Object resultf = AccessController.doPrivileged(new PrivilegedExceptionAction() {
            public Object run() throws Exception {
                return e.apply(sourcef, lineNof, columnNof, funcBodyf, paramNamesf, argumentsf);
            }
        });
        result = resultf;
    } catch (PrivilegedActionException prive) {

        logger.error("Exception: ", prive);
        throw (BSFException) prive.getException();
    }

    return result;
}

From source file:org.apache.axiom.om.util.StAXUtils.java

public static XMLStreamReader createXMLStreamReader(StAXParserConfiguration configuration, final InputStream in,
        final String encoding) throws XMLStreamException {

    final XMLInputFactory inputFactory = getXMLInputFactory(configuration);
    try {/*from w  ww  .  j  av  a2 s.c om*/
        XMLStreamReader reader = (XMLStreamReader) AccessController
                .doPrivileged(new PrivilegedExceptionAction() {
                    public Object run() throws XMLStreamException {
                        return inputFactory.createXMLStreamReader(in, encoding);
                    }
                });
        if (isDebugEnabled) {
            log.debug("XMLStreamReader is " + reader.getClass().getName());
        }
        return reader;
    } catch (PrivilegedActionException pae) {
        throw (XMLStreamException) pae.getException();
    }
}

From source file:org.apache.hadoop.mapred.gridmix.Gridmix.java

public int run(final String[] argv) throws IOException, InterruptedException {
    int val = -1;
    final Configuration conf = getConf();
    UserGroupInformation.setConfiguration(conf);
    UserGroupInformation ugi = UserGroupInformation.getLoginUser();

    val = ugi.doAs(new PrivilegedExceptionAction<Integer>() {
        public Integer run() throws Exception {
            return runJob(conf, argv);
        }/*from   ww  w  . java 2s. co  m*/
    });
    return val;
}

From source file:com.trendmicro.hdfs.webdav.HDFSResource.java

@Override
public void copy(final DavResource resource, final boolean shallow) throws DavException {
    if (!exists()) {
        throw new DavException(DavServletResponse.SC_NOT_FOUND);
    }// ww w. j av a2  s  .co  m
    if (!shallow || !isCollection()) {
        final HDFSResource dfsResource = (HDFSResource) resource;
        final Path destPath = dfsResource.getPath();
        if (LOG.isDebugEnabled()) {
            LOG.debug("Copying '" + path.toUri().getPath() + "' to '" + destPath.toUri().getPath() + "'");
        }
        try {
            user.doAs(new PrivilegedExceptionAction<Void>() {
                public Void run() throws Exception {
                    FileSystem fs = FileSystem.get(conf);
                    FileUtil.copy(fs, path, fs, destPath, false, conf);
                    return null;
                }
            });
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return;
    }
    // TODO: Currently no support for shallow copy; however, this is
    // only relevant if the source resource is a collection
    throw new DavException(DavServletResponse.SC_FORBIDDEN, "Shallow copies are not supported");
}

From source file:com.flipkart.fdp.migration.distcp.security.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 2s  .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>() {

            public Void run() throws Exception {
                GSSContext gssContext = null;
                try {
                    GSSManager gssManager = GSSManager.getInstance();
                    Oid oid = KerberosUtil.getOidInstance("NT_GSS_KRB5_PRINCIPAL");
                    String sp = KerberosAuthenticator2.this.servicePrincipal;
                    if (sp == null) {
                        sp = "HTTP/" + KerberosAuthenticator2.this.url.getHost();
                    }
                    GSSName serviceName = gssManager.createName(sp, 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);
}