List of usage examples for java.security PrivilegedExceptionAction PrivilegedExceptionAction
PrivilegedExceptionAction
From source file:org.wso2.carbon.mediator.kerberos.KerberosMediator.java
/** * Create GSSCredential for the user./*from ww w .j av a2s.co m*/ * * @param callbackHandler callback handler. * @param mechanismOId Oid for the mechanism. * @return GSSCredential. * @throws LoginException * @throws PrivilegedActionException * @throws GSSException */ private GSSCredential createClientCredentials(CallbackHandler callbackHandler, final Oid mechanismOId) throws LoginException, PrivilegedActionException, GSSException { LoginContext loginContext; String loginName; if (StringUtils.isNotEmpty(getLoginContextName())) { loginName = getLoginContextName(); } else { loginName = "com.sun.security.auth.module.Krb5LoginModule"; } if (callbackHandler != null) { loginContext = new LoginContext(loginName, callbackHandler); } else { loginContext = new LoginContext(loginName); } loginContext.login(); if (log.isDebugEnabled()) { log.debug("Pre-authentication successful for with Kerberos Server."); } // Create client credentials from pre authentication with the AD final GSSName clientName = gssManager.createName(clientPrincipalValue, GSSName.NT_USER_NAME); final PrivilegedExceptionAction<GSSCredential> action = new PrivilegedExceptionAction<GSSCredential>() { public GSSCredential run() throws GSSException { return gssManager.createCredential(clientName.canonicalize(mechanismOId), GSSCredential.DEFAULT_LIFETIME, mechanismOId, GSSCredential.INITIATE_ONLY); } }; if (log.isDebugEnabled()) { Set<Principal> principals = loginContext.getSubject().getPrincipals(); String principalName = null; if (principals != null) { principalName = principals.toString(); } log.debug("Creating gss credentials as principal : " + principalName); } return Subject.doAs(loginContext.getSubject(), action); }
From source file:org.apache.hadoop.mapred.TestJobACLs.java
private void verifyModifyJobAsUnauthorizedUser(final JobConf clusterConf, final JobID jobId, String unauthorizedUser) throws IOException, InterruptedException { UserGroupInformation unauthorizedUGI = UserGroupInformation.createUserForTesting(unauthorizedUser, new String[] {}); unauthorizedUGI.doAs(new PrivilegedExceptionAction<Object>() { @SuppressWarnings("null") @Override//ww w . jav a2 s.com public Object run() { RunningJob myJob = null; try { JobClient client = new JobClient(clusterConf); myJob = client.getJob(jobId); } catch (Exception e) { fail("Exception .." + e); } assertNotNull("Job " + jobId + " is not known to the JobTracker!", myJob); // Tests authorization failure with killJob try { myJob.killJob(); fail("AccessControlException expected.."); } catch (IOException ioe) { assertTrue(ioe.getMessage().contains("AccessControlException")); } // Tests authorization failure with setJobPriority try { myJob.setJobPriority(JobPriority.HIGH.toString()); fail("AccessControlException expected.."); } catch (IOException ioe) { assertTrue(ioe.getMessage().contains("AccessControlException")); } return null; } }); }
From source file:org.apache.axis2.jaxws.util.WSDL4JWrapper.java
private URLConnection getPrivilegedURLConnection(final URL url) throws IOException { try {/*from w w w. jav a2 s . c om*/ return (URLConnection) AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() throws IOException { return (getURLConnection(url)); } }); } catch (PrivilegedActionException e) { throw (IOException) e.getException(); } }
From source file:org.apache.axis2.deployment.DescriptionBuilder.java
protected Class findAndValidateSelectorClass(final String className, final String errorMsg) throws PrivilegedActionException { return (Class) org.apache.axis2.java.security.AccessController .doPrivileged(new PrivilegedExceptionAction() { public Object run() throws org.apache.axis2.deployment.DeploymentException { Class selectorClass; try { if ((className != null) && !"".equals(className)) { selectorClass = Loader.loadClass(Thread.currentThread().getContextClassLoader(), className); } else { throw new DeploymentException( Messages.getMessage(errorMsg, "Invalid Class Name", className)); }/*www . j av a 2 s . c om*/ } catch (ClassNotFoundException e) { throw new DeploymentException( Messages.getMessage(errorMsg, "ClassNotFoundException", className), e); } return selectorClass; } }); }
From source file:org.apache.hadoop.crypto.key.kms.server.KMS.java
@GET @Path(KMSRESTConstants.KEYS_NAMES_RESOURCE) @Produces(MediaType.APPLICATION_JSON)//from ww w .j a va 2s . co m public Response getKeyNames() throws Exception { try { LOG.trace("Entering getKeyNames method."); KMSWebApp.getAdminCallsMeter().mark(); UserGroupInformation user = HttpUserGroupInformation.get(); assertAccess(KMSACLs.Type.GET_KEYS, user, KMSOp.GET_KEYS); List<String> json = user.doAs(new PrivilegedExceptionAction<List<String>>() { @Override public List<String> run() throws Exception { return provider.getKeys(); } }); kmsAudit.ok(user, KMSOp.GET_KEYS, ""); LOG.trace("Exiting getKeyNames method."); return Response.ok().type(MediaType.APPLICATION_JSON).entity(json).build(); } catch (Exception e) { LOG.debug("Exception in getkeyNames.", e); throw e; } }
From source file:org.apache.drill.exec.server.rest.spnego.TestDrillSpnegoAuthenticator.java
/** * Test to verify authentication fails when client sends invalid SPNEGO token for the * {@link WebServerConstants#SPENGO_LOGIN_RESOURCE_PATH} resource. * @throws Exception/* ww w.ja v a 2s .c o m*/ */ @Test public void testSpnegoLoginInvalidToken() throws Exception { final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); final HttpServletResponse response = Mockito.mock(HttpServletResponse.class); final HttpSession session = Mockito.mock(HttpSession.class); // Create client subject using it's principal and keytab final Subject clientSubject = JaasKrbUtil.loginUsingKeytab(spnegoHelper.CLIENT_PRINCIPAL, spnegoHelper.clientKeytab.getAbsoluteFile()); // Generate a SPNEGO token for the peer SERVER_PRINCIPAL from this CLIENT_PRINCIPAL final String token = Subject.doAs(clientSubject, new PrivilegedExceptionAction<String>() { @Override public String run() throws Exception { final GSSManager gssManager = GSSManager.getInstance(); GSSContext gssContext = null; try { final Oid oid = GSSUtil.GSS_SPNEGO_MECH_OID; final GSSName serviceName = gssManager.createName(spnegoHelper.SERVER_PRINCIPAL, GSSName.NT_USER_NAME, oid); gssContext = gssManager.createContext(serviceName, oid, null, GSSContext.DEFAULT_LIFETIME); gssContext.requestCredDeleg(true); gssContext.requestMutualAuth(true); byte[] outToken = new byte[0]; outToken = gssContext.initSecContext(outToken, 0, outToken.length); return Base64.encodeBase64String(outToken); } finally { if (gssContext != null) { gssContext.dispose(); } } } }); Mockito.when(request.getSession(true)).thenReturn(session); final String httpReqAuthHeader = String.format("%s:%s", HttpHeader.NEGOTIATE.asString(), String.format("%s%s", "1234", token)); Mockito.when(request.getHeader(HttpHeader.AUTHORIZATION.asString())).thenReturn(httpReqAuthHeader); Mockito.when(request.getRequestURI()).thenReturn(WebServerConstants.SPENGO_LOGIN_RESOURCE_PATH); assertEquals(spnegoAuthenticator.validateRequest(request, response, false), Authentication.UNAUTHENTICATED); verify(session, never()).setAttribute(SessionAuthentication.__J_AUTHENTICATED, null); verify(response, never()).sendError(401); verify(response, never()).setHeader(HttpHeader.WWW_AUTHENTICATE.asString(), HttpHeader.NEGOTIATE.asString()); }
From source file:com.buaa.cfs.fs.FileContext.java
private static AbstractFileSystem getAbstractFileSystem(UserGroupInformation user, final URI uri, final Configuration conf) throws UnsupportedFileSystemException, IOException { try {/*from ww w . j a va 2 s. c o m*/ return user.doAs(new PrivilegedExceptionAction<AbstractFileSystem>() { @Override public AbstractFileSystem run() throws UnsupportedFileSystemException { return AbstractFileSystem.get(uri, conf); } }); } catch (InterruptedException ex) { LOG.error(ex); throw new IOException("Failed to get the AbstractFileSystem for path: " + uri, ex); } }
From source file:com.lucidworks.security.authentication.server.KerberosAuthenticationHandler.java
/** * It enforces the the Kerberos SPNEGO authentication sequence returning an {@link AuthenticationToken} only * after the Kerberos SPNEGO sequence has completed successfully. * <p/>/* w w w . j ava 2 s.co m*/ * * @param request the HTTP client request. * @param response the HTTP client response. * * @return an authentication token if the Kerberos SPNEGO sequence is complete and valid, * <code>null</code> if it is in progress (in this case the handler handles the response to the client). * * @throws IOException thrown if an IO error occurred. * @throws AuthenticationException thrown if Kerberos SPNEGO sequence failed. */ @Override public AuthenticationToken authenticate(HttpServletRequest request, final HttpServletResponse response) throws IOException, AuthenticationException { AuthenticationToken token = null; String authorization = request.getHeader(KerberosAuthenticator.AUTHORIZATION); if (authorization == null || !authorization.startsWith(KerberosAuthenticator.NEGOTIATE)) { response.setHeader(KerberosAuthenticator.WWW_AUTHENTICATE, KerberosAuthenticator.NEGOTIATE); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); if (authorization == null) { LOG.trace("SPNEGO starting"); } else { LOG.warn("'" + KerberosAuthenticator.AUTHORIZATION + "' does not start with '" + KerberosAuthenticator.NEGOTIATE + "' : {}", authorization); } } else { authorization = authorization.substring(KerberosAuthenticator.NEGOTIATE.length()).trim(); final Base64 base64 = new Base64(0); final byte[] clientToken = base64.decode(authorization); Subject serverSubject = loginContext.getSubject(); try { token = Subject.doAs(serverSubject, new PrivilegedExceptionAction<AuthenticationToken>() { @Override public AuthenticationToken run() throws Exception { AuthenticationToken token = null; GSSContext gssContext = null; GSSCredential gssCreds = null; try { if (PlatformName.IBM_JAVA) { // IBM JDK needs non-null credentials to be passed to createContext here, with // SPNEGO mechanism specified, otherwise JGSS will use its default mechanism // only, which is Kerberos V5. gssCreds = gssManager.createCredential(null, GSSCredential.INDEFINITE_LIFETIME, new Oid[] { KerberosUtil.getOidInstance("GSS_SPNEGO_MECH_OID"), KerberosUtil.getOidInstance("GSS_KRB5_MECH_OID") }, GSSCredential.ACCEPT_ONLY); } gssContext = gssManager.createContext(gssCreds); byte[] serverToken = gssContext.acceptSecContext(clientToken, 0, clientToken.length); if (serverToken != null && serverToken.length > 0) { String authenticate = base64.encodeToString(serverToken); response.setHeader(KerberosAuthenticator.WWW_AUTHENTICATE, KerberosAuthenticator.NEGOTIATE + " " + authenticate); } if (!gssContext.isEstablished()) { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); LOG.trace("SPNEGO in progress"); } else { String clientPrincipal = gssContext.getSrcName().toString(); KerberosName kerberosName = new KerberosName(clientPrincipal); String userName = kerberosName.getShortName(); token = new AuthenticationToken(userName, clientPrincipal, getType()); response.setStatus(HttpServletResponse.SC_OK); LOG.trace("SPNEGO completed for principal [{}]", clientPrincipal); } } finally { if (gssContext != null) { gssContext.dispose(); } if (gssCreds != null) { gssCreds.dispose(); } } return token; } }); } catch (PrivilegedActionException ex) { if (ex.getException() instanceof IOException) { throw (IOException) ex.getException(); } else { throw new AuthenticationException(ex.getException()); } } } return token; }
From source file:org.apache.hadoop.hbase.security.visibility.TestVisibilityLabelsWithDeletes.java
@Test public void testVisibilityLabelsWithDeleteFamilyVersion() throws Exception { setAuths();/* w w w .j a v a 2s . c o m*/ final TableName tableName = TableName.valueOf(TEST_NAME.getMethodName()); long[] ts = new long[] { 123l, 125l }; try (Table table = createTableAndWriteDataWithLabels(ts, CONFIDENTIAL + "|" + 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 + "|" + CONFIDENTIAL)); d.addFamilyVersion(fam, 123l); 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:org.apache.hadoop.hbase.master.procedure.CreateTableProcedure.java
private void postCreate(final MasterProcedureEnv env) throws IOException, InterruptedException { final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); if (cpHost != null) { final HRegionInfo[] regions = (newRegions == null) ? null : newRegions.toArray(new HRegionInfo[newRegions.size()]); user.doAs(new PrivilegedExceptionAction<Void>() { @Override//from w w w . ja v a 2 s .c o m public Void run() throws Exception { cpHost.postCreateTableHandler(hTableDescriptor, regions); return null; } }); } }