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.hbase.security.NettyHBaseSaslRpcClientHandler.java

@Override
public void handlerAdded(ChannelHandlerContext ctx) {
    try {//www. j  a  v a  2s .c o m
        byte[] initialResponse = ugi.doAs(new PrivilegedExceptionAction<byte[]>() {

            @Override
            public byte[] run() throws Exception {
                return saslRpcClient.getInitialResponse();
            }
        });
        if (initialResponse != null) {
            writeResponse(ctx, initialResponse);
        }
        tryComplete(ctx);
    } catch (Exception e) {
        // the exception thrown by handlerAdded will not be passed to the exceptionCaught below
        // because netty will remove a handler if handlerAdded throws an exception.
        exceptionCaught(ctx, e);
    }
}

From source file:org.apache.flink.runtime.security.SecurityContext.java

public <T> T runSecured(final FlinkSecuredRunner<T> runner) throws Exception {
    return ugi.doAs(new PrivilegedExceptionAction<T>() {
        @Override//  ww  w  . j  av a2 s.c  o  m
        public T run() throws Exception {
            return runner.run();
        }
    });
}

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

@SuppressWarnings("unchecked")
public void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    Map<String, String[]> pmap = request.getParameterMap();
    try {//from   w  w  w  .ja v  a  2s  .  com
        ServletContext context = getServletContext();
        final FSImage nnImage = (FSImage) context.getAttribute("name.system.image");
        final TransferFsImage ff = new TransferFsImage(pmap, request, response);
        final Configuration conf = (Configuration) getServletContext().getAttribute(JspHelper.CURRENT_CONF);
        if (UserGroupInformation.isSecurityEnabled() && !isValidRequestor(request.getRemoteUser(), conf)) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN,
                    "Only Namenode and Secondary Namenode may access this servlet");
            LOG.warn("Received non-NN/SNN request for image or edits from " + request.getRemoteHost());
            return;
        }

        UserGroupInformation.getCurrentUser().doAs(new PrivilegedExceptionAction<Void>() {

            @Override
            public Void run() throws Exception {
                if (ff.getImage()) {
                    // send fsImage
                    TransferFsImage.getFileServer(response.getOutputStream(), nnImage.getFsImageName());
                } else if (ff.getEdit()) {
                    // send edits
                    TransferFsImage.getFileServer(response.getOutputStream(), nnImage.getFsEditName());
                } else if (ff.putImage()) {
                    // issue a HTTP get request to download the new fsimage 
                    nnImage.validateCheckpointUpload(ff.getToken());
                    reloginIfNecessary().doAs(new PrivilegedExceptionAction<Void>() {
                        @Override
                        public Void run() throws Exception {
                            TransferFsImage.getFileClient(ff.getInfoServer(), "getimage=1",
                                    nnImage.getFsImageNameCheckpoint());
                            return null;
                        }
                    });

                    nnImage.checkpointUploadDone();
                }
                return null;
            }

            // We may have lost our ticket since the last time we tried to open
            // an http connection, so log in just in case.
            private UserGroupInformation reloginIfNecessary() throws IOException {
                // This method is only called on the NN, therefore it is safe to
                // use these key values.
                return UserGroupInformation.loginUserFromKeytabAndReturnUGI(
                        SecurityUtil.getServerPrincipal(conf.get(DFS_NAMENODE_KRB_HTTPS_USER_NAME_KEY),
                                NameNode.getAddress(conf).getHostName()),
                        conf.get(DFSConfigKeys.DFS_NAMENODE_KEYTAB_FILE_KEY));
            }
        });

    } catch (Exception ie) {
        String errMsg = "GetImage failed. " + StringUtils.stringifyException(ie);
        response.sendError(HttpServletResponse.SC_GONE, errMsg);
        throw new IOException(errMsg);
    } finally {
        response.getOutputStream().close();
    }
}

From source file:org.apache.coheigea.bigdata.hdfs.HDFSAccessControlEnforcerTest.java

@org.junit.Test
public void customPermissionsTest() 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/tmpdir/data-file2");
    FSDataOutputStream out = fileSystem.create(file);
    for (int i = 0; i < 1024; ++i) {
        out.write(("data" + i + "\n").getBytes("UTF-8"));
        out.flush();//  ww w . j ava2s .  c o  m
    }
    out.close();

    // Now try to read the file as "bob" - this should be allowed
    UserGroupInformation ugi = UserGroupInformation.createRemoteUser("bob");
    ugi.doAs(new PrivilegedExceptionAction<Void>() {

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

            FileSystem fs = FileSystem.get(conf);

            // Read the file
            FSDataInputStream in = fs.open(file);
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            IOUtils.copy(in, output);
            String content = new String(output.toByteArray());
            Assert.assertTrue(content.startsWith("data0"));

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

    // Now try to read the file as "eve" - this should not be allowed
    ugi = UserGroupInformation.createRemoteUser("eve");
    ugi.doAs(new PrivilegedExceptionAction<Void>() {

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

            FileSystem fs = FileSystem.get(conf);

            // Read the file
            try {
                fs.open(file);
                Assert.fail("Failure expected on an incorrect permission");
            } catch (AccessControlException ex) {
                // expected
            }

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

    // Write to the file as the owner, this should be allowed
    out = fileSystem.append(file);
    out.write(("new data\n").getBytes("UTF-8"));
    out.flush();
    out.close();

    // Now try to write to the file as "bob" - this should not be allowed
    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 (AccessControlException ex) {
                // expected
            }

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

From source file:org.apache.axis2.jaxws.utility.XmlEnumUtils.java

/**
 * @param e enumeration class//from www .j  a  v  a2 s  .com
 * @param convObject Object of conversion type
 * @return Object of enum
 */
public static Object fromValue(final Class e, final Object convObject) {
    Object enumValue = null;
    if (log.isDebugEnabled()) {
        log.debug("fromValue for " + JavaUtils.getObjectIdentity(convObject));
    }
    try {
        enumValue = AccessController.doPrivileged(new PrivilegedExceptionAction() {
            public Object run() throws InvocationTargetException, IllegalAccessException {
                Method m = getConversionMethod(e);
                return m.invoke(null, new Object[] { convObject });
            }
        });
    } catch (PrivilegedActionException pae) {
        throw ExceptionFactory.makeWebServiceException(pae.getException());
    } finally {
        if (log.isDebugEnabled()) {
            log.debug("getEnumValue is" + JavaUtils.getObjectIdentity(enumValue));
        }
    }
    return enumValue;
}

From source file:org.apache.hadoop.mapred.JSPUtil.java

/**
 * Validates if current user can view the job.
 * If user is not authorized to view the job, this method will modify the
 * response and forwards to an error page and returns Job with
 * viewJobAccess flag set to false./*from www . j a va  2 s  . c o m*/
 * @return JobWithViewAccessCheck object(contains JobInProgress object and
 *         viewJobAccess flag). Callers of this method will check the flag
 *         and decide if view should be allowed or not. Job will be null if
 *         the job with given jobid doesnot exist at the JobTracker.
 */
public static JobWithViewAccessCheck checkAccessAndGetJob(final JobTracker jt, JobID jobid,
        HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    final JobInProgress job = jt.getJob(jobid);
    JobWithViewAccessCheck myJob = new JobWithViewAccessCheck(job);

    String user = request.getRemoteUser();
    if (user != null && job != null && jt.areACLsEnabled()) {
        final UserGroupInformation ugi = UserGroupInformation.createRemoteUser(user);
        try {
            ugi.doAs(new PrivilegedExceptionAction<Void>() {
                public Void run() throws IOException, ServletException {

                    // checks job view permission
                    jt.getACLsManager().checkAccess(job, ugi, Operation.VIEW_JOB_DETAILS);
                    return null;
                }
            });
        } catch (AccessControlException e) {
            String errMsg = "User " + ugi.getShortUserName() + " failed to view " + jobid + "!<br><br>"
                    + e.getMessage() + "<hr><a href=\"jobtracker.jsp\">Go back to JobTracker</a><br>";
            JSPUtil.setErrorAndForward(errMsg, request, response);
            myJob.setViewAccess(false);
        } catch (InterruptedException e) {
            String errMsg = " Interrupted while trying to access " + jobid
                    + "<hr><a href=\"jobtracker.jsp\">Go back to JobTracker</a><br>";
            JSPUtil.setErrorAndForward(errMsg, request, response);
            myJob.setViewAccess(false);
        }
    }
    return myJob;
}

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

public Statistics(final Configuration conf, int pollingInterval, CountDownLatch startFlag)
        throws IOException, InterruptedException {
    UserGroupInformation ugi = UserGroupInformation.getLoginUser();
    this.cluster = ugi.doAs(new PrivilegedExceptionAction<JobClient>() {
        public JobClient run() throws IOException {
            return new JobClient(new JobConf(conf));
        }/*from   w ww.j av a2 s .  c  o  m*/
    });

    this.jtPollingInterval = pollingInterval;
    maxJobCompletedInInterval = conf.getInt(MAX_JOBS_COMPLETED_IN_POLL_INTERVAL_KEY, 1);
    this.startFlag = startFlag;
}

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

@Test
public void testRenameBlockedByDestinationParentAccessAcl() throws IOException, InterruptedException {
    try {//from  w  ww  .ja v a 2s.c o  m
        setup();

        setReadOnlyUserAccessAcl(user2.getShortUserName(), subtree2);

        FileSystem user2fs = user2.doAs(new PrivilegedExceptionAction<FileSystem>() {
            @Override
            public FileSystem run() throws Exception {
                return FileSystem.get(conf);
            }
        });

        try {
            user2fs.rename(level1folder1, new Path(subtree2, "newname"));
            fail("Owner permission should block rename");
        } catch (AccessControlException expected) {
            assertTrue("Wrong inode triggered access control exception.",
                    expected.getMessage().contains("inode=\"/subtrees/subtree2\""));
            //Operation should fail.
        }
    } finally {
        teardown();
    }
}

From source file:org.apache.axis2.jaxws.message.databinding.JAXBContextFromClasses.java

/**
 * Utility method that creates a JAXBContext from the 
 * class[] and ClassLoader.//from   w  w  w  .j  a  v a  2 s .c o  m
 * 
 * @param classArray
 * @param cl
 * @return JAXBContext
 * @throws Throwable
 */
private static JAXBContext _newInstance(final Class[] classArray, final ClassLoader cl,
        final Map<String, ?> properties) throws Throwable {
    JAXBContext jaxbContext;
    try {
        jaxbContext = (JAXBContext) AccessController.doPrivileged(new PrivilegedExceptionAction() {
            public Object run() throws JAXBException {
                // Unlike the JAXBContext.newInstance(Class[]) method
                // does now accept a classloader.  To workaround this
                // issue, the classloader is temporarily changed to cl
                Thread currentThread = Thread.currentThread();
                ClassLoader savedClassLoader = currentThread.getContextClassLoader();
                try {
                    currentThread.setContextClassLoader(cl);
                    return JAXBContext.newInstance(classArray, properties);
                } finally {
                    currentThread.setContextClassLoader(savedClassLoader);
                }
            }
        });
    } catch (PrivilegedActionException e) {
        throw ((PrivilegedActionException) e).getException();
    } catch (Throwable t) {
        throw t;
    }
    return jaxbContext;
}

From source file:org.apache.hadoop.hbase.security.access.TestAccessControlFilter.java

@Test
public void testQualifierAccess() throws Exception {
    final HTable table = TEST_UTIL.createTable(TABLE, FAMILY);

    // set permissions
    ADMIN.runAs(new PrivilegedExceptionAction<Object>() {
        @Override//from   w  w  w.  j av  a 2s  .c o m
        public Object run() throws Exception {
            HTable aclmeta = new HTable(TEST_UTIL.getConfiguration(), AccessControlLists.ACL_TABLE_NAME);
            AccessControllerProtocol acls = aclmeta.coprocessorProxy(AccessControllerProtocol.class,
                    Bytes.toBytes("testtable"));
            UserPermission perm = new UserPermission(Bytes.toBytes(READER.getShortName()), TABLE, null,
                    Permission.Action.READ);
            acls.grant(perm);
            perm = new UserPermission(Bytes.toBytes(LIMITED.getShortName()), TABLE, FAMILY, PUBLIC_COL,
                    Permission.Action.READ);
            acls.grant(perm);
            return null;
        }
    });

    // put some test data
    List<Put> puts = new ArrayList<Put>(100);
    for (int i = 0; i < 100; i++) {
        Put p = new Put(Bytes.toBytes(i));
        p.add(FAMILY, PRIVATE_COL, Bytes.toBytes("secret " + i));
        p.add(FAMILY, PUBLIC_COL, Bytes.toBytes("info " + i));
        puts.add(p);
    }
    table.put(puts);

    // test read
    READER.runAs(new PrivilegedExceptionAction<Object>() {
        public Object run() throws Exception {
            Configuration conf = new Configuration(TEST_UTIL.getConfiguration());
            // force a new RS connection
            conf.set("testkey", UUID.randomUUID().toString());
            HTable t = new HTable(conf, TABLE);
            ResultScanner rs = t.getScanner(new Scan());
            int rowcnt = 0;
            for (Result r : rs) {
                rowcnt++;
                int rownum = Bytes.toInt(r.getRow());
                assertTrue(r.containsColumn(FAMILY, PRIVATE_COL));
                assertEquals("secret " + rownum, Bytes.toString(r.getValue(FAMILY, PRIVATE_COL)));
                assertTrue(r.containsColumn(FAMILY, PUBLIC_COL));
                assertEquals("info " + rownum, Bytes.toString(r.getValue(FAMILY, PUBLIC_COL)));
            }
            assertEquals("Expected 100 rows returned", 100, rowcnt);
            return null;
        }
    });

    // test read with qualifier filter
    LIMITED.runAs(new PrivilegedExceptionAction<Object>() {
        public Object run() throws Exception {
            Configuration conf = new Configuration(TEST_UTIL.getConfiguration());
            // force a new RS connection
            conf.set("testkey", UUID.randomUUID().toString());
            HTable t = new HTable(conf, TABLE);
            ResultScanner rs = t.getScanner(new Scan());
            int rowcnt = 0;
            for (Result r : rs) {
                rowcnt++;
                int rownum = Bytes.toInt(r.getRow());
                assertFalse(r.containsColumn(FAMILY, PRIVATE_COL));
                assertTrue(r.containsColumn(FAMILY, PUBLIC_COL));
                assertEquals("info " + rownum, Bytes.toString(r.getValue(FAMILY, PUBLIC_COL)));
            }
            assertEquals("Expected 100 rows returned", 100, rowcnt);
            return null;
        }
    });

    // test as user with no permission
    DENIED.runAs(new PrivilegedExceptionAction() {
        public Object run() throws Exception {
            try {
                Configuration conf = new Configuration(TEST_UTIL.getConfiguration());
                // force a new RS connection
                conf.set("testkey", UUID.randomUUID().toString());
                HTable t = new HTable(conf, TABLE);
                ResultScanner rs = t.getScanner(new Scan());
                fail("Attempt to open scanner should have been denied");
            } catch (AccessDeniedException ade) {
                // expected
            }
            return null;
        }
    });
}