@Before public void login() throws Exception { final LoginContext lc = Util.getCLMLoginContext("user1", "password1"); lc.login(); this.loginContext = lc; }
@Test public void testRoleExpansion() throws LoginException { LoginContext context = new LoginContext( "ExpandedLDAPLogin", new CallbackHandler() { public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { for (int i = 0; i < callbacks.length; i++) { if (callbacks[i] instanceof NameCallback) { ((NameCallback) callbacks[i]).setName("first"); } else if (callbacks[i] instanceof PasswordCallback) { ((PasswordCallback) callbacks[i]).setPassword("secret".toCharArray()); } else { throw new UnsupportedCallbackException(callbacks[i]); } } } }); context.login(); Subject subject = context.getSubject(); boolean isAdmin = false; boolean isUser = false; for (Principal principal : subject.getPrincipals()) { if (principal instanceof GroupPrincipal) { GroupPrincipal groupPrincipal = (GroupPrincipal) principal; if (groupPrincipal.getName().equalsIgnoreCase("admins")) isAdmin = true; if (groupPrincipal.getName().equalsIgnoreCase("users")) isUser = true; } } // Should be in users by virtue of being in admins assertTrue(isAdmin && isUser); context.logout(); }
/** * Log a user in from a keytab file. Loads a user identity from a keytab file and login them in. * This new user does not affect the currently logged-in user. * * @param user the principal name to load from the keytab * @param path the path to the keytab file * @throws IOException if the keytab file can't be read */ public static synchronized UserGroupInformation loginUserFromKeytabAndReturnUGI( String user, String path) throws IOException { if (!isSecurityEnabled()) return UserGroupInformation.getCurrentUser(); String oldKeytabFile = null; String oldKeytabPrincipal = null; long start = 0; try { oldKeytabFile = keytabFile; oldKeytabPrincipal = keytabPrincipal; keytabFile = path; keytabPrincipal = user; Subject subject = new Subject(); LoginContext login = new LoginContext(HadoopConfiguration.KEYTAB_KERBEROS_CONFIG_NAME, subject); start = System.currentTimeMillis(); login.login(); metrics.loginSuccess.inc(System.currentTimeMillis() - start); UserGroupInformation newLoginUser = new UserGroupInformation(subject); newLoginUser.setLogin(login); newLoginUser.setAuthenticationMethod(AuthenticationMethod.KERBEROS); return newLoginUser; } catch (LoginException le) { if (start > 0) { metrics.loginFailure.inc(System.currentTimeMillis() - start); } throw new IOException("Login failure for " + user + " from keytab " + path, le); } finally { if (oldKeytabFile != null) keytabFile = oldKeytabFile; if (oldKeytabPrincipal != null) keytabPrincipal = oldKeytabPrincipal; } }
@Override public void run(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { LoginContext lc = null; if (request.getUserPrincipal() == null) { try { lc = doLogin(request, response); request = wrapRequest(request, lc); } catch (LoginException e) { // login failed handleLoginFailure(request, response, e); return; } } try { chain.doFilter(request, response); } finally { ClientLoginModule.getThreadLocalLogin().clear(); if (lc != null) { // a null lc may indicate an anonymous login try { lc.logout(); } catch (Exception e) { } } } }
/** * Re-Login a user in from the ticket cache. This method assumes that login had happened already. * The Subject field of this UserGroupInformation object is updated to have the new credentials. * * @throws IOException on a failure */ public synchronized void reloginFromTicketCache() throws IOException { if (!isSecurityEnabled() || user.getAuthenticationMethod() != AuthenticationMethod.KERBEROS || !isKrbTkt) return; LoginContext login = getLogin(); if (login == null) { throw new IOException("login must be done first"); } if (!hasSufficientTimeElapsed()) { return; } try { LOG.info("Initiating logout for " + getUserName()); // clear up the kerberos state. But the tokens are not cleared! As per // the Java kerberos login module code, only the kerberos credentials // are cleared login.logout(); // login and also update the subject field of this instance to // have the new credentials (pass it to the LoginContext constructor) login = new LoginContext(HadoopConfiguration.USER_KERBEROS_CONFIG_NAME, getSubject()); LOG.info("Initiating re-login for " + getUserName()); login.login(); setLogin(login); } catch (LoginException le) { throw new IOException("Login failure for " + getUserName(), le); } }
/** * Log a user in from a keytab file. Loads a user identity from a keytab file and logs them in. * They become the currently logged-in user. * * @param user the principal name to load from the keytab * @param path the path to the keytab file * @throws IOException if the keytab file can't be read */ public static synchronized void loginUserFromKeytab(String user, String path) throws IOException { if (!isSecurityEnabled()) { return; } keytabFile = path; keytabPrincipal = user; Subject subject = new Subject(); LoginContext login; long start = 0; try { login = new LoginContext(HadoopConfiguration.KEYTAB_KERBEROS_CONFIG_NAME, subject); start = System.currentTimeMillis(); login.login(); metrics.loginSuccess.inc(System.currentTimeMillis() - start); loginUser = new UserGroupInformation(subject); loginUser.setLogin(login); loginUser.setAuthenticationMethod(AuthenticationMethod.KERBEROS); } catch (LoginException le) { if (start > 0) { metrics.loginFailure.inc(System.currentTimeMillis() - start); } throw new IOException("Login failure for " + user + " from keytab " + path, le); } LOG.info("Login successful for user " + keytabPrincipal + " using keytab file " + keytabFile); }
private synchronized void serviceLogin() throws AuthLoginException { debug.message("New Service Login ..."); System.setProperty("java.security.krb5.realm", kdcRealm); System.setProperty("java.security.krb5.kdc", kdcServer); System.setProperty("java.security.auth.login.config", "/dev/null"); try { Configuration config = Configuration.getConfiguration(); WindowsDesktopSSOConfig wtc = null; if (config instanceof WindowsDesktopSSOConfig) { wtc = (WindowsDesktopSSOConfig) config; wtc.setRefreshConfig("true"); } else { wtc = new WindowsDesktopSSOConfig(config); } wtc.setPrincipalName(servicePrincipalName); wtc.setKeyTab(keyTabFile); Configuration.setConfiguration(wtc); // perform service authentication using JDK Kerberos module LoginContext lc = new LoginContext(WindowsDesktopSSOConfig.defaultAppName); lc.login(); serviceSubject = lc.getSubject(); debug.message("Service login succeeded."); } catch (Exception e) { debug.error("Service Login Error: "); if (debug.messageEnabled()) { debug.message("Stack trace: ", e); } throw new AuthLoginException(amAuthWindowsDesktopSSO, "serviceAuth", null, e); } }
/** * Tries to login the user. If username as well as password are correctly spelled this method * returns the PatientSearch-Site, if not the Login-Failed Site will be returned. * * @return correct login: PatientSearch, else LoginFailed * @throws Exception */ public String login() throws Exception { // FacesContext fc = FacesContext.getCurrentInstance().getExternalContext().getResponse(); // HttpServletResponse resp = // (HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse(); // resp. // fc.getMessages(). // throw new Exception(); // TODO: facesContext - register new Error try { LoginContext lc = new LoginContext("Test"); lc.login(); } catch (LoginException e) { e.printStackTrace(); } finally { return "/errorPage.xhtml"; } // File f = null; // f.getName(); // if(findUser(username, password)){ // return "loginAccepted"; // } // else{ // return "loginDenied"; // } // if(findUser(username, password)){ // return "/patientSearch.xhtml"; // } // else{ // return "/loginFalse.xhtml"; // } }
public static void authenticate( PGStream pgStream, String host, String user, String password, String jaasApplicationName, String kerberosServerName, Logger logger) throws IOException, SQLException { if (logger.logDebug()) logger.debug(" <=BE AuthenticationReqGSS"); Object result = null; if (jaasApplicationName == null) jaasApplicationName = "pgjdbc"; if (kerberosServerName == null) kerberosServerName = "postgres"; try { LoginContext lc = new LoginContext(jaasApplicationName, new GSSCallbackHandler(user, password)); lc.login(); Subject sub = lc.getSubject(); PrivilegedAction action = new GssAction(pgStream, host, user, password, kerberosServerName, logger); result = Subject.doAs(sub, action); } catch (Exception e) { throw new PSQLException(GT.tr("GSS Authentication failed"), PSQLState.CONNECTION_FAILURE, e); } if (result instanceof IOException) throw (IOException) result; else if (result instanceof SQLException) throw (SQLException) result; else if (result != null) throw new PSQLException( GT.tr("GSS Authentication failed"), PSQLState.CONNECTION_FAILURE, (Exception) result); }
public Subject krb5PasswordLogin(String password) { String loginModuleName = "krb5UsernamePasswordLogin"; LOG.info( "Attempting kerberos authentication of user: "******" using username and password mechanism"); // Set the domain to realm and the kdc // System.setProperty("java.security.krb5.realm", "JTLAN.CO.UK"); // System.setProperty("java.security.krb5.kdc", "jtserver.jtlan.co.uk"); // System.setProperty("java.security.krb5.conf", // "/home/turnerj/git/servlet-security-filter/KerberosSecurityFilter/src/main/resources/krb5.conf"); // Form jaasOptions map Map<String, String> jaasOptions = new HashMap<String, String>(); jaasOptions.put("useKeyTab", "false"); jaasOptions.put("storeKey", "false"); jaasOptions.put("doNotPrompt", "false"); jaasOptions.put("refreshKrb5Config", "false"); jaasOptions.put("clearPass", "true"); jaasOptions.put("useTicketCache", "false"); LOG.debug("Dynamic jaas configuration used:" + jaasOptions.toString()); // Create dynamic jaas config DynamicJaasConfiguration contextConfig = new DynamicJaasConfiguration(); contextConfig.addAppConfigEntry( loginModuleName, "com.sun.security.auth.module.Krb5LoginModule", AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, jaasOptions); try { /* * Create login context using dynamic config * The "krb5UsernamePasswordLogin" needs to correspond to a configuration in the jaas config. */ LoginContext loginCtx = new LoginContext( loginModuleName, null, new LoginUsernamePasswordHandler(clientPrincipal, password), contextConfig); loginCtx.login(); Subject clientSubject = loginCtx.getSubject(); String loggedInUser = principalNameFromSubject(clientSubject); LOG.info( "SUCCESSFUL LOGIN for user: "******" using username and password mechanism."); return clientSubject; } catch (LoginException le) { le.printStackTrace(); // Failed logins are not an application error so the following line is at info level. LOG.info( "LOGIN FAILED for user: "******" using username and password mechanism. Reason: " + le.toString()); return null; } }
private String getEncodedKerberosTicket(boolean spnego) throws Exception { System.setProperty("java.security.auth.login.config", "src/test/resources/kerberos.jaas"); System.setProperty("org.apache.xml.security.ignoreLineBreaks", "true"); Oid kerberos5Oid = null; if (spnego) { kerberos5Oid = new Oid("1.3.6.1.5.5.2"); } else { kerberos5Oid = new Oid("1.2.840.113554.1.2.2"); } GSSManager manager = GSSManager.getInstance(); GSSName serverName = manager.createName("*****@*****.**", GSSName.NT_HOSTBASED_SERVICE); GSSContext context = manager.createContext( serverName.canonicalize(kerberos5Oid), kerberos5Oid, null, GSSContext.DEFAULT_LIFETIME); context.requestCredDeleg(true); final byte[] token = new byte[0]; String contextName = "alice"; LoginContext lc = new LoginContext(contextName); lc.login(); byte[] ticket = (byte[]) Subject.doAs(lc.getSubject(), new CreateServiceTicketAction(context, token)); return Base64.encode(ticket); }
private Subject getAuthenticatedSubject( final String user, final String password, final X509Certificate[] certificates) throws LoginException { LoginContext lc = new LoginContext(configurationName, new JaasCallbackHandler(user, password, certificates)); lc.login(); return lc.getSubject(); }
/* ------------------------------------------------------------ */ public void logout(UserIdentity user) { Set<JAASUserPrincipal> userPrincipals = user.getSubject().getPrincipals(JAASUserPrincipal.class); LoginContext loginContext = userPrincipals.iterator().next().getLoginContext(); try { loginContext.logout(); } catch (LoginException e) { LOG.warn(e); } }
@Test public void testLoginEmailAddressWithScreenName() throws Exception { _jaasAuthTypeField.set(null, "screenName"); LoginContext loginContext = getLoginContext(_user.getEmailAddress(), _user.getPassword()); try { loginContext.login(); Assert.fail(); } catch (Exception e) { } }
private boolean authenticate(SecurityContext securityContext) { Connection connection = endpoint.getConnection(); credentials.setEndpoint(connection.getInetAddress().getHostAddress()); try { LoginContext lc = securityContext.createClientLoginContext(credentials); lc.login(); endpoint.setLoginContext(lc); return true; } catch (LoginException e) { logger.warning(e); return false; } }
@Test public void testLoginScreenNameWithUserId() throws Exception { _jaasAuthTypeField.set(null, "userId"); LoginContext loginContext = getLoginContext(_user.getScreenName(), _user.getPassword()); try { loginContext.login(); Assert.fail(); } catch (Exception e) { } }
@Test public void testLoginScreenNameWithScreenName() throws Exception { _jaasAuthTypeField.set(null, "screenName"); LoginContext loginContext = getLoginContext(_user.getScreenName(), _user.getPassword()); try { loginContext.login(); } catch (Exception e) { Assert.fail(); } validateSubject(loginContext.getSubject(), _user.getScreenName()); }
@Test public void testLoginEmailAddressWithLogin() throws Exception { _jaasAuthTypeField.set(null, "login"); LoginContext loginContext = getLoginContext(_user.getEmailAddress(), _user.getPassword()); try { loginContext.login(); } catch (Exception e) { Assert.fail(); } validateSubject(loginContext.getSubject(), _user.getEmailAddress()); }
@Test public void testRunAsICIR_TwoBeans() throws Exception { LoginContext lc = Util.getCLMLoginContext("user1", "password1"); lc.login(); try { // TODO - Enable once auth checks are working. /* * try { whoAmIBean.getCallerPrincipal(); fail("Expected call to whoAmIBean to fail"); } catch (Exception expected) * { } */ boolean[] response; response = entryBean.doubleDoIHaveRole("Users"); assertTrue(response[0]); assertFalse(response[1]); response = entryBean.doubleDoIHaveRole("Role1"); assertTrue(response[0]); assertFalse(response[1]); response = entryBean.doubleDoIHaveRole("Role2"); assertFalse(response[0]); assertTrue(response[1]); } finally { lc.logout(); } lc = Util.getCLMLoginContext("user2", "password2"); lc.login(); try { // Verify the call now passes. Principal user = whoAmIBean.getCallerPrincipal(); assertNotNull(user); boolean[] response; response = entryBean.doubleDoIHaveRole("Users"); assertTrue(response[0]); assertFalse(response[1]); response = entryBean.doubleDoIHaveRole("Role1"); assertFalse(response[0]); assertFalse(response[1]); response = entryBean.doubleDoIHaveRole("Role2"); assertTrue(response[0]); assertTrue(response[1]); } finally { lc.logout(); } }
@Test public void testLoginUserIdWithScreenName() throws Exception { _jaasAuthTypeField.set(null, "screenName"); LoginContext loginContext = getLoginContext(String.valueOf(_user.getUserId()), _user.getPassword()); try { loginContext.login(); Assert.fail(); } catch (Exception e) { } }
/** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession httpSession = request.getSession(); LoginContext lc = (LoginContext) httpSession.getAttribute("LoginContext"); try { System.out.println("INVOCO IL LOGOUT"); lc.logout(); } catch (LoginException e) { e.printStackTrace(); } response.sendRedirect(response.encodeRedirectURL("/JAAS_XACML_Exercise2/public/logout.jsp")); }
/** * Authenticates user. * * @param user user - authenticated user * @param password - authentication password * @return true/false - authentication decision */ @Override protected boolean authenticate(Principal user, String password) { String username = user.getName(); LoginContext lc = null; try { lc = new LoginContext(AUTHENTICATION_CONTEXT, new StringCallbackHandler(username, password)); lc.login(); log.info("Kerberos authentication attempt PASSED!"); return true; } catch (LoginException le) { log.error("Kerberos authentication attempt FAILED. Reason:" + le); } return false; }
private Subject login() throws AuthenticationException { try { LoginContext lc = new LoginContext( KerberosLdapContextSource.class.getSimpleName(), null, null, this.loginConfig); lc.login(); return lc.getSubject(); } catch (LoginException e) { AuthenticationException ae = new AuthenticationException(e.getMessage()); ae.initCause(e); throw ae; } }
/** * Returns true if user was successfully authenticated against Kerberos * * @param username username without Kerberos realm attached * @param password kerberos password * @return true if user was successfully authenticated */ public Subject authenticateSubject(String username, String password) throws LoginException { String principal = getKerberosPrincipal(username); logger.debug("Validating password of principal: " + principal); loginContext = new LoginContext( "does-not-matter", null, createJaasCallbackHandler(principal, password), createJaasConfiguration()); loginContext.login(); logger.debug("Principal " + principal + " authenticated succesfully"); return loginContext.getSubject(); }
public static void verifyPassword(String principal, String password) throws LoginException { LoginContext lc = null; try { lc = Krb5Login.withPassword(principal, password); lc.login(); } finally { if (lc != null) { try { lc.logout(); } catch (LoginException le) { ZimbraLog.account.warn("krb5 logout failed", le); } } } }
@Test public void testLoginUserIdWithUserId() throws Exception { _jaasAuthTypeField.set(null, "userId"); LoginContext loginContext = getLoginContext(String.valueOf(_user.getUserId()), _user.getPassword()); try { loginContext.login(); } catch (Exception e) { Assert.fail(); } validateSubject(loginContext.getSubject(), String.valueOf(_user.getUserId())); }
public Subject krb5KeytabLogin(String keytab) { String loginModuleName = "krb5NonInteractiveClientLogin"; LOG.info("Attempting kerberos login of user: "******" using keytab: " + keytab); // Form jaasOptions map Map<String, String> jaasOptions = new HashMap<String, String>(); jaasOptions.put("useKeyTab", "true"); jaasOptions.put("keyTab", keytab); jaasOptions.put("principal", clientPrincipal); jaasOptions.put("storeKey", "true"); // Need this to be true for when the server side logs in. jaasOptions.put("doNotPrompt", "true"); jaasOptions.put("refreshKrb5Config", "false"); jaasOptions.put("clearPass", "true"); jaasOptions.put("useTicketCache", "false"); LOG.debug("Dynamic jaas configuration used:" + jaasOptions.toString()); // Create dynamic jaas config DynamicJaasConfiguration contextConfig = new DynamicJaasConfiguration(); contextConfig.addAppConfigEntry( loginModuleName, "com.sun.security.auth.module.Krb5LoginModule", AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, jaasOptions); try { /* * The nonInteractiveCallbackHandler should not be needed as the jaas config sets the client to use keytab file and not prompt the user. * Therefore this is suitable for system authentication. if the callback handler is used the nonInteractiveCallbackHandler just throws exceptions. */ LoginContext loginCtx = new LoginContext( loginModuleName, null, new NonInteractiveCallbackHandler(), contextConfig); loginCtx.login(); Subject clientSubject = loginCtx.getSubject(); String loggedInUser = principalNameFromSubject(clientSubject); LOG.info("SUCCESSFUL LOGIN for user: "******" using keytab: " + keytab); return clientSubject; } catch (LoginException le) { LOG.info( "LOGIN FAILED for user: "******" using keytab: " + keytab + " Reason: " + le.toString()); le.printStackTrace(); return null; } }
public void generate() throws SAXException, ProcessingException { if (log.isDebugEnabled()) log.debug("begin generate"); contentHandler.startDocument(); Document doc = XercesHelper.getNewDocument(); Element root = doc.createElement("authentication"); doc.appendChild(root); try { LoginContext lc = new LoginContext(jaasRealm, new InternalCallbackHandler()); lc.login(); Subject s = lc.getSubject(); if (log.isDebugEnabled()) log.debug("Subject is: " + s.getPrincipals().toString()); Element idElement = doc.createElement("ID"); root.appendChild(idElement); Iterator it = s.getPrincipals(java.security.Principal.class).iterator(); while (it.hasNext()) { Principal prp = (Principal) it.next(); if (prp.getName().equalsIgnoreCase("Roles")) { Element roles = doc.createElement("roles"); root.appendChild(roles); Group grp = (Group) prp; Enumeration member = grp.members(); while (member.hasMoreElements()) { Principal sg = (Principal) member.nextElement(); Element role = doc.createElement("role"); roles.appendChild(role); Text txt = doc.createTextNode(sg.getName()); role.appendChild(txt); } } else { Node nde = doc.createTextNode(prp.getName()); idElement.appendChild(nde); } } lc.logout(); } catch (Exception exe) { log.warn("Could not login user \"" + userid + "\""); } finally { try { DOMStreamer ds = new DOMStreamer(contentHandler); ds.stream(doc.getDocumentElement()); contentHandler.endDocument(); } catch (Exception exe) { log.error("Error streaming to dom", exe); } if (log.isDebugEnabled()) log.debug("end generate"); } }
/** * Returns true if user with given username exists in kerberos database * * @param username username without Kerberos realm attached or with correct realm attached * @return true if user available */ public boolean isUserAvailable(String username) { logger.debug("Checking existence of user: "******"does-not-matter", null, createJaasCallbackHandler(principal, "fake-password-which-nobody-has"), createJaasConfiguration()); loginContext.login(); throw new IllegalStateException("Didn't expect to end here"); } catch (LoginException le) { String message = le.getMessage(); logger.debug("Message from kerberos: " + message); checkKerberosServerAvailable(le); // Bit cumbersome, but seems to work with tested kerberos servers boolean exists = (!message.contains("Client not found")); return exists; } }
@Test public void testAuthentication_TwoBeans() throws Exception { LoginContext lc = Util.getCLMLoginContext("user1", "password1"); lc.login(); try { String[] response = entryBean.doubleWhoAmI(); assertEquals("user1", response[0]); assertEquals( "anonymous", response[ 1]); // Unless a run-as-principal configuration has been done, you cannot expect a // principal } finally { lc.logout(); } }