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.fs.FileContextPermissionBase.java

@Test
public void testUgi() throws IOException, InterruptedException {

    UserGroupInformation otherUser = UserGroupInformation.createRemoteUser("otherUser");
    FileContext newFc = otherUser.doAs(new PrivilegedExceptionAction<FileContext>() {

        @Override//from   w w  w .  j  av a2 s . c o  m
        public FileContext run() throws Exception {
            FileContext newFc = FileContext.getFileContext();
            return newFc;
        }

    });
    assertEquals("otherUser", newFc.getUgi().getUserName());
}

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

/**
 * Method used to process the request from the job page based on the 
 * request which it has received. For example like changing priority.
 * /*from  ww w .  ja  va  2s.  c  o m*/
 * @param request HTTP request Object.
 * @param response HTTP response object.
 * @param tracker {@link JobTracker} instance
 * @throws IOException
 * @throws InterruptedException 
 * @throws ServletException 
 */
public static void processButtons(HttpServletRequest request, HttpServletResponse response,
        final JobTracker tracker) throws IOException, InterruptedException, ServletException {

    String user = request.getRemoteUser();
    if (privateActionsAllowed(tracker.conf) && request.getParameter("killJobs") != null) {
        String[] jobs = request.getParameterValues("jobCheckBox");
        if (jobs != null) {
            boolean notAuthorized = false;
            String errMsg = "User " + user + " failed to kill the following job(s)!<br><br>";
            for (String job : jobs) {
                final JobID jobId = JobID.forName(job);
                if (user != null) {
                    UserGroupInformation ugi = UserGroupInformation.createRemoteUser(user);
                    try {
                        ugi.doAs(new PrivilegedExceptionAction<Void>() {
                            public Void run() throws IOException {

                                tracker.killJob(jobId);// checks job modify permission
                                return null;
                            }
                        });
                    } catch (AccessControlException e) {
                        errMsg = errMsg.concat("<br>" + e.getMessage());
                        notAuthorized = true;
                        // We don't return right away so that we can try killing other
                        // jobs that are requested to be killed.
                        continue;
                    }
                } else {// no authorization needed
                    tracker.killJob(jobId);
                }
            }
            if (notAuthorized) {// user is not authorized to kill some/all of jobs
                errMsg = errMsg.concat("<br><hr><a href=\"jobtracker.jsp\">Go back to JobTracker</a><br>");
                setErrorAndForward(errMsg, request, response);
                return;
            }
        }
    }

    if (privateActionsAllowed(tracker.conf) && request.getParameter("changeJobPriority") != null) {
        String[] jobs = request.getParameterValues("jobCheckBox");
        if (jobs != null) {
            final JobPriority jobPri = JobPriority.valueOf(request.getParameter("setJobPriority"));
            boolean notAuthorized = false;
            String errMsg = "User " + user + " failed to set priority for the following job(s)!<br><br>";

            for (String job : jobs) {
                final JobID jobId = JobID.forName(job);
                if (user != null) {
                    UserGroupInformation ugi = UserGroupInformation.createRemoteUser(user);
                    try {
                        ugi.doAs(new PrivilegedExceptionAction<Void>() {
                            public Void run() throws IOException {

                                // checks job modify permission
                                tracker.setJobPriority(jobId, jobPri);
                                return null;
                            }
                        });
                    } catch (AccessControlException e) {
                        errMsg = errMsg.concat("<br>" + e.getMessage());
                        notAuthorized = true;
                        // We don't return right away so that we can try operating on
                        // other jobs.
                        continue;
                    }
                } else {// no authorization needed
                    tracker.setJobPriority(jobId, jobPri);
                }
            }
            if (notAuthorized) {// user is not authorized to kill some/all of jobs
                errMsg = errMsg.concat("<br><hr><a href=\"jobtracker.jsp\">Go back to JobTracker</a><br>");
                setErrorAndForward(errMsg, request, response);
                return;
            }
        }
    }
}

From source file:com.cloudera.alfredo.server.KerberosAuthenticationHandler.java

/**
 * Initializes the authentication handler instance.
 * <p/>//from  w ww  . j  a v a  2  s.c  o  m
 * It creates a Kerberos context using the principal and keytab specified in the configuration.
 * <p/>
 * This method is invoked by the {@link AuthenticationFilter#init} method.
 *
 * @param config configuration properties to initialize the handler.
 *
 * @throws ServletException thrown if the handler could not be initialized.
 */
@Override
public void init(Properties config) throws ServletException {
    try {
        principal = config.getProperty(PRINCIPAL, principal);
        if (principal == null || principal.trim().length() == 0) {
            throw new ServletException("Principal not defined in configuration");
        }
        keytab = config.getProperty(KEYTAB, keytab);
        if (keytab == null || keytab.trim().length() == 0) {
            throw new ServletException("Keytab not defined in configuration");
        }
        if (!new File(keytab).exists()) {
            throw new ServletException("Keytab does not exist: " + keytab);
        }

        Set<Principal> principals = new HashSet<Principal>();
        principals.add(new KerberosPrincipal(principal));
        Subject subject = new Subject(false, principals, new HashSet<Object>(), new HashSet<Object>());

        KerberosConfiguration kerberosConfiguration = new KerberosConfiguration(keytab, principal);

        loginContext = new LoginContext("", subject, null, kerberosConfiguration);
        loginContext.login();

        Subject serverSubject = loginContext.getSubject();
        try {
            gssManager = Subject.doAs(serverSubject, new PrivilegedExceptionAction<GSSManager>() {

                @Override
                public GSSManager run() throws Exception {
                    return GSSManager.getInstance();
                }
            });
        } catch (PrivilegedActionException ex) {
            throw ex.getException();
        }
        LOG.info("Initialized, principal [{}] from keytab [{}]", principal, keytab);
    } catch (Exception ex) {
        throw new ServletException(ex);
    }
}

From source file:org.apache.apex.engine.security.TokenRenewer.java

private long renewTokens(final boolean refresh, boolean checkOnly) throws IOException {
    logger.info("{}", checkOnly ? "Checking renewal" : (refresh ? "Refreshing tokens" : "Renewing tokens"));
    long expiryTime = System.currentTimeMillis() + (refresh ? tokenLifeTime : tokenRenewalInterval);

    final String tokenRenewer = UserGroupInformation.getCurrentUser().getUserName();
    logger.debug("Token renewer {}", tokenRenewer);

    File keyTabFile = null;/*from  w w  w .j a  v a  2  s.  c  om*/
    try (FileSystem fs = FileSystem.newInstance(conf)) {
        String destinationDir = FileUtils.getTempDirectoryPath();
        keyTabFile = FSUtil.copyToLocalFileSystem(fs, destinationDir, destinationFile, hdfsKeyTabFile, conf);

        if (principal == null) {
            //principal = UserGroupInformation.getCurrentUser().getUserName();
            principal = UserGroupInformation.getLoginUser().getUserName();
        }
        logger.debug("Principal {}", principal);
        UserGroupInformation ugi = UserGroupInformation.loginUserFromKeytabAndReturnUGI(principal,
                keyTabFile.getAbsolutePath());
        if (!checkOnly) {
            try {
                UserGroupInformation currUGI = UserGroupInformation.createProxyUser(tokenRenewer, ugi);
                currUGI.doAs(new PrivilegedExceptionAction<Object>() {
                    @Override
                    public Object run() throws Exception {

                        if (refresh) {
                            Credentials creds = new Credentials();
                            try (FileSystem fs1 = FileSystem.newInstance(conf)) {
                                logger.info("Refreshing fs tokens");
                                fs1.addDelegationTokens(tokenRenewer, creds);
                                logger.info("Refreshed tokens");
                            }
                            if (renewRMToken) {
                                try (YarnClient yarnClient = StramClientUtils.createYarnClient(conf)) {
                                    logger.info("Refreshing rm tokens");
                                    new StramClientUtils.ClientRMHelper(yarnClient, conf)
                                            .addRMDelegationToken(tokenRenewer, creds);
                                    logger.info("Refreshed tokens");
                                }
                            }
                            credentials.addAll(creds);
                        } else {
                            Collection<Token<? extends TokenIdentifier>> tokens = credentials.getAllTokens();
                            for (Token<? extends TokenIdentifier> token : tokens) {
                                logger.debug("Token {}", token);
                                if (token.getKind().equals(HDFS_TOKEN_KIND) || (renewRMToken
                                        && token.getKind().equals(RMDelegationTokenIdentifier.KIND_NAME))) {
                                    logger.info("Renewing token {}", token.getKind());
                                    token.renew(conf);
                                    logger.info("Renewed token");
                                }
                            }
                        }

                        return null;
                    }
                });
                UserGroupInformation.getCurrentUser().addCredentials(credentials);
            } catch (InterruptedException e) {
                logger.error("Error while renewing tokens ", e);
                expiryTime = System.currentTimeMillis();
            } catch (IOException e) {
                logger.error("Error while renewing tokens ", e);
                expiryTime = System.currentTimeMillis();
            }
        }
        if (logger.isDebugEnabled()) {
            logger.debug("number of tokens: {}", credentials.getAllTokens().size());
            Iterator<Token<?>> iter = credentials.getAllTokens().iterator();
            while (iter.hasNext()) {
                Token<?> token = iter.next();
                logger.debug("updated token: {}", token);
            }
        }
    } finally {
        if (keyTabFile != null) {
            keyTabFile.delete();
        }
    }
    return expiryTime;
}

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

@org.junit.Test
public void readTest() 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();//from w ww.  j a va  2s .  c  om
    }
    out.close();

    // Change permissions to read-only
    fileSystem.setPermission(file, new FsPermission(FsAction.READ, FsAction.NONE, FsAction.NONE));

    // Now try to read the file as "bob" - this should be allowed (by the policy - user)
    final Configuration conf = new Configuration();
    conf.set("fs.defaultFS", defaultFs);
    conf.set("hadoop.security.authentication", "kerberos");
    UserGroupInformation.setConfiguration(conf);

    String basedir = System.getProperty("basedir");
    if (basedir == null) {
        basedir = new File(".").getCanonicalPath();
    }

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

        public Void run() throws Exception {
            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;
        }
    });
}

From source file:org.nebulaframework.deployment.classloading.GridNodeClassLoader.java

/**
  * Attempts to find the class definition for the given class name, by first
  * searching the local cache, and then through the remote
  * {@link ClassLoadingService}./*w w  w . j a  v a  2 s.  co  m*/
  *
  * @param name
  *            binary name of the class
  *
  * @return The {@code Class<?>} object for requested class, if found
  *
  * @throws ClassNotFoundException
  *             if unable to find the class
  */
@Override
protected Class<?> findClass(final String name) throws ClassNotFoundException {

    log.debug("[GridNodeClassLoader] Finding Class : " + name);

    Class<?> cls = null;
    // Attempt remote load
    try {
        log.debug("[GridNodeClassLoader] Attempt Remote Loading : " + name);

        // Get bytes for class from remote service
        byte[] bytes = AccessController.doPrivileged(new PrivilegedExceptionAction<byte[]>() {

            @Override
            public byte[] run() throws ClassNotFoundException {

                // If we don't know owner
                if (ownerId == null) {
                    return classLoadingService.findClass(jobId, name);
                } else { // If we know owner
                    return classLoadingService.findClass(ownerId, name);
                }
            }

        });

        cls = defineClass(name, bytes, 0, bytes.length, REMOTE_CODESOURCE);
        log.debug("[GridNodeClassLoader] Remote Loaded : " + name);

        return cls;

    } catch (Exception ex) {
        log.warn("[GridNodeClassLoader] Exception while Remote Loading ", ex);
        throw new ClassNotFoundException("Class not found due to Exception", ex);
    }
}

From source file:com.buaa.cfs.fs.FileSystem.java

/**
 * Get a filesystem instance based on the uri, the passed configuration and the user
 *
 * @param uri  of the filesystem//from   ww w . j  a va 2s. c  om
 * @param conf the configuration to use
 * @param user to perform the get as
 *
 * @return the filesystem instance
 *
 * @throws IOException
 * @throws InterruptedException
 */
public static FileSystem get(final URI uri, final Configuration conf, final String user)
        throws IOException, InterruptedException {
    String ticketCachePath = conf.get(CommonConfigurationKeys.KERBEROS_TICKET_CACHE_PATH);
    UserGroupInformation ugi = UserGroupInformation.getBestUGI(ticketCachePath, user);
    return ugi.doAs(new PrivilegedExceptionAction<FileSystem>() {
        @Override
        public FileSystem run() throws IOException {
            return get(uri, conf);
        }
    });
}

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

private void verifyViewJobAsAuthorizedUser(final JobConf myConf, final JobID jobId, String authorizedUser)
        throws IOException, InterruptedException {
    UserGroupInformation authorizedUGI = UserGroupInformation.createUserForTesting(authorizedUser,
            new String[] {});
    authorizedUGI.doAs(new PrivilegedExceptionAction<Object>() {
        @SuppressWarnings("null")
        @Override/*from   w  w  w .j a  v  a 2 s .  c om*/
        public Object run() throws Exception {
            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 with getCounters
            try {
                myJob.getCounters();
            } catch (IOException ioe) {
                fail("Unexpected.. exception.. " + ioe);
            }

            // Tests authorization  with getTaskReports
            try {
                client.getCleanupTaskReports(jobId);
            } catch (IOException ioe) {
                fail("Unexpected.. exception.. " + ioe);
            }

            return null;
        }
    });
}

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

@org.junit.Test
public void testChangedPermissionsTest() throws Exception {
    FileSystem fileSystem = hdfsCluster.getFileSystem();

    // Write a file
    final Path file = new Path("/tmp/tmpdir/data-file3");
    FSDataOutputStream out = fileSystem.create(file);
    for (int i = 0; i < 1024; ++i) {
        out.write(("data" + i + "\n").getBytes("UTF-8"));
        out.flush();//www  .  j  av a2s .co m
    }
    out.close();

    // Change permissions to read-only
    fileSystem.setPermission(file, new FsPermission(FsAction.READ, FsAction.NONE, FsAction.NONE));

    // Now try to read the file as "bob" - this should fail
    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
            try {
                FSDataInputStream in = fs.open(file);
                ByteArrayOutputStream output = new ByteArrayOutputStream();
                IOUtils.copy(in, output);
                Assert.fail("Failure expected on an incorrect permission");
            } catch (AccessControlException ex) {
                // expected
            }

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

}

From source file:SecuritySupport.java

FileInputStream getFileInputStream(final File file) throws FileNotFoundException {
    try {/*w w  w.ja  va  2 s  . c om*/
        return (FileInputStream) AccessController.doPrivileged(new PrivilegedExceptionAction() {
            public Object run() throws FileNotFoundException {
                return new FileInputStream(file);
            }
        });
    } catch (PrivilegedActionException e) {
        throw (FileNotFoundException) e.getException();
    }
}