List of usage examples for javax.security.auth Subject doAs
public static <T> T doAs(final Subject subject, final java.security.PrivilegedExceptionAction<T> action) throws java.security.PrivilegedActionException
From source file:org.apache.hadoop.security.authentication.server.KerberosAuthenticationHandler.java
/** * Initializes the authentication handler instance. * <p/>// w w w. j a v a 2s . c om * 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); LOG.info("Login using keytab " + keytab + ", for principal " + 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.wildfly.test.integration.elytron.http.SpnegoMechTestCase.java
@Test public void testSuccess() throws Exception { final Krb5LoginConfiguration krb5Configuration = new Krb5LoginConfiguration(Utils.getLoginConfiguration()); Configuration.setConfiguration(krb5Configuration); LoginContext lc = Utils.loginWithKerberos(krb5Configuration, "user1@WILDFLY.ORG", "password1"); Subject.doAs(lc.getSubject(), (PrivilegedExceptionAction<Void>) () -> { try (CloseableHttpClient httpClient = HttpClients.createDefault()) { GSSManager manager = GSSManager.getInstance(); GSSName acceptorName = manager.createName("HTTP@localhost", GSSName.NT_HOSTBASED_SERVICE); GSSCredential credential = manager.createCredential(null, GSSCredential.DEFAULT_LIFETIME, new Oid[] { KERBEROS_V5, SPNEGO }, GSSCredential.INITIATE_ONLY); GSSContext context = manager.createContext(acceptorName, KERBEROS_V5, credential, GSSContext.INDEFINITE_LIFETIME); URI uri = new URI(url.toExternalForm() + "role1"); byte[] message = new byte[0]; for (int i = 0; i < 5; i++) { // prevent infinite loop - max 5 continuations message = context.initSecContext(message, 0, message.length); HttpGet request = new HttpGet(uri); request.setHeader(HEADER_AUTHORIZATION, CHALLENGE_PREFIX + Base64.getEncoder().encodeToString(message)); try (CloseableHttpResponse response = httpClient.execute(request)) { int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != SC_UNAUTHORIZED) { assertEquals("Unexpected status code in HTTP response.", SC_OK, statusCode); assertEquals("Unexpected content of HTTP response.", SimpleServlet.RESPONSE_BODY, EntityUtils.toString(response.getEntity())); // test cached identity HttpGet request2 = new HttpGet(uri); try (CloseableHttpResponse response2 = httpClient.execute(request2)) { int statusCode2 = response.getStatusLine().getStatusCode(); assertEquals("Unexpected status code in HTTP response.", SC_OK, statusCode2); assertEquals("Unexpected content of HTTP response.", SimpleServlet.RESPONSE_BODY, EntityUtils.toString(response2.getEntity())); }/*from w w w .ja v a 2 s .c om*/ return null; } String responseHeader = response.getFirstHeader(HEADER_WWW_AUTHENTICATE).getValue(); if (!responseHeader.startsWith(CHALLENGE_PREFIX)) Assert.fail("Invalid authenticate header"); message = Base64.getDecoder().decode(responseHeader.substring(CHALLENGE_PREFIX.length())); } } Assert.fail("Infinite unauthorized loop"); } return null; }); }
From source file:org.apache.ranger.biz.KmsKeyMgr.java
@SuppressWarnings("unchecked") public VXKmsKeyList searchKeys(HttpServletRequest request, String repoName) throws Exception { String providers[] = null;/* w w w . j a v a 2s. c om*/ try { providers = getKMSURL(repoName); } catch (Exception e) { logger.error("getKey(" + repoName + ") failed", e); } List<VXKmsKey> vXKeys = new ArrayList<VXKmsKey>(); VXKmsKeyList vxKmsKeyList = new VXKmsKeyList(); List<String> keys = null; String connProvider = null; boolean isKerberos = false; try { isKerberos = checkKerberos(); } catch (Exception e1) { logger.error("checkKerberos(" + repoName + ") failed", e1); } if (providers != null) { for (int i = 0; i < providers.length; i++) { Client c = getClient(); String currentUserLoginId = ContextUtil.getCurrentUserLoginId(); String keyLists = KMS_KEY_LIST_URI.replaceAll(Pattern.quote("${userName}"), currentUserLoginId); connProvider = providers[i]; String uri = providers[i] + (providers[i].endsWith("/") ? keyLists : ("/" + keyLists)); if (!isKerberos) { uri = uri.concat("?user.name=" + currentUserLoginId); } else { uri = uri.concat("?doAs=" + currentUserLoginId); } final WebResource r = c.resource(uri); try { String response = null; if (!isKerberos) { response = r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE) .get(String.class); } else { Subject sub = getSubjectForKerberos(repoName); response = Subject.doAs(sub, new PrivilegedAction<String>() { @Override public String run() { return r.accept(MediaType.APPLICATION_JSON_TYPE) .type(MediaType.APPLICATION_JSON_TYPE).get(String.class); } }); } Gson gson = new GsonBuilder().create(); logger.debug(" Search Key RESPONSE: [" + response + "]"); keys = gson.fromJson(response, List.class); Collections.sort(keys); VXKmsKeyList vxKmsKeyList2 = new VXKmsKeyList(); List<VXKmsKey> vXKeys2 = new ArrayList<VXKmsKey>(); for (String name : keys) { VXKmsKey key = new VXKmsKey(); key.setName(name); vXKeys2.add(key); } vxKmsKeyList2.setVXKeys(vXKeys2); vxKmsKeyList = getFilteredKeyList(request, vxKmsKeyList2); break; } catch (Exception e) { if (e instanceof UniformInterfaceException || i == providers.length - 1) throw e; else continue; } } } //details if (vxKmsKeyList != null && vxKmsKeyList.getVXKeys() != null && vxKmsKeyList.getVXKeys().size() > 0) { List<VXKmsKey> lstKMSKey = vxKmsKeyList.getVXKeys(); int startIndex = restErrorUtil.parseInt(request.getParameter("startIndex"), 0, "Invalid value for parameter startIndex", MessageEnums.INVALID_INPUT_DATA, null, "startIndex"); startIndex = startIndex < 0 ? 0 : startIndex; int pageSize = restErrorUtil.parseInt(request.getParameter("pageSize"), 0, "Invalid value for parameter pageSize", MessageEnums.INVALID_INPUT_DATA, null, "pageSize"); pageSize = pageSize < 0 ? 0 : pageSize; vxKmsKeyList.setResultSize(lstKMSKey.size()); vxKmsKeyList.setTotalCount(lstKMSKey.size()); if ((startIndex + pageSize) <= lstKMSKey.size()) { lstKMSKey = lstKMSKey.subList(startIndex, (startIndex + pageSize)); } else { startIndex = startIndex >= lstKMSKey.size() ? 0 : startIndex; lstKMSKey = lstKMSKey.subList(startIndex, lstKMSKey.size()); } if (CollectionUtils.isNotEmpty(lstKMSKey)) { for (VXKmsKey kmsKey : lstKMSKey) { if (kmsKey != null) { VXKmsKey key = getKeyFromUri(connProvider, kmsKey.getName(), isKerberos, repoName); vXKeys.add(key); } } } vxKmsKeyList.setStartIndex(startIndex); vxKmsKeyList.setPageSize(pageSize); } if (vxKmsKeyList != null) { vxKmsKeyList.setVXKeys(vXKeys); } return vxKmsKeyList; }
From source file:org.apache.sentry.service.thrift.SentryService.java
@Override public String call() throws Exception { SentryKerberosContext kerberosContext = null; try {/*w w w . j a v a 2 s. c o m*/ status = Status.STARTED; if (kerberos) { kerberosContext = new SentryKerberosContext(principal, keytab, true); Subject.doAs(kerberosContext.getSubject(), new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { runServer(); return null; } }); } else { runServer(); } } catch (Exception t) { LOGGER.error("Error starting server", t); throw new Exception("Error starting server", t); } finally { if (kerberosContext != null) { kerberosContext.shutDown(); } status = Status.NOT_STARTED; } return null; }
From source file:org.apache.ranger.services.hive.client.HiveClient.java
public List<String> getTableList(String tableNameMatching, List<String> databaseList, List<String> tblNameList) throws HadoopException { final String tblNameMatching = tableNameMatching; final List<String> dbList = databaseList; final List<String> tblList = tblNameList; List<String> tableList = Subject.doAs(getLoginSubject(), new PrivilegedAction<List<String>>() { public List<String> run() { List<String> ret = null; try { ret = getTblList(tblNameMatching, dbList, tblList); } catch (HadoopException he) { LOG.error("<== HiveClient getTblList() :Unable to get the Table List", he); throw he; }/*w ww . ja va 2 s . c om*/ return ret; } }); return tableList; }
From source file:org.apache.sentry.api.service.thrift.TestSentryWebServerWithKerberos.java
@Test public void testPingWithCaseSensitiveUser() throws Exception { // USER1 is present in the list of users who are allowed to connect to sentry web ui. String userPrinciple = "user1/" + SentryServiceIntegrationBase.SERVER_HOST; String userKerberosName = userPrinciple + "@" + SentryServiceIntegrationBase.REALM; Subject userSubject = new Subject(false, Sets.newHashSet(new KerberosPrincipal(userKerberosName)), new HashSet<Object>(), new HashSet<Object>()); File userKeytab = new File(SentryServiceIntegrationBase.kdcWorkDir, "user1.keytab"); SentryServiceIntegrationBase.kdc.createPrincipal(userKeytab, userPrinciple); LoginContext userLoginContext = new LoginContext("", userSubject, null, KerberosConfiguration.createClientConfig(userKerberosName, userKeytab)); userLoginContext.login();//from w w w. j a v a 2 s . c om Subject.doAs(userLoginContext.getSubject(), new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { final URL url = new URL("http://" + SentryServiceIntegrationBase.SERVER_HOST + ":" + SentryServiceIntegrationBase.webServerPort + "/ping"); try { new AuthenticatedURL(new KerberosAuthenticator()).openConnection(url, new AuthenticatedURL.Token()); fail("Login with user1 should fail"); } catch (AuthenticationException e) { String expectedError = "status code: 403"; if (!exceptionContainsMessage(e, expectedError)) { LOG.error("UnexpectedError: " + e.getMessage(), e); fail("UnexpectedError: " + e.getMessage()); } } return null; } }); }
From source file:org.apache.hadoop.security.authentication.client.KerberosAuthenticator.java
/** * Implements the SPNEGO authentication sequence interaction using the current default principal * in the Kerberos cache (normally set via kinit). * * @param token the authentication token being used for the user. * * @throws IOException if an IO error occurred. * @throws AuthenticationException if an authentication error occurred. */// ww w. ja v a 2s. com 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(); } Subject.doAs(subject, new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { GSSContext gssContext = null; try { GSSManager gssManager = GSSManager.getInstance(); String servicePrincipal = "HTTP/" + KerberosAuthenticator.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.storm.daemon.worker.Worker.java
public void start() throws Exception { LOG.info("Launching worker for {} on {}:{} with id {} and conf {}", topologyId, assignmentId, port, workerId, conf);// w w w . j ava 2s. co m // because in local mode, its not a separate // process. supervisor will register it in this case // if ConfigUtils.isLocalMode(conf) returns false then it is in distributed mode. if (!ConfigUtils.isLocalMode(conf)) { // Distributed mode SysOutOverSLF4J.sendSystemOutAndErrToSLF4J(); String pid = Utils.processPid(); FileUtils.touch(new File(ConfigUtils.workerPidPath(conf, workerId, pid))); FileUtils.writeStringToFile(new File(ConfigUtils.workerArtifactsPidPath(conf, topologyId, port)), pid, Charset.forName("UTF-8")); } final Map<String, Object> topologyConf = ConfigUtils .overrideLoginConfigWithSystemProperty(ConfigUtils.readSupervisorStormConf(conf, topologyId)); List<ACL> acls = Utils.getWorkerACL(topologyConf); IStateStorage stateStorage = ClusterUtils.mkStateStorage(conf, topologyConf, acls, new ClusterStateContext(DaemonType.WORKER)); IStormClusterState stormClusterState = ClusterUtils.mkStormClusterState(stateStorage, acls, new ClusterStateContext()); Credentials initialCredentials = stormClusterState.credentials(topologyId, null); Map<String, String> initCreds = new HashMap<>(); if (initialCredentials != null) { initCreds.putAll(initialCredentials.get_creds()); } autoCreds = AuthUtils.GetAutoCredentials(topologyConf); subject = AuthUtils.populateSubject(null, autoCreds, initCreds); backpressureZnodeTimeoutMs = ObjectReader.getInt(topologyConf.get(Config.BACKPRESSURE_ZNODE_TIMEOUT_SECS)) * 1000; Subject.doAs(subject, new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { workerState = new WorkerState(conf, context, topologyId, assignmentId, port, workerId, topologyConf, stateStorage, stormClusterState); // Heartbeat here so that worker process dies if this fails // it's important that worker heartbeat to supervisor ASAP so that supervisor knows // that worker is running and moves on doHeartBeat(); executorsAtom = new AtomicReference<>(null); // launch heartbeat threads immediately so that slow-loading tasks don't cause the worker to timeout // to the supervisor workerState.heartbeatTimer.scheduleRecurring(0, (Integer) conf.get(Config.WORKER_HEARTBEAT_FREQUENCY_SECS), () -> { try { doHeartBeat(); } catch (IOException e) { throw new RuntimeException(e); } }); workerState.executorHeartbeatTimer.scheduleRecurring(0, (Integer) conf.get(Config.WORKER_HEARTBEAT_FREQUENCY_SECS), Worker.this::doExecutorHeartbeats); workerState.registerCallbacks(); workerState.refreshConnections(null); workerState.activateWorkerWhenAllConnectionsReady(); workerState.refreshStormActive(null); workerState.runWorkerStartHooks(); List<IRunningExecutor> newExecutors = new ArrayList<IRunningExecutor>(); for (List<Long> e : workerState.getExecutors()) { if (ConfigUtils.isLocalMode(topologyConf)) { newExecutors.add(LocalExecutor.mkExecutor(workerState, e, initCreds).execute()); } else { newExecutors.add(Executor.mkExecutor(workerState, e, initCreds).execute()); } } executorsAtom.set(newExecutors); EventHandler<Object> tupleHandler = (packets, seqId, batchEnd) -> workerState .sendTuplesToRemoteWorker((HashMap<Integer, ArrayList<TaskMessage>>) packets, seqId, batchEnd); // This thread will publish the messages destined for remote tasks to remote connections transferThread = Utils.asyncLoop(() -> { workerState.transferQueue.consumeBatchWhenAvailable(tupleHandler); return 0L; }); DisruptorBackpressureCallback disruptorBackpressureHandler = mkDisruptorBackpressureHandler( workerState); workerState.transferQueue.registerBackpressureCallback(disruptorBackpressureHandler); workerState.transferQueue .setEnableBackpressure((Boolean) topologyConf.get(Config.TOPOLOGY_BACKPRESSURE_ENABLE)); workerState.transferQueue.setHighWaterMark( ObjectReader.getDouble(topologyConf.get(Config.BACKPRESSURE_DISRUPTOR_HIGH_WATERMARK))); workerState.transferQueue.setLowWaterMark( ObjectReader.getDouble(topologyConf.get(Config.BACKPRESSURE_DISRUPTOR_LOW_WATERMARK))); WorkerBackpressureCallback backpressureCallback = mkBackpressureHandler(topologyConf); backpressureThread = new WorkerBackpressureThread(workerState.backpressureTrigger, workerState, backpressureCallback); if ((Boolean) topologyConf.get(Config.TOPOLOGY_BACKPRESSURE_ENABLE)) { backpressureThread.start(); stormClusterState.topologyBackpressure(topologyId, backpressureZnodeTimeoutMs, workerState::refreshThrottle); int pollingSecs = ObjectReader.getInt(topologyConf.get(Config.TASK_BACKPRESSURE_POLL_SECS)); workerState.refreshBackpressureTimer.scheduleRecurring(0, pollingSecs, workerState::refreshThrottle); } credentialsAtom = new AtomicReference<Credentials>(initialCredentials); establishLogSettingCallback(); workerState.stormClusterState.credentials(topologyId, Worker.this::checkCredentialsChanged); workerState.refreshCredentialsTimer.scheduleRecurring(0, (Integer) conf.get(Config.TASK_CREDENTIALS_POLL_SECS), new Runnable() { @Override public void run() { checkCredentialsChanged(); if ((Boolean) topologyConf.get(Config.TOPOLOGY_BACKPRESSURE_ENABLE)) { checkThrottleChanged(); } } }); workerState.checkForUpdatedBlobsTimer.scheduleRecurring(0, (Integer) conf.getOrDefault(Config.WORKER_BLOB_UPDATE_POLL_INTERVAL_SECS, 10), new Runnable() { @Override public void run() { try { LOG.debug("Checking if blobs have updated"); updateBlobUpdates(); } catch (IOException e) { // IOException from reading the version files to be ignored LOG.error(e.getStackTrace().toString()); } } }); // The jitter allows the clients to get the data at different times, and avoids thundering herd if (!(Boolean) topologyConf.get(Config.TOPOLOGY_DISABLE_LOADAWARE_MESSAGING)) { workerState.refreshLoadTimer.scheduleRecurringWithJitter(0, 1, 500, Worker.this::doRefreshLoad); } workerState.refreshConnectionsTimer.scheduleRecurring(0, (Integer) conf.get(Config.TASK_REFRESH_POLL_SECS), workerState::refreshConnections); workerState.resetLogLevelsTimer.scheduleRecurring(0, (Integer) conf.get(Config.WORKER_LOG_LEVEL_RESET_POLL_SECS), logConfigManager::resetLogLevels); workerState.refreshActiveTimer.scheduleRecurring(0, (Integer) conf.get(Config.TASK_REFRESH_POLL_SECS), workerState::refreshStormActive); LOG.info("Worker has topology config {}", Utils.redactValue(topologyConf, Config.STORM_ZOOKEEPER_TOPOLOGY_AUTH_PAYLOAD)); LOG.info("Worker {} for storm {} on {}:{} has finished loading", workerId, topologyId, assignmentId, port); return this; }; }); }
From source file:org.apache.ws.security.validate.KerberosTokenValidator.java
/** * Validate the credential argument. It must contain a non-null BinarySecurityToken. * /*w ww. ja va 2 s . c o m*/ * @param credential the Credential to be validated * @param data the RequestData associated with the request * @throws WSSecurityException on a failed validation */ public Credential validate(Credential credential, RequestData data) throws WSSecurityException { if (credential == null || credential.getBinarySecurityToken() == null) { throw new WSSecurityException(WSSecurityException.FAILURE, "noCredential"); } BinarySecurity binarySecurity = credential.getBinarySecurityToken(); if (!(binarySecurity instanceof KerberosSecurity)) { return credential; } if (log.isDebugEnabled()) { try { String jaasAuth = System.getProperty("java.security.auth.login.config"); String krbConf = System.getProperty("java.security.krb5.conf"); log.debug("KerberosTokenValidator - Using JAAS auth login file: " + jaasAuth); log.debug("KerberosTokenValidator - Using KRB conf file: " + krbConf); } catch (SecurityException ex) { log.debug(ex.getMessage(), ex); } } // Get a TGT from the KDC using JAAS LoginContext loginContext = null; try { if (callbackHandler == null) { loginContext = new LoginContext(getContextName()); } else { loginContext = new LoginContext(getContextName(), callbackHandler); } loginContext.login(); } catch (LoginException ex) { if (log.isDebugEnabled()) { log.debug(ex.getMessage(), ex); } throw new WSSecurityException(WSSecurityException.FAILURE, "kerberosLoginError", new Object[] { ex.getMessage() }, ex); } if (log.isDebugEnabled()) { log.debug("Successfully authenticated to the TGT"); } byte[] token = binarySecurity.getToken(); // Get the service name to use - fall back on the principal Subject subject = loginContext.getSubject(); String service = serviceName; if (service == null) { Set<Principal> principals = subject.getPrincipals(); if (principals.isEmpty()) { throw new WSSecurityException(WSSecurityException.FAILURE, "kerberosLoginError", new Object[] { "No Client principals found after login" }); } service = principals.iterator().next().getName(); } // Validate the ticket KerberosServiceAction action = new KerberosServiceAction(token, service); Principal principal = (Principal) Subject.doAs(subject, action); if (principal == null) { throw new WSSecurityException(WSSecurityException.FAILURE, "kerberosTicketValidationError"); } credential.setPrincipal(principal); credential.setSubject(subject); // Try to extract the session key from the token if a KerberosTokenDecoder implementation is // available if (kerberosTokenDecoder != null) { kerberosTokenDecoder.clear(); kerberosTokenDecoder.setToken(token); kerberosTokenDecoder.setSubject(subject); byte[] sessionKey = kerberosTokenDecoder.getSessionKey(); credential.setSecretKey(sessionKey); } if (log.isDebugEnabled()) { log.debug("Successfully validated a ticket"); } return credential; }
From source file:org.apache.ranger.services.hdfs.client.HdfsClient.java
public List<String> listFiles(final String baseDir, final String fileMatching, final List<String> pathList) throws Exception { PrivilegedExceptionAction<List<String>> action = new PrivilegedExceptionAction<List<String>>() { @Override/*from w w w.jav a2 s . c o m*/ public List<String> run() throws Exception { return listFilesInternal(baseDir, fileMatching, pathList); } }; return Subject.doAs(getLoginSubject(), action); }