public boolean login() throws LoginException { // prompt for a user name and password if (callbackHandler == null) throw new LoginException( "Error: no CallbackHandler available " + "to garner authentication information from the user"); Callback[] callbacks = new Callback[1]; callbacks[0] = new CMCCArtifactIDCallback(); try { this.callbackHandler.handle(callbacks); this.artifactID = ((CMCCArtifactIDCallback) callbacks[0]).getArtifactID(); this.artifactDomain = ((CMCCArtifactIDCallback) callbacks[0]).getArtifactDomain(); if (StringUtils.isEmpty(artifactID)) { succeeded = false; artifactID = null; return false; } Helper.validateArtifactID(artifactID); } catch (java.io.IOException e) { log.error(e.getMessage(), e); throw new LoginException(e.toString()); } catch (UnsupportedCallbackException e) { log.error(e.getMessage(), e); throw new LoginException( "Error: " + e.getCallback().toString() + " not available to garner authentication information " + "from the user"); } // print debugging information if (debug) { log.info("Resolv artifactId from cookie: " + artifactID); } // verify the artifactID/password boolean correct; try { correct = authenticate(artifactID, artifactDomain); } catch (Exception e) { log.error("Failure to check artifactID.", e); throw new LoginException(e.getMessage()); } if (correct) { // authentication succeeded!!! if (debug) log.info("Success to verify artifactID: [" + artifactID + "]"); succeeded = true; return true; } else { // authentication failed -- clean out state if (debug) log.info("Invalidate artifactID: [" + artifactID + "]"); succeeded = false; artifactID = null; artifactDomain = null; return false; } }
@Override public boolean login() throws LoginException { Callback[] callbacks = new Callback[2]; callbacks[0] = new NameCallback(Messages.PROMPT_USERNAME.getText()); callbacks[1] = new PasswordCallback(Messages.PROMPT_PASSWORD.getText(), false); try { mCallback.handle(callbacks); } catch (UnsupportedCallbackException e) { final LoginException ex = new FailedLoginException(e.getMessage()); ex.initCause(e); throw ex; } catch (IOException e) { final LoginException ex = new FailedLoginException(e.getMessage()); ex.initCause(e); throw ex; } mUsername = ((NameCallback) callbacks[0]).getName(); if (mUsername == null || mUsername.trim().length() == 0) { throw new AccountNotFoundException(Messages.EMPTY_USERNAME.getText()); } char[] password = ((PasswordCallback) callbacks[1]).getPassword(); try { if (!ClientLoginHelper.isValidCredentials(mUsername, password)) { Messages.USER_LOGIN_ERROR_LOG.warn(this, mUsername); throw new FailedLoginException(Messages.USER_LOGIN_FAIL.getText(mUsername)); } } catch (ClientInitException e) { Messages.USER_LOGIN_ERROR_LOG.warn(this, e, mUsername); LoginException exception = new FailedLoginException(Messages.USER_LOGIN_ERROR.getText()); exception.initCause(e); throw exception; } SLF4JLoggerProxy.debug(this, "login done for user {}", mUsername); // $NON-NLS-1$ return true; }
@Override protected void getLoginDataFromUser() throws LoginException { try { getCallbackHandler().handle(callbacks); setUsername(getNameFromCallback()); setPassword(getPasswordFromCallback()); resetPassword(); } catch (java.io.IOException ioe) { throw new LoginException(ioe.toString()); } catch (UnsupportedCallbackException uce) { throw new LoginException( "Callback error : " + uce.getCallback().toString() + " not available to authenticate the user"); } }
public boolean login() throws LoginException { Callback[] callbacks = new Callback[2]; callbacks[0] = new NameCallback("Username: "******"Password: "******" not available to obtain information from user"); } String user = ((NameCallback) callbacks[0]).getName(); char[] tmpPassword = ((PasswordCallback) callbacks[1]).getPassword(); return user.equals(new String(tmpPassword)); }
/** Here, we attempt to get the password from the private alias/passwords map. */ public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { for (Callback callback : callbacks) { try { String id = (String) callback.getClass().getMethod("getIdentifier").invoke(callback); String pass = passwords.get(id); if (pass != null) { callback.getClass().getMethod("setPassword", String.class).invoke(callback, pass); return; } } catch (Exception ex) { UnsupportedCallbackException e = new UnsupportedCallbackException(callback); e.initCause(ex); throw e; } } }
/** * Retrieves the user name by querying the property of {@link Constants#SECURITY_LOGIN_USERNAME} * through {@link AppCallbackHandler}. * * @return true if user name provided by application is set and not empty * @throws LoginException when the login fails */ @Override public boolean login() throws LoginException { Callback[] callbacks = new Callback[1]; callbacks[0] = new NameCallback("user name: "); try { mCallbackHandler.handle(callbacks); } catch (IOException e) { throw new LoginException(e.getMessage()); } catch (UnsupportedCallbackException e) { throw new LoginException(e.getMessage()); } String userName = ((NameCallback) callbacks[0]).getName(); if (!userName.isEmpty()) { mUser = new User(userName); return true; } return false; }
private void getSaltedPasswordFromTwoWay(NameCallback nameCallback, ByteStringBuilder b) throws SaslException { CredentialCallback credentialCallback = new CredentialCallback(singletonMap(TwoWayPassword.class, emptySet())); final ParameterCallback parameterCallback = new ParameterCallback(IteratedSaltedPasswordAlgorithmSpec.class); try { tryHandleCallbacks(nameCallback, parameterCallback, credentialCallback); algorithmSpec = (IteratedSaltedPasswordAlgorithmSpec) parameterCallback.getParameterSpec(); if (algorithmSpec == null) throw new FastUnsupportedCallbackException(parameterCallback); } catch (UnsupportedCallbackException e) { Callback callback = e.getCallback(); if (callback == nameCallback) { throw log.saslCallbackHandlerDoesNotSupportUserName(getMechanismName(), e); } else if (callback == credentialCallback) { return; // credential acquisition not supported } else if (callback == parameterCallback) { // one more try, with default parameters salt = ScramUtil.generateSalt(16, getRandom()); algorithmSpec = new IteratedSaltedPasswordAlgorithmSpec(minimumIterationCount, salt); try { tryHandleCallbacks(nameCallback, credentialCallback); } catch (UnsupportedCallbackException ex) { callback = ex.getCallback(); if (callback == nameCallback) { throw log.saslCallbackHandlerDoesNotSupportUserName(getMechanismName(), ex); } else if (callback == credentialCallback) { return; } else { throw log.saslCallbackHandlerFailedForUnknownReason(getMechanismName(), ex); } } } else { throw log.saslCallbackHandlerDoesNotSupportCredentialAcquisition(getMechanismName(), e); } } // get the clear password TwoWayPassword password = (TwoWayPassword) credentialCallback.getCredential(); char[] passwordChars = ScramUtil.getTwoWayPasswordChars(getMechanismName(), password); getSaltedPasswordFromPasswordChars(passwordChars, b); }
@Override public boolean login() throws LoginException { Callback[] callbacks = new Callback[2]; callbacks[0] = new NameCallback("Username: "******"Password: "******" not available to obtain information from user"); } user = ((NameCallback) callbacks[0]).getName(); char[] tmpPassword = ((PasswordCallback) callbacks[1]).getPassword(); if (tmpPassword == null) { tmpPassword = new char[0]; } if (user == null) { if (configuration.getDefaultUser() == null) { throw new FailedLoginException("Both username and defaultUser are null"); } else { user = configuration.getDefaultUser(); } } else { String password = configuration.getUser(user) == null ? null : configuration.getUser(user).getPassword(); if (password == null) { throw new FailedLoginException("User does not exist"); } if (!password.equals(new String(tmpPassword))) { throw new FailedLoginException("Password does not match"); } } loginSucceeded = true; logger.debug("login " + user); return loginSucceeded; }
/** * The instance method checks if for the given user the password is correct and the person is * active (status equals 10001).<br> * All exceptions which could be thrown from the test are catched. Instead a <i>false</i> is * returned. * * @param _name name of the person name to check * @param _passwd password of the person to check * @return <i>true</i> if user name and password is correct and exists, otherwise <i>false</i> is * returned * @return <i>true</i> if login is allowed and user name with password is correct * @throws FailedLoginException if login is not allowed with given user name and password (if user * does not exists or password is not correct) * @throws LoginException if an error occurs while calling the callback handler or the {@link * #checkLogin} method * @throws LoginException if user or password could not be get from the callback handler */ public final boolean login() throws LoginException { boolean ret = false; Callback[] callbacks = new Callback[2]; callbacks[0] = new NameCallback("Username: "******"Password: "******"login failed for user '" + userName + "'", e); throw new LoginException(e.toString()); } catch (UnsupportedCallbackException e) { LOG.error("login failed for user '" + userName + "'", e); throw new LoginException(e.toString()); } if (userName != null) { try { Person person = Person.getWithJAASKey(JAASSystem.getJAASSystem(this.jaasSystem), userName); if (person != null) { if (!person.checkPassword(password)) { throw new FailedLoginException("Username or password is incorrect"); } ret = true; this.principal = new PersonPrincipal(userName); if (LOG.isDebugEnabled()) { LOG.debug("login " + userName + " " + this.principal); } } } catch (EFapsException e) { LOG.error("login failed for user '" + userName + "'", e); throw new LoginException(e.toString()); } } return ret; }
/** * @see javax.security.auth.spi.LoginModule#login() * @return true if is authenticated, false otherwise * @throws LoginException */ public boolean login() throws LoginException { try { if (callbackHandler == null) throw new LoginException("No callback handler"); Callback[] callbacks = configureCallbacks(); callbackHandler.handle(callbacks); String webUserName = ((NameCallback) callbacks[0]).getName(); Object webCredential = null; webCredential = ((ObjectCallback) callbacks[1]) .getObject(); // first check if ObjectCallback has the credential if (webCredential == null) webCredential = ((PasswordCallback) callbacks[2]).getPassword(); // use standard PasswordCallback if ((webUserName == null) || (webCredential == null)) { setAuthenticated(false); return isAuthenticated(); } UserInfo userInfo = getUserInfo(webUserName); if (userInfo == null) { setAuthenticated(false); return isAuthenticated(); } currentUser = new JAASUserInfo(userInfo); setAuthenticated(currentUser.checkCredential(webCredential)); return isAuthenticated(); } catch (IOException e) { throw new LoginException(e.toString()); } catch (UnsupportedCallbackException e) { throw new LoginException(e.toString()); } catch (Exception e) { e.printStackTrace(); throw new LoginException(e.toString()); } }
@Test public void testHandler() { DefaultCallbackHandler handler = new DefaultCallbackHandler(); SecurityContext context = new SecurityContext(); handler.setup(context); Callback[] callbacks = new Callback[3]; callbacks[0] = new NameCallback("UserName:"******"Password:"******"Realm:"); try { handler.handle(callbacks); Assert.assertEquals("Username", "user1", ((NameCallback) callbacks[0]).getName()); Assert.assertEquals( "Password", "pass", new String(((PasswordCallback) callbacks[1]).getPassword())); Assert.assertEquals("Realm", "default", ((RealmCallback) callbacks[2]).getText()); } catch (IOException e) { Assert.fail(e.getMessage()); } catch (UnsupportedCallbackException e) { Assert.fail(e.getMessage()); } }
private void getSaltedPasswordFromPasswordCallback(NameCallback nameCallback, ByteStringBuilder b) throws SaslException { final PasswordCallback passwordCallback = new PasswordCallback("User password", false); try { tryHandleCallbacks(nameCallback, passwordCallback); } catch (UnsupportedCallbackException e) { final Callback callback = e.getCallback(); if (callback == nameCallback) { throw log.saslCallbackHandlerDoesNotSupportUserName(getMechanismName(), e); } else if (callback == passwordCallback) { return; // PasswordCallback not supported } else { throw log.saslCallbackHandlerFailedForUnknownReason(getMechanismName(), e); } } salt = ScramUtil.generateSalt(16, getRandom()); algorithmSpec = new IteratedSaltedPasswordAlgorithmSpec(minimumIterationCount, salt); char[] passwordChars = passwordCallback.getPassword(); passwordCallback.clearPassword(); getSaltedPasswordFromPasswordChars(passwordChars, b); }
/** * Method tries to acquire an Impersonator in the following order: * * <ul> * <li>Try to access it from the {@link Credentials} via {@link * SimpleCredentials#getAttribute(String)} * <li>Ask CallbackHandler for Impersonator with use of {@link ImpersonationCallback}. * </ul> * * @param credentials which, may contain an impersonation Subject * @return impersonation subject or null if non contained * @see #login() * @see #impersonate(java.security.Principal, javax.jcr.Credentials) */ protected Subject getImpersonatorSubject(Credentials credentials) { Subject impersonator = null; if (credentials == null) { try { ImpersonationCallback impers = new ImpersonationCallback(); callbackHandler.handle(new Callback[] {impers}); impersonator = impers.getImpersonator(); } catch (UnsupportedCallbackException e) { log.warn( e.getCallback().getClass().getName() + " not supported: Unable to perform Impersonation."); } catch (IOException e) { log.error( "Impersonation-Callback failed: " + e.getMessage() + ": Unable to perform Impersonation."); } } else if (credentials instanceof SimpleCredentials) { SimpleCredentials sc = (SimpleCredentials) credentials; impersonator = (Subject) sc.getAttribute(SecurityConstants.IMPERSONATOR_ATTRIBUTE); } return impersonator; }
/** * Get the username and password. This method does not return any value. Instead, it sets global * name and password variables. * * <p>Also note that this method will set the username and password values in the shared state in * case subsequent LoginModules want to use them via use/tryFirstPass. * * @param getPasswdFromSharedState boolean that tells this method whether to retrieve the password * from the sharedState. * @exception LoginException if the username/password cannot be acquired. */ private void getUsernamePassword(boolean getPasswdFromSharedState) throws LoginException { if (getPasswdFromSharedState) { // use the password saved by the first module in the stack username = (String) sharedState.get(USERNAME_KEY); password = (char[]) sharedState.get(PASSWORD_KEY); return; } // prompt for a username and password if (callbackHandler == null) throw new LoginException( "No CallbackHandler available " + "to acquire authentication information from the user"); Callback[] callbacks = new Callback[2]; callbacks[0] = new NameCallback(rb.getString("username: "******"password: "******"Error: " + uce.getCallback().toString() + " not available to acquire authentication information" + " from the user"); } }
@Override public boolean login() throws LoginException { if (this.callbackHandler == null) throw new LoginException("No callbackHandler available."); Callback[] callbacks = new Callback[2]; callbacks[0] = new NameCallback("User Name:"); callbacks[1] = new PasswordCallback("Password:"******"Callback " + e.getCallback() + " is not support."); } if (debug) { System.out.println("\t\t[DefaultLoginModule] " + "user entered user name: " + username); System.out.print("\t\t[DefaultLoginModule] " + "user entered password: "); for (int i = 0; i < password.length; i++) System.out.print(password[i]); System.out.println(); } succeeded = true; return true; }
private void getPredigestedSaltedPassword(NameCallback nameCallback) throws SaslException { String passwordType; switch (getMechanismName()) { case SaslMechanismInformation.Names.SCRAM_SHA_1: case SaslMechanismInformation.Names.SCRAM_SHA_1_PLUS: { passwordType = ScramDigestPassword.ALGORITHM_SCRAM_SHA_1; break; } case SaslMechanismInformation.Names.SCRAM_SHA_256: case SaslMechanismInformation.Names.SCRAM_SHA_256_PLUS: { passwordType = ScramDigestPassword.ALGORITHM_SCRAM_SHA_256; break; } case SaslMechanismInformation.Names.SCRAM_SHA_384: case SaslMechanismInformation.Names.SCRAM_SHA_384_PLUS: { passwordType = ScramDigestPassword.ALGORITHM_SCRAM_SHA_384; break; } case SaslMechanismInformation.Names.SCRAM_SHA_512: case SaslMechanismInformation.Names.SCRAM_SHA_512_PLUS: { passwordType = ScramDigestPassword.ALGORITHM_SCRAM_SHA_512; break; } default: throw Assert.impossibleSwitchCase(getMechanismName()); } CredentialCallback credentialCallback = new CredentialCallback(singletonMap(ScramDigestPassword.class, singleton(passwordType))); try { tryHandleCallbacks(nameCallback, credentialCallback); } catch (UnsupportedCallbackException e) { final Callback callback = e.getCallback(); if (callback == nameCallback) { throw log.saslCallbackHandlerDoesNotSupportUserName(getMechanismName(), e); } else if (callback == credentialCallback) { return; // pre digested not supported } else { throw log.saslCallbackHandlerFailedForUnknownReason(getMechanismName(), e); } } Password password = (Password) credentialCallback.getCredential(); if (password instanceof ScramDigestPassword) { // got a scram password final ScramDigestPassword scramDigestPassword = (ScramDigestPassword) password; if (!passwordType.equals(scramDigestPassword.getAlgorithm())) { return; } iterationCount = scramDigestPassword.getIterationCount(); salt = scramDigestPassword.getSalt(); if (iterationCount < minimumIterationCount) { throw log.saslIterationCountIsTooLow( getMechanismName(), iterationCount, minimumIterationCount); } else if (iterationCount > maximumIterationCount) { throw log.saslIterationCountIsTooHigh( getMechanismName(), iterationCount, maximumIterationCount); } if (salt == null) { throw log.saslSaltMustBeSpecified(getMechanismName()); } saltedPassword = scramDigestPassword.getDigest(); } }
/** * Authenticate the user by prompting for the SSO Session Identifier assigned by the SSO Gateway * on logon. * * <p>This method obtains from the gateway, using the provided session identifier, the user * associated with such session identifier. Only the NameCallBack is used, since its not a * user/password pair but only one value containing the session identifier. Any other callback * type is ignored. * * @return true in all cases since this LoginModule should not be ignored. * @exception javax.security.auth.login.FailedLoginException if the authentication fails. * @exception javax.security.auth.login.LoginException if this LoginModule is unable to perform * the authentication. */ public boolean login() throws LoginException { if (_callbackHandler == null) throw new LoginException( "Error: no CallbackHandler available " + "to garner authentication information from the user"); Callback[] callbacks = new Callback[4]; // Just ask for the session identifier callbacks[0] = new NameCallback("ssoSessionId"); callbacks[1] = new PasswordCallback("password", false); callbacks[2] = new NameCallback("appID"); callbacks[3] = new NameCallback("nodeID"); String ssoSessionId; String ssoSessionId2 = null; try { _callbackHandler.handle(callbacks); ssoSessionId = ((NameCallback) callbacks[0]).getName(); if (((PasswordCallback) callbacks[1]).getPassword() != null) ssoSessionId2 = String.valueOf(((PasswordCallback) callbacks[1]).getPassword()); _requester = ((NameCallback) callbacks[2]).getName(); _nodeId = ((NameCallback) callbacks[3]).getName(); } catch (java.io.IOException ioe) { throw new LoginException(ioe.toString()); } catch (UnsupportedCallbackException uce) { throw new LoginException( "Error: " + uce.getCallback().toString() + " not available to garner authentication information " + "from the user"); } logger.debug( "Requested authentication to gateway by " + _requester + " using sso session " + ssoSessionId + "/" + ssoSessionId2); try { if (ssoSessionId2 != null && !ssoSessionId2.equals(ssoSessionId)) ssoSessionId = ssoSessionId2; // If no session is found, ignore this module. if (ssoSessionId == null) { logger.debug("Session authentication failed : " + ssoSessionId); _succeeded = false; return false; } _currentSSOSessionId = ssoSessionId; SSOUser ssoUser = null; SSOAgent agent = Lookup.getInstance().lookupSSOAgent(); SSOIdentityManagerService im = agent.getSSOIdentityManager(); if (_nodeId != null && !"".equals(_nodeId)) { im = agent.getSSOIdentityManager(_nodeId); } ssoUser = im.findUserInSession(_requester, ssoSessionId); logger.debug("Session authentication succeeded : " + ssoSessionId); _ssoUserPrincipal = ssoUser; _succeeded = true; } catch (SSOIdentityException e) { // Ignore this ... (user does not exist for this session) if (logger.isDebugEnabled()) logger.debug(e.getMessage()); _succeeded = false; return false; } catch (Exception e) { logger.error("Session authentication failed : " + ssoSessionId, e); _succeeded = false; clearCredentials(); throw new FailedLoginException("Fatal error authenticating session : " + e); } return true; }
@Override public boolean login() throws LoginException { NameCallback nameCallback = new NameCallback("Username"); PasswordCallback passwordCallback = new PasswordCallback("Password", false); Callback callbacks[] = new Callback[] {nameCallback, passwordCallback}; try { callbackHandler.handle(callbacks); } catch (java.io.IOException e) { throw new LoginException(e.toString()); } catch (UnsupportedCallbackException e) { throw new LoginException("Error: " + e.getCallback().toString()); } boolean success; ParticipantId id = null; String address = nameCallback.getName(); if (!address.contains(ParticipantId.DOMAIN_PREFIX)) { address = address + ParticipantId.DOMAIN_PREFIX + AccountStoreHolder.getDefaultDomain(); } try { id = ParticipantId.of(address); AccountData account = accountStore.getAccount(id); char[] password = passwordCallback.getPassword(); if (account == null) { // The user doesn't exist. Auth failed. success = false; } else if (!account.isHuman()) { // The account is owned by a robot. Auth failed. success = false; } else if (password == null) { // Null password provided by callback. We require a password (even an empty one). success = false; } else if (!account.asHuman().getPasswordDigest().verify(password)) { // The supplied password doesn't match. Auth failed. success = false; } else { success = true; } } catch (InvalidParticipantAddress e) { // The supplied user address is invalid. Auth failed. success = false; } catch (PersistenceException e) { LOG.severe("Failed to retreive account data for " + id, e); throw new LoginException( "An unexpected error occured while trying to retrieve account information!"); } // The password is zeroed before it gets GC'ed for memory security. passwordCallback.clearPassword(); if (success) { principal = new ParticipantPrincipal(id); status = Status.OK; return true; } else { return false; } }
@Override public AuthStatus validateRequest( MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject) throws AuthException { HttpServletRequest request = (HttpServletRequest) messageInfo.getRequestMessage(); HttpServletResponse response = (HttpServletResponse) messageInfo.getResponseMessage(); String credentials = request.getHeader(HttpHeader.AUTHORIZATION.asString()); try { boolean stale = false; // TODO extract from request long timestamp = System.currentTimeMillis(); if (credentials != null) { if (LOG.isDebugEnabled()) LOG.debug("Credentials: " + credentials); QuotedStringTokenizer tokenizer = new QuotedStringTokenizer(credentials, "=, ", true, false); final Digest digest = new Digest(request.getMethod()); String last = null; String name = null; while (tokenizer.hasMoreTokens()) { String tok = tokenizer.nextToken(); char c = (tok.length() == 1) ? tok.charAt(0) : '\0'; switch (c) { case '=': name = last; last = tok; break; case ',': name = null; case ' ': break; default: last = tok; if (name != null) { if ("username".equalsIgnoreCase(name)) digest.username = tok; else if ("realm".equalsIgnoreCase(name)) digest.realm = tok; else if ("nonce".equalsIgnoreCase(name)) digest.nonce = tok; else if ("nc".equalsIgnoreCase(name)) digest.nc = tok; else if ("cnonce".equalsIgnoreCase(name)) digest.cnonce = tok; else if ("qop".equalsIgnoreCase(name)) digest.qop = tok; else if ("uri".equalsIgnoreCase(name)) digest.uri = tok; else if ("response".equalsIgnoreCase(name)) digest.response = tok; break; } } } int n = checkNonce(digest.nonce, timestamp); if (n > 0) { if (login( clientSubject, digest.username, digest, Constraint.__DIGEST_AUTH, messageInfo)) { return AuthStatus.SUCCESS; } } else if (n == 0) stale = true; } if (!isMandatory(messageInfo)) { return AuthStatus.SUCCESS; } String domain = request.getContextPath(); if (domain == null) domain = "/"; response.setHeader( HttpHeader.WWW_AUTHENTICATE.asString(), "Digest realm=\"" + realmName + "\", domain=\"" + domain + "\", nonce=\"" + newNonce(timestamp) + "\", algorithm=MD5, qop=\"auth\"" + (useStale ? (" stale=" + stale) : "")); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return AuthStatus.SEND_CONTINUE; } catch (IOException e) { throw new AuthException(e.getMessage()); } catch (UnsupportedCallbackException e) { throw new AuthException(e.getMessage()); } }
public PrivateKey getPrivateKey(String alias) { RandomAccessFile raf = null; try { if (key == null && keyfile != null) // If keyfile is null, we do not load the key { // The private key must be loaded if (cert == null) { // We need the certificate for the algorithm if (getCertificateChain("user") == null) return null; // getCertificateChain failed... } try { raf = new RandomAccessFile(new File(keyfile), "r"); } catch (FileNotFoundException ex) { if (!defaultfile) { // It is not an error if there is no file at the default location throw ex; } return null; } byte[] keydata = new byte[(int) raf.length()]; raf.readFully(keydata); raf.close(); raf = null; KeyFactory kf = KeyFactory.getInstance(cert[0].getPublicKey().getAlgorithm()); try { KeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keydata); key = kf.generatePrivate(pkcs8KeySpec); } catch (InvalidKeySpecException ex) // The key might be password protected { EncryptedPrivateKeyInfo ePKInfo = new EncryptedPrivateKeyInfo(keydata); Cipher cipher; try { cipher = Cipher.getInstance(ePKInfo.getAlgName()); } catch ( NoSuchPaddingException npex) { // Why is it not a subclass of NoSuchAlgorithmException? throw new NoSuchAlgorithmException(npex.getMessage(), npex); } // We call back for the password PasswordCallback pwdcb = new PasswordCallback(GT.tr("Enter SSL password: "******"Console is not available".equals(ucex.getMessage()))) { error = new PSQLException( GT.tr( "Could not read password for SSL key file, console is not available.", null), PSQLState.CONNECTION_FAILURE, ucex); } else { error = new PSQLException( GT.tr( "Could not read password for SSL key file by callbackhandler {0}.", new Object[] {cbh.getClass().getName()}), PSQLState.CONNECTION_FAILURE, ucex); } return null; } try { PBEKeySpec pbeKeySpec = new PBEKeySpec(pwdcb.getPassword()); // Now create the Key from the PBEKeySpec SecretKeyFactory skFac = SecretKeyFactory.getInstance(ePKInfo.getAlgName()); Key pbeKey = skFac.generateSecret(pbeKeySpec); // Extract the iteration count and the salt AlgorithmParameters algParams = ePKInfo.getAlgParameters(); cipher.init(Cipher.DECRYPT_MODE, pbeKey, algParams); // Decrypt the encryped private key into a PKCS8EncodedKeySpec KeySpec pkcs8KeySpec = ePKInfo.getKeySpec(cipher); key = kf.generatePrivate(pkcs8KeySpec); } catch (GeneralSecurityException ikex) { error = new PSQLException( GT.tr("Could not decrypt SSL key file {0}.", new Object[] {keyfile}), PSQLState.CONNECTION_FAILURE, ikex); return null; } } } } catch (IOException ioex) { if (raf != null) { try { raf.close(); } catch (IOException ex) { } ; } error = new PSQLException( GT.tr("Could not read SSL key file {0}.", new Object[] {keyfile}), PSQLState.CONNECTION_FAILURE, ioex); } catch (NoSuchAlgorithmException ex) { error = new PSQLException( GT.tr( "Could not find a java cryptographic algorithm: {0}.", new Object[] {ex.getMessage()}), PSQLState.CONNECTION_FAILURE, ex); return null; } return key; }
public boolean login() throws LoginException { File f = new File(usersFile); Properties users; try { users = new Properties(f); } catch (IOException ioe) { throw new LoginException("Unable to load user properties file " + f); } Callback[] callbacks = new Callback[2]; callbacks[0] = new NameCallback("Username: "******" not available to obtain information from user"); } String user = ((NameCallback) callbacks[0]).getName(); if (user == null) { throw new FailedLoginException("Unable to retrieve user name"); } PublicKey key = ((PublickeyCallback) callbacks[1]).getPublicKey(); if (key == null) { throw new FailedLoginException("Unable to retrieve public key"); } // user infos container read from the users properties file String userInfos = null; try { userInfos = (String) users.get(user); } catch (NullPointerException e) { // error handled in the next statement } if (userInfos == null) { if (!this.detailedLoginExcepion) { throw new FailedLoginException("login failed"); } else { throw new FailedLoginException("User " + user + " does not exist"); } } // the password is in the first position String[] infos = userInfos.split(","); String storedKey = infos[0]; // check if the stored password is flagged as encrypted String encryptedKey = getEncryptedPassword(storedKey); if (!storedKey.equals(encryptedKey)) { if (debug) { LOG.debug("The key isn't flagged as encrypted, encrypt it."); } if (debug) { LOG.debug("Rebuild the user informations string."); } userInfos = encryptedKey + ","; for (int i = 2; i < infos.length; i++) { if (i == (infos.length - 1)) { userInfos = userInfos + infos[i]; } else { userInfos = userInfos + infos[i] + ","; } } if (debug) { LOG.debug("Push back the user informations in the users properties."); } users.put(user, userInfos); try { if (debug) { LOG.debug("Store the users properties file."); } users.save(); } catch (IOException ioe) { LOG.warn("Unable to write user properties file " + f, ioe); } storedKey = encryptedKey; } // check the provided password if (!checkPassword(getString(key), storedKey)) { if (!this.detailedLoginExcepion) { throw new FailedLoginException("login failed"); } else { throw new FailedLoginException("Public key for " + user + " does not match"); } } principals = new HashSet<Principal>(); principals.add(new UserPrincipal(user)); for (int i = 1; i < infos.length; i++) { principals.add(new RolePrincipal(infos[i])); } users.clear(); if (debug) { LOG.debug("Successfully logged in " + user); } return true; }