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.UserGroupInformation.java
/** * Run the given action as the user, potentially throwing an exception. * @param <T> the return type of the run method * @param action the method to execute//from w ww. j a v a 2 s . c o m * @return the value from the run method * @throws IOException if the action throws an IOException * @throws Error if the action throws an Error * @throws RuntimeException if the action throws a RuntimeException * @throws InterruptedException if the action throws an InterruptedException * @throws UndeclaredThrowableException if the action throws something else */ public <T> T doAs(PrivilegedExceptionAction<T> action) throws IOException, InterruptedException { try { logPriviledgedAction(subject, action); return Subject.doAs(subject, action); } catch (PrivilegedActionException pae) { Throwable cause = pae.getCause(); LOG.error("PriviledgedActionException as:" + this + " cause:" + cause); if (cause instanceof IOException) { throw (IOException) cause; } else if (cause instanceof Error) { throw (Error) cause; } else if (cause instanceof RuntimeException) { throw (RuntimeException) cause; } else if (cause instanceof InterruptedException) { throw (InterruptedException) cause; } else { throw new UndeclaredThrowableException(pae, "Unknown exception in doAs"); } } }
From source file:org.apache.directory.studio.connection.core.io.jndi.JNDIConnectionWrapper.java
private void doGssapiBind(final InnerRunnable innerRunnable) throws NamingException { File configFile = null;//from ww w . j av a 2 s. c om try { Preferences preferences = ConnectionCorePlugin.getDefault().getPluginPreferences(); boolean useKrb5SystemProperties = preferences .getBoolean(ConnectionCoreConstants.PREFERENCE_USE_KRB5_SYSTEM_PROPERTIES); String krb5LoginModule = preferences.getString(ConnectionCoreConstants.PREFERENCE_KRB5_LOGIN_MODULE); if (!useKrb5SystemProperties) { // Kerberos Configuration switch (connection.getConnectionParameter().getKrb5Configuration()) { case DEFAULT: // nothing System.clearProperty("java.security.krb5.conf"); //$NON-NLS-1$ break; case FILE: // use specified krb5.conf System.setProperty("java.security.krb5.conf", connection.getConnectionParameter() //$NON-NLS-1$ .getKrb5ConfigurationFile()); break; case MANUAL: // write manual config parameters to connection specific krb5.conf file String fileName = Utils.getFilenameString(connection.getId()) + ".krb5.conf"; //$NON-NLS-1$ configFile = ConnectionCorePlugin.getDefault().getStateLocation().append(fileName).toFile(); String realm = connection.getConnectionParameter().getKrb5Realm(); String host = connection.getConnectionParameter().getKrb5KdcHost(); int port = connection.getConnectionParameter().getKrb5KdcPort(); StringBuilder sb = new StringBuilder(); sb.append("[libdefaults]").append(ConnectionCoreConstants.LINE_SEPARATOR); //$NON-NLS-1$ sb.append("default_realm = ").append(realm).append(ConnectionCoreConstants.LINE_SEPARATOR); //$NON-NLS-1$ sb.append("[realms]").append(ConnectionCoreConstants.LINE_SEPARATOR); //$NON-NLS-1$ sb.append(realm).append(" = {").append(ConnectionCoreConstants.LINE_SEPARATOR); //$NON-NLS-1$ sb.append("kdc = ").append(host).append(":").append(port).append( //$NON-NLS-1$ //$NON-NLS-2$ ConnectionCoreConstants.LINE_SEPARATOR); sb.append("}").append(ConnectionCoreConstants.LINE_SEPARATOR); //$NON-NLS-1$ try { FileUtils.writeStringToFile(configFile, sb.toString()); } catch (IOException ioe) { NamingException ne = new NamingException(); ne.setRootCause(ioe); throw ne; } System.setProperty("java.security.krb5.conf", configFile.getAbsolutePath()); //$NON-NLS-1$ } // Use our custom configuration so we don't need to mess with external configuration Configuration.setConfiguration(new InnerConfiguration(krb5LoginModule)); } // Gets the TGT, either from native ticket cache or obtain new from KDC LoginContext lc = null; try { lc = new LoginContext(this.getClass().getName(), new InnerCallbackHandler()); lc.login(); } catch (LoginException le) { NamingException ne = new NamingException(); ne.setRootCause(le); throw ne; } // Login to LDAP server, obtains a service ticket from KDC Subject.doAs(lc.getSubject(), (PrivilegedAction<Object>) () -> { try { context.reconnect(context.getConnectControls()); } catch (NamingException ne) { innerRunnable.namingException = ne; } return null; }); } finally { // delete temporary config file if (configFile != null && configFile.exists()) { configFile.delete(); } } }
From source file:org.jboss.as.test.integration.security.common.Utils.java
/** * Creates Kerberos TGS ticket for given user to access given server. * * @param user/*from w w w . j a v a 2s. co m*/ * @param pass * @param serverName * @return */ public static byte[] createKerberosTicketForServer(final String user, final String pass, final GSSName serverName) throws MalformedURLException, LoginException, PrivilegedActionException { Objects.requireNonNull(serverName); final Krb5LoginConfiguration krb5Configuration = new Krb5LoginConfiguration(getLoginConfiguration()); try { Configuration.setConfiguration(krb5Configuration); final LoginContext lc = loginWithKerberos(krb5Configuration, user, pass); try { return Subject.doAs(lc.getSubject(), new PrivilegedExceptionAction<byte[]>() { public byte[] run() throws Exception { final GSSManager manager = GSSManager.getInstance(); final Oid oid = new Oid(OID_KERBEROS_V5); final GSSContext gssContext = manager.createContext(serverName.canonicalize(oid), oid, null, 60); gssContext.requestMutualAuth(true); gssContext.requestCredDeleg(true); return gssContext.initSecContext(new byte[0], 0, 0); } }); } finally { lc.logout(); } } finally { krb5Configuration.resetConfiguration(); } }
From source file:org.alfresco.web.site.servlet.SSOAuthenticationFilter.java
/** * Perform a Kerberos login and return an SPNEGO response * /*from w ww.jav a2 s. c o m*/ * @param negToken NegTokenInit * @param req HttpServletRequest * @param resp HttpServletResponse * @param httpSess HttpSession * @return NegTokenTarg */ @SuppressWarnings("unchecked") private NegTokenTarg doKerberosLogon(NegTokenInit negToken, HttpServletRequest req, HttpServletResponse resp, HttpSession httpSess) { // Authenticate the user KerberosDetails krbDetails = null; NegTokenTarg negTokenTarg = null; try { // Run the session setup as a privileged action KerberosSessionSetupPrivilegedAction sessSetupAction = new KerberosSessionSetupPrivilegedAction( krbAccountName, negToken.getMechtoken(), krbEndpointSPN); Object result = Subject.doAs(jaasLoginContext.getSubject(), sessSetupAction); if (result != null) { // Access the Kerberos response Pair<KerberosDetails, String> resultPair = (Pair<KerberosDetails, String>) result; krbDetails = resultPair.getFirst(); String tokenForEndpoint = resultPair.getSecond(); // Create the NegTokenTarg response blob negTokenTarg = new NegTokenTarg(SPNEGO.AcceptCompleted, OID.KERBEROS5, krbDetails.getResponseToken()); // Check if the user has been authenticated, if so then setup the user environment if (negTokenTarg != null) { String userName = stripUserNameSuffix ? krbDetails.getUserName() : krbDetails.getSourceName(); // Debug if (logger.isDebugEnabled()) logger.debug("User " + userName + " logged on via Kerberos; attempting to log on to Alfresco then"); boolean authenticated = doKerberosDelegateLogin(req, resp, httpSess, userName, tokenForEndpoint); if (!authenticated) { return null; } else { // Firefox and Chrome hack (MNT-15561): // These browsers only send the authorization header (SPNEGO - Kerberos) once // (when redirecting to /share/page/user/<username>/dashboard only Internet Explorer will send the header again). // Therefore we need to have some way of knowing that the previous authentication was done using Kerberos, // otherwise we'll end-up having problems like MNT-15561 ('Logout' button is still present in spite of SSO being set). httpSess.setAttribute(AUTH_BY_KERBEROS, true); } } } else { // Debug if (logger.isDebugEnabled()) logger.debug("No SPNEGO response, Kerberos logon failed"); } } catch (Exception ex) { // Log the error if (logger.isDebugEnabled()) logger.debug("Kerberos logon error", ex); } // Return the response SPNEGO blob return negTokenTarg; }
From source file:org.alfresco.filesys.auth.cifs.EnterpriseCifsAuthenticator.java
/** * Perform a Kerberos login and return an SPNEGO response * /*from w ww .j a v a2s.com*/ * @param sess SMBSrvSession * @param negToken NegTokenInit * @param client ClientInfo * @return NegTokenTarg * @exception SMBSrvException */ private final NegTokenTarg doKerberosLogon(SMBSrvSession sess, NegTokenInit negToken, ClientInfo client) throws SMBSrvException { // Authenticate the user KerberosDetails krbDetails = null; NegTokenTarg negTokenTarg = null; try { // Parse the mechToken to get the AP-REQ details KerberosApReq krbApReq = new KerberosApReq(); krbApReq.parseMechToken(negToken.getMechtoken()); if (logger.isDebugEnabled()) logger.debug("Kerberos AP-REQ - " + krbApReq); // Check if mutual authentication is required KrbAuthContext krbAuthCtx = null; if (krbApReq.hasMutualAuthentication() && m_enableTicketCracking == true) { // Allocate the Kerberos authentication and parse the AP-REQ krbAuthCtx = new KrbAuthContext(); krbAuthCtx.setDebug(hasDebug()); // DEBUG if (logger.isDebugEnabled()) logger.debug("Kerberos mutual auth required, parsing AP-REQ"); try { // Parse the AP-REQ krbAuthCtx.parseKerberosApReq(m_loginContext.getSubject(), krbApReq); } catch (IOException ex) { // Failed to parse AP-REQ logger.error("Kerberos Failed to parse AP-REQ ", ex); // Return a logon failure status throw new SMBSrvException(SMBStatus.NTLogonFailure, SMBStatus.ErrDos, SMBStatus.DOSAccessDenied); } } // Run the session setup as a privileged action SessionSetupPrivilegedAction sessSetupAction = new SessionSetupPrivilegedAction(m_accountName, negToken.getMechtoken()); Object result = Subject.doAs(m_loginContext.getSubject(), sessSetupAction); if (result != null) { // Access the Kerberos response krbDetails = (KerberosDetails) result; // Determine the response OID Oid respOid = null; if (negToken.hasOid(OID.MSKERBEROS5)) { respOid = OID.MSKERBEROS5; // DEBUG if (logger.isDebugEnabled()) logger.debug("Using OID MS Kerberos5 for NegTokenTarg"); } else { respOid = OID.KERBEROS5; // DEBUG if (logger.isDebugEnabled()) logger.debug("Using OID Kerberos5 for NegTokenTarg"); } // If mutual authentication is required then we unpack the AP-REP and add in the missing // subkey that the AD client requires if (krbAuthCtx != null) { try { // Parse the AP-REP and add the missing subkey, return the updated response blob byte[] respToken = krbAuthCtx.parseKerberosApRep(krbDetails.getResponseToken()); krbDetails.setResponseToken(respToken); // Create the NegtokenTarg negTokenTarg = new NegTokenTarg(SPNEGO.AcceptCompleted, respOid, krbDetails.getResponseToken()); // DEBUG if (logger.isDebugEnabled()) logger.debug("Created NegTokenTarg using updated AP-REP, added subkey"); } catch (Exception ex) { if (logger.isDebugEnabled()) { logger.debug("AP-REP Error:"); logger.debug(ex); } } } else { // Create the NegTokenTarg response blob negTokenTarg = new NegTokenTarg(SPNEGO.AcceptCompleted, respOid, krbDetails.getResponseToken()); // DEBUG if (logger.isDebugEnabled()) logger.debug("Created NegTokenTarg using standard Krb5 API response"); } // Check if this is a null logon String userName = krbDetails.getUserName(); String userId = m_stripKerberosUsernameSuffix ? krbDetails.getUserName() : krbDetails.getSourceName(); if (userName != null) { // Check for the machine account name // ALF-4395: Sometimes machine account name comes lowercase // and new Alfresco user is being created with machine name // if ( userName.endsWith( "$") && userName.equals( userName.toUpperCase())) if (userName.endsWith("$")) { // Null logon client.setLogonType(ClientInfo.LogonNull); // Debug if (logger.isDebugEnabled()) logger.debug("Machine account logon, " + userId + ", as null logon"); } else { // Set the current user to be authenticated, save the authentication token try { AlfrescoClientInfo alfClient = (AlfrescoClientInfo) client; getAuthenticationComponent().setCurrentUser(mapUserNameToPerson(userId, true)); alfClient.setAuthenticationTicket(getAuthenticationService().getCurrentTicket()); } catch (AuthenticationException e) { // Invalid user or max tickets exceeded. Return a logon failure status logger.error("invalid user or tickets exceeded"); throw new SMBSrvException(SMBStatus.NTLogonFailure, SMBStatus.ErrDos, SMBStatus.DOSAccessDenied); } // Store the user name in the client information, indicate that this is not a guest logon client.setUserName(userId); client.setGuest(false); // Indicate that the session is logged on sess.setLoggedOn(true); } } else { // Null logon client.setLogonType(ClientInfo.LogonNull); } // Indicate that the session is logged on sess.setLoggedOn(true); // Debug if (logger.isDebugEnabled()) logger.debug("Logged on using Kerberos, user " + userName); } else { logger.error("No SPNEGO response, Kerberos logon failed"); // Return a logon failure status throw new SMBSrvException(SMBStatus.NTLogonFailure, SMBStatus.ErrDos, SMBStatus.DOSAccessDenied); } } catch (Exception ex) { if (ex instanceof SMBSrvException) { throw (SMBSrvException) ex; } // Return a logon failure status logger.error("Error during kerberos authentication", ex); throw new SMBSrvException(SMBStatus.NTLogonFailure, SMBStatus.ErrDos, SMBStatus.DOSAccessDenied); } // Return the response SPNEGO blob return negTokenTarg; }
From source file:com.buaa.cfs.security.UserGroupInformation.java
/** * Run the given action as the user.//ww w. j a v a 2 s .c o m * * @param <T> the return type of the run method * @param action the method to execute * * @return the value from the run method */ public <T> T doAs(PrivilegedAction<T> action) { logPrivilegedAction(subject, action); return Subject.doAs(subject, action); }
From source file:com.buaa.cfs.security.UserGroupInformation.java
/** * Run the given action as the user, potentially throwing an exception. * * @param <T> the return type of the run method * @param action the method to execute//from w w w. ja v a 2 s . c o m * * @return the value from the run method * * @throws IOException if the action throws an IOException * @throws Error if the action throws an Error * @throws RuntimeException if the action throws a RuntimeException * @throws InterruptedException if the action throws an InterruptedException * @throws UndeclaredThrowableException if the action throws something else */ public <T> T doAs(PrivilegedExceptionAction<T> action) throws IOException, InterruptedException { try { logPrivilegedAction(subject, action); return Subject.doAs(subject, action); } catch (PrivilegedActionException pae) { Throwable cause = pae.getCause(); if (LOG.isDebugEnabled()) { LOG.debug("PrivilegedActionException as:" + this + " cause:" + cause); } if (cause instanceof IOException) { throw (IOException) cause; } else if (cause instanceof Error) { throw (Error) cause; } else if (cause instanceof RuntimeException) { throw (RuntimeException) cause; } else if (cause instanceof InterruptedException) { throw (InterruptedException) cause; } else { throw new UndeclaredThrowableException(cause); } } }