Search in sources :

Example 46 with UnsupportedCallbackException

use of javax.security.auth.callback.UnsupportedCallbackException in project keycloak by keycloak.

the class KerberosUsernamePasswordAuthenticator method createJaasCallbackHandler.

protected CallbackHandler createJaasCallbackHandler(final String principal, final String password) {
    return new CallbackHandler() {

        @Override
        public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
            for (Callback callback : callbacks) {
                if (callback instanceof NameCallback) {
                    NameCallback nameCallback = (NameCallback) callback;
                    nameCallback.setName(principal);
                } else if (callback instanceof PasswordCallback) {
                    PasswordCallback passwordCallback = (PasswordCallback) callback;
                    passwordCallback.setPassword(password.toCharArray());
                } else {
                    throw new UnsupportedCallbackException(callback, "Unsupported callback: " + callback.getClass().getCanonicalName());
                }
            }
        }
    };
}
Also used : CallbackHandler(javax.security.auth.callback.CallbackHandler) PasswordCallback(javax.security.auth.callback.PasswordCallback) NameCallback(javax.security.auth.callback.NameCallback) Callback(javax.security.auth.callback.Callback) NameCallback(javax.security.auth.callback.NameCallback) PasswordCallback(javax.security.auth.callback.PasswordCallback) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException)

Example 47 with UnsupportedCallbackException

use of javax.security.auth.callback.UnsupportedCallbackException in project apache-kafka-on-k8s by banzaicloud.

the class SaslClientCallbackHandler method handle.

@Override
public void handle(Callback[] callbacks) throws UnsupportedCallbackException {
    for (Callback callback : callbacks) {
        if (callback instanceof NameCallback) {
            NameCallback nc = (NameCallback) callback;
            if (!isKerberos && subject != null && !subject.getPublicCredentials(String.class).isEmpty()) {
                nc.setName(subject.getPublicCredentials(String.class).iterator().next());
            } else
                nc.setName(nc.getDefaultName());
        } else if (callback instanceof PasswordCallback) {
            if (!isKerberos && subject != null && !subject.getPrivateCredentials(String.class).isEmpty()) {
                char[] password = subject.getPrivateCredentials(String.class).iterator().next().toCharArray();
                ((PasswordCallback) callback).setPassword(password);
            } else {
                String errorMessage = "Could not login: the client is being asked for a password, but the Kafka" + " client code does not currently support obtaining a password from the user.";
                if (isKerberos) {
                    errorMessage += " Make sure -Djava.security.auth.login.config property passed to JVM and" + " the client is configured to use a ticket cache (using" + " the JAAS configuration setting 'useTicketCache=true)'. Make sure you are using" + " FQDN of the Kafka broker you are trying to connect to.";
                }
                throw new UnsupportedCallbackException(callback, errorMessage);
            }
        } else if (callback instanceof RealmCallback) {
            RealmCallback rc = (RealmCallback) callback;
            rc.setText(rc.getDefaultText());
        } else if (callback instanceof AuthorizeCallback) {
            AuthorizeCallback ac = (AuthorizeCallback) callback;
            String authId = ac.getAuthenticationID();
            String authzId = ac.getAuthorizationID();
            ac.setAuthorized(authId.equals(authzId));
            if (ac.isAuthorized())
                ac.setAuthorizedID(authzId);
        } else if (callback instanceof ScramExtensionsCallback) {
            ScramExtensionsCallback sc = (ScramExtensionsCallback) callback;
            if (!isKerberos && subject != null && !subject.getPublicCredentials(Map.class).isEmpty()) {
                sc.extensions((Map<String, String>) subject.getPublicCredentials(Map.class).iterator().next());
            }
        } else {
            throw new UnsupportedCallbackException(callback, "Unrecognized SASL ClientCallback");
        }
    }
}
Also used : RealmCallback(javax.security.sasl.RealmCallback) PasswordCallback(javax.security.auth.callback.PasswordCallback) NameCallback(javax.security.auth.callback.NameCallback) ScramExtensionsCallback(org.apache.kafka.common.security.scram.ScramExtensionsCallback) AuthorizeCallback(javax.security.sasl.AuthorizeCallback) Callback(javax.security.auth.callback.Callback) NameCallback(javax.security.auth.callback.NameCallback) ScramExtensionsCallback(org.apache.kafka.common.security.scram.ScramExtensionsCallback) PasswordCallback(javax.security.auth.callback.PasswordCallback) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) Map(java.util.Map) AuthorizeCallback(javax.security.sasl.AuthorizeCallback) RealmCallback(javax.security.sasl.RealmCallback)

Example 48 with UnsupportedCallbackException

use of javax.security.auth.callback.UnsupportedCallbackException in project apache-kafka-on-k8s by banzaicloud.

the class ScramSaslServer method evaluateResponse.

/**
 * @throws SaslAuthenticationException if the requested authorization id is not the same as username.
 * <p>
 * <b>Note:</b> This method may throw {@link SaslAuthenticationException} to provide custom error messages
 * to clients. But care should be taken to avoid including any information in the exception message that
 * should not be leaked to unauthenticated clients. It may be safer to throw {@link SaslException} in
 * most cases so that a standard error message is returned to clients.
 * </p>
 */
@Override
public byte[] evaluateResponse(byte[] response) throws SaslException, SaslAuthenticationException {
    try {
        switch(state) {
            case RECEIVE_CLIENT_FIRST_MESSAGE:
                this.clientFirstMessage = new ClientFirstMessage(response);
                this.scramExtensions = clientFirstMessage.extensions();
                if (!SUPPORTED_EXTENSIONS.containsAll(scramExtensions.extensionNames())) {
                    log.debug("Unsupported extensions will be ignored, supported {}, provided {}", SUPPORTED_EXTENSIONS, scramExtensions.extensionNames());
                }
                String serverNonce = formatter.secureRandomString();
                try {
                    String saslName = clientFirstMessage.saslName();
                    this.username = formatter.username(saslName);
                    NameCallback nameCallback = new NameCallback("username", username);
                    ScramCredentialCallback credentialCallback;
                    if (scramExtensions.tokenAuthenticated()) {
                        DelegationTokenCredentialCallback tokenCallback = new DelegationTokenCredentialCallback();
                        credentialCallback = tokenCallback;
                        callbackHandler.handle(new Callback[] { nameCallback, tokenCallback });
                        if (tokenCallback.tokenOwner() == null)
                            throw new SaslException("Token Authentication failed: Invalid tokenId : " + username);
                        this.authorizationId = tokenCallback.tokenOwner();
                    } else {
                        credentialCallback = new ScramCredentialCallback();
                        callbackHandler.handle(new Callback[] { nameCallback, credentialCallback });
                        this.authorizationId = username;
                    }
                    this.scramCredential = credentialCallback.scramCredential();
                    if (scramCredential == null)
                        throw new SaslException("Authentication failed: Invalid user credentials");
                    String authorizationIdFromClient = clientFirstMessage.authorizationId();
                    if (!authorizationIdFromClient.isEmpty() && !authorizationIdFromClient.equals(username))
                        throw new SaslAuthenticationException("Authentication failed: Client requested an authorization id that is different from username");
                    if (scramCredential.iterations() < mechanism.minIterations())
                        throw new SaslException("Iterations " + scramCredential.iterations() + " is less than the minimum " + mechanism.minIterations() + " for " + mechanism);
                    this.serverFirstMessage = new ServerFirstMessage(clientFirstMessage.nonce(), serverNonce, scramCredential.salt(), scramCredential.iterations());
                    setState(State.RECEIVE_CLIENT_FINAL_MESSAGE);
                    return serverFirstMessage.toBytes();
                } catch (IOException | NumberFormatException | UnsupportedCallbackException e) {
                    throw new SaslException("Authentication failed: Credentials could not be obtained", e);
                }
            case RECEIVE_CLIENT_FINAL_MESSAGE:
                try {
                    ClientFinalMessage clientFinalMessage = new ClientFinalMessage(response);
                    verifyClientProof(clientFinalMessage);
                    byte[] serverKey = scramCredential.serverKey();
                    byte[] serverSignature = formatter.serverSignature(serverKey, clientFirstMessage, serverFirstMessage, clientFinalMessage);
                    ServerFinalMessage serverFinalMessage = new ServerFinalMessage(null, serverSignature);
                    clearCredentials();
                    setState(State.COMPLETE);
                    return serverFinalMessage.toBytes();
                } catch (InvalidKeyException e) {
                    throw new SaslException("Authentication failed: Invalid client final message", e);
                }
            default:
                throw new IllegalSaslStateException("Unexpected challenge in Sasl server state " + state);
        }
    } catch (SaslException e) {
        clearCredentials();
        setState(State.FAILED);
        throw e;
    }
}
Also used : ClientFirstMessage(org.apache.kafka.common.security.scram.ScramMessages.ClientFirstMessage) IOException(java.io.IOException) IllegalSaslStateException(org.apache.kafka.common.errors.IllegalSaslStateException) SaslException(javax.security.sasl.SaslException) InvalidKeyException(java.security.InvalidKeyException) NameCallback(javax.security.auth.callback.NameCallback) ClientFinalMessage(org.apache.kafka.common.security.scram.ScramMessages.ClientFinalMessage) ServerFinalMessage(org.apache.kafka.common.security.scram.ScramMessages.ServerFinalMessage) DelegationTokenCredentialCallback(org.apache.kafka.common.security.token.delegation.DelegationTokenCredentialCallback) ServerFirstMessage(org.apache.kafka.common.security.scram.ScramMessages.ServerFirstMessage) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) SaslAuthenticationException(org.apache.kafka.common.errors.SaslAuthenticationException)

Example 49 with UnsupportedCallbackException

use of javax.security.auth.callback.UnsupportedCallbackException in project xades4j by luisgoncalves.

the class KeyStoreKeyingDataProvider method ensureInitialized.

private void ensureInitialized() throws UnexpectedJCAException {
    synchronized (this.lockObj) {
        if (!this.initialized) {
            try {
                KeyStore.CallbackHandlerProtection storeLoadProtec = null;
                if (storePasswordProvider != null)
                    // Create the load protection with callback.
                    storeLoadProtec = new KeyStore.CallbackHandlerProtection(new CallbackHandler() {

                        @Override
                        public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
                            PasswordCallback c = (PasswordCallback) callbacks[0];
                            c.setPassword(storePasswordProvider.getPassword());
                        }
                    });
                else
                    // If no load password provider is supplied is because it shouldn't
                    // be needed. Create a dummy protection because the keystore
                    // builder needs it to be non-null.
                    storeLoadProtec = new KeyStore.CallbackHandlerProtection(new CallbackHandler() {

                        @Override
                        public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
                            throw new UnsupportedOperationException("No KeyStorePasswordProvider");
                        }
                    });
                this.keyStore = builderCreator.getBuilder(storeLoadProtec).getKeyStore();
            } catch (KeyStoreException ex) {
                throw new UnexpectedJCAException("The keystore couldn't be initialized", ex);
            }
            this.initialized = true;
        }
    }
}
Also used : CallbackHandler(javax.security.auth.callback.CallbackHandler) IOException(java.io.IOException) KeyStoreException(java.security.KeyStoreException) KeyStore(java.security.KeyStore) PasswordCallback(javax.security.auth.callback.PasswordCallback) Callback(javax.security.auth.callback.Callback) UnexpectedJCAException(xades4j.verification.UnexpectedJCAException) PasswordCallback(javax.security.auth.callback.PasswordCallback) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException)

Example 50 with UnsupportedCallbackException

use of javax.security.auth.callback.UnsupportedCallbackException in project Bytecoder by mirkosertic.

the class ConsoleCallbackHandler method handle.

/**
 * Handles the specified set of callbacks.
 *
 * @param callbacks the callbacks to handle
 * @throws IOException if an input or output error occurs.
 * @throws UnsupportedCallbackException if the callback is not an
 * instance of NameCallback or PasswordCallback
 */
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
    ConfirmationCallback confirmation = null;
    for (int i = 0; i < callbacks.length; i++) {
        if (callbacks[i] instanceof TextOutputCallback) {
            TextOutputCallback tc = (TextOutputCallback) callbacks[i];
            String text;
            switch(tc.getMessageType()) {
                case TextOutputCallback.INFORMATION:
                    text = "";
                    break;
                case TextOutputCallback.WARNING:
                    text = "Warning: ";
                    break;
                case TextOutputCallback.ERROR:
                    text = "Error: ";
                    break;
                default:
                    throw new UnsupportedCallbackException(callbacks[i], "Unrecognized message type");
            }
            String message = tc.getMessage();
            if (message != null) {
                text += message;
            }
            if (text != null) {
                System.err.println(text);
            }
        } else if (callbacks[i] instanceof NameCallback) {
            NameCallback nc = (NameCallback) callbacks[i];
            if (nc.getDefaultName() == null) {
                System.err.print(nc.getPrompt());
            } else {
                System.err.print(nc.getPrompt() + " [" + nc.getDefaultName() + "] ");
            }
            System.err.flush();
            String result = readLine();
            if (result.equals("")) {
                result = nc.getDefaultName();
            }
            nc.setName(result);
        } else if (callbacks[i] instanceof PasswordCallback) {
            PasswordCallback pc = (PasswordCallback) callbacks[i];
            System.err.print(pc.getPrompt());
            System.err.flush();
            pc.setPassword(Password.readPassword(System.in, pc.isEchoOn()));
        } else if (callbacks[i] instanceof ConfirmationCallback) {
            confirmation = (ConfirmationCallback) callbacks[i];
        } else {
            throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback");
        }
    }
    /* Do the confirmation callback last. */
    if (confirmation != null) {
        doConfirmation(confirmation);
    }
}
Also used : ConfirmationCallback(javax.security.auth.callback.ConfirmationCallback) NameCallback(javax.security.auth.callback.NameCallback) PasswordCallback(javax.security.auth.callback.PasswordCallback) TextOutputCallback(javax.security.auth.callback.TextOutputCallback) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException)

Aggregations

UnsupportedCallbackException (javax.security.auth.callback.UnsupportedCallbackException)332 Callback (javax.security.auth.callback.Callback)213 IOException (java.io.IOException)201 NameCallback (javax.security.auth.callback.NameCallback)182 PasswordCallback (javax.security.auth.callback.PasswordCallback)177 LoginException (javax.security.auth.login.LoginException)89 CallbackHandler (javax.security.auth.callback.CallbackHandler)63 FailedLoginException (javax.security.auth.login.FailedLoginException)45 LoginContext (javax.security.auth.login.LoginContext)43 Subject (javax.security.auth.Subject)36 Principal (java.security.Principal)34 AuthorizeCallback (javax.security.sasl.AuthorizeCallback)31 RealmCallback (javax.security.sasl.RealmCallback)27 HttpServletRequest (javax.servlet.http.HttpServletRequest)27 HashMap (java.util.HashMap)23 CallerPrincipalCallback (javax.security.auth.message.callback.CallerPrincipalCallback)23 Test (org.junit.Test)21 GroupPrincipalCallback (javax.security.auth.message.callback.GroupPrincipalCallback)20 SaslException (javax.security.sasl.SaslException)19 AuthException (javax.security.auth.message.AuthException)18