Search in sources :

Example 11 with Base64Exception

use of org.apache.cxf.common.util.Base64Exception in project midpoint by Evolveum.

the class TestSecurityQuestionChallengeResponse method testChallengeResponse.

@Test
public void testChallengeResponse() {
    Response response = getUserAdministrator("SecQ");
    String challengeBase64 = assertAndGetChallenge(response);
    String usernameChallenge = null;
    try {
        usernameChallenge = new String(Base64Utility.decode(challengeBase64));
        logger.info("Username challenge: " + usernameChallenge);
    } catch (Base64Exception e) {
        fail("Failed to decode base64 username challenge");
    }
    String secQusernameChallenge = usernameChallenge.replace("username", "administrator");
    logger.info("Username response: " + secQusernameChallenge);
    response = getUserAdministrator("SecQ " + Base64Utility.encode(secQusernameChallenge.getBytes()));
    challengeBase64 = assertAndGetChallenge(response);
    String answerChallenge = null;
    try {
        answerChallenge = new String(Base64Utility.decode(challengeBase64));
        logger.info("Answer challenge: " + answerChallenge);
    } catch (Base64Exception e) {
        fail("Failed to decode base64 username challenge");
    }
    assertEquals("Wrong number of questions", 3, StringUtils.countMatches(answerChallenge, "\"qid\":"));
    String secQAnswerChallenge = "{" + "\"user\" : \"administrator\"," + "\"answer\" : [" + "{ " + "\"qid\" : \"http://midpoint.evolveum.com/xml/ns/public/security/question-2#q001\"," + "\"qans\" : \"5ecr3t\"" + "}," + "{ " + "\"qid\" : \"http://midpoint.evolveum.com/xml/ns/public/security/question-2#q002\"," + "\"qans\" : \"black\"" + "}" + "]" + "}";
    logger.info("Answer response: " + secQAnswerChallenge);
    response = getUserAdministrator("SecQ " + Base64Utility.encode(secQAnswerChallenge.getBytes()));
    assertEquals("Unexpected status code. Expected 200 but got " + response.getStatus(), 200, response.getStatus());
    UserType user = response.readEntity(UserType.class);
    assertNotNull("Returned entity in body must not be null.", user);
    logger.info("Returned entity: {}", user.asPrismObject().debugDump());
}
Also used : Response(javax.ws.rs.core.Response) Base64Exception(org.apache.cxf.common.util.Base64Exception) UserType(com.evolveum.midpoint.xml.ns._public.common.common_3.UserType) Test(org.testng.annotations.Test)

Example 12 with Base64Exception

use of org.apache.cxf.common.util.Base64Exception in project cxf by apache.

the class AbstractHTTPDestination method getAuthorizationPolicyFromMessage.

private AuthorizationPolicy getAuthorizationPolicyFromMessage(String credentials, SecurityContext sc) {
    if (credentials == null || StringUtils.isEmpty(credentials.trim())) {
        return null;
    }
    List<String> creds = StringUtils.getParts(credentials, " ");
    String authType = creds.get(0);
    if ("Basic".equals(authType) && creds.size() == 2) {
        String authEncoded = creds.get(1);
        try {
            byte[] authBytes = Base64Utility.decode(authEncoded);
            if (authBytes == null) {
                throw new Base64Exception(new Throwable("Invalid Base64 data."));
            }
            String authDecoded = decodeBasicAuthWithIso8859 ? new String(authBytes, StandardCharsets.ISO_8859_1) : new String(authBytes);
            int idx = authDecoded.indexOf(':');
            String username = null;
            String password = null;
            if (idx == -1) {
                username = authDecoded;
            } else {
                username = authDecoded.substring(0, idx);
                if (idx < (authDecoded.length() - 1)) {
                    password = authDecoded.substring(idx + 1);
                }
            }
            AuthorizationPolicy policy = sc.getUserPrincipal() == null ? new AuthorizationPolicy() : new PrincipalAuthorizationPolicy(sc);
            policy.setUserName(username);
            policy.setPassword(password);
            policy.setAuthorizationType(authType);
            return policy;
        } catch (Base64Exception ex) {
        // Invalid authentication => treat as not authenticated or use the Principal
        }
    }
    if (sc.getUserPrincipal() != null) {
        AuthorizationPolicy policy = new PrincipalAuthorizationPolicy(sc);
        policy.setAuthorization(credentials);
        policy.setAuthorizationType(authType);
        return policy;
    }
    return null;
}
Also used : AuthorizationPolicy(org.apache.cxf.configuration.security.AuthorizationPolicy) Base64Exception(org.apache.cxf.common.util.Base64Exception)

Example 13 with Base64Exception

use of org.apache.cxf.common.util.Base64Exception in project cxf by apache.

the class AbstractXmlEncInHandler method decryptSymmetricKey.

// TODO: Support symmetric keys if requested
protected byte[] decryptSymmetricKey(String base64EncodedKey, X509Certificate cert, Crypto crypto, String keyEncAlgo, String digestAlgo, Message message) throws WSSecurityException {
    CallbackHandler callback = RSSecurityUtils.getCallbackHandler(message, this.getClass());
    PrivateKey key = null;
    try {
        key = crypto.getPrivateKey(cert, callback);
    } catch (Exception ex) {
        throwFault("Encrypted key can not be decrypted", ex);
    }
    Cipher cipher = EncryptionUtils.initCipherWithKey(keyEncAlgo, digestAlgo, Cipher.DECRYPT_MODE, key);
    try {
        byte[] encryptedBytes = Base64Utility.decode(base64EncodedKey);
        return cipher.doFinal(encryptedBytes);
    } catch (Base64Exception ex) {
        throwFault("Base64 decoding has failed", ex);
    } catch (Exception ex) {
        throwFault("Encrypted key can not be decrypted", ex);
    }
    return null;
}
Also used : CallbackHandler(javax.security.auth.callback.CallbackHandler) PrivateKey(java.security.PrivateKey) Base64Exception(org.apache.cxf.common.util.Base64Exception) XMLCipher(org.apache.xml.security.encryption.XMLCipher) Cipher(javax.crypto.Cipher) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) XMLEncryptionException(org.apache.xml.security.encryption.XMLEncryptionException) Base64Exception(org.apache.cxf.common.util.Base64Exception)

Example 14 with Base64Exception

use of org.apache.cxf.common.util.Base64Exception in project cxf by apache.

the class Saml2BearerAuthHandler method readToken.

protected Element readToken(Message message, String assertion) {
    if (assertion == null) {
        throw ExceptionUtils.toNotAuthorizedException(null, null);
    }
    try {
        byte[] deflatedToken = Base64UrlUtility.decode(assertion);
        InputStream is = new ByteArrayInputStream(deflatedToken);
        return readToken(message, is);
    } catch (Base64Exception ex) {
        throw ExceptionUtils.toNotAuthorizedException(null, null);
    }
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Base64Exception(org.apache.cxf.common.util.Base64Exception)

Example 15 with Base64Exception

use of org.apache.cxf.common.util.Base64Exception in project cxf by apache.

the class AbstractRequestAssertionConsumerHandler method readSAMLResponse.

private org.opensaml.saml.saml2.core.Response readSAMLResponse(boolean postBinding, String samlResponse) {
    if (StringUtils.isEmpty(samlResponse)) {
        reportError("MISSING_SAML_RESPONSE");
        throw ExceptionUtils.toBadRequestException(null, null);
    }
    String samlResponseDecoded = samlResponse;
    /*
        // URL Decoding only applies for the re-direct binding
        if (!postBinding) {
            try {
                samlResponseDecoded = URLDecoder.decode(samlResponse, StandardCharsets.UTF_8);
            } catch (UnsupportedEncodingException e) {
                throw ExceptionUtils.toBadRequestException(null, null);
            }
        }
        */
    InputStream tokenStream = null;
    if (isSupportBase64Encoding()) {
        try {
            byte[] deflatedToken = Base64Utility.decode(samlResponseDecoded);
            tokenStream = !postBinding && isSupportDeflateEncoding() ? new DeflateEncoderDecoder().inflateToken(deflatedToken) : new ByteArrayInputStream(deflatedToken);
        } catch (Base64Exception ex) {
            throw ExceptionUtils.toBadRequestException(ex, null);
        } catch (DataFormatException ex) {
            throw ExceptionUtils.toBadRequestException(ex, null);
        }
    } else {
        tokenStream = new ByteArrayInputStream(samlResponseDecoded.getBytes(StandardCharsets.UTF_8));
    }
    Document responseDoc = null;
    try {
        responseDoc = StaxUtils.read(new InputStreamReader(tokenStream, StandardCharsets.UTF_8));
    } catch (Exception ex) {
        throw new WebApplicationException(400);
    }
    if (LOG.isLoggable(Level.FINE)) {
        LOG.fine("Received response: " + DOM2Writer.nodeToString(responseDoc.getDocumentElement()));
    }
    XMLObject responseObject = null;
    try {
        responseObject = OpenSAMLUtil.fromDom(responseDoc.getDocumentElement());
    } catch (WSSecurityException ex) {
        throw ExceptionUtils.toBadRequestException(ex, null);
    }
    if (!(responseObject instanceof org.opensaml.saml.saml2.core.Response)) {
        throw ExceptionUtils.toBadRequestException(null, null);
    }
    return (org.opensaml.saml.saml2.core.Response) responseObject;
}
Also used : InputStreamReader(java.io.InputStreamReader) WebApplicationException(javax.ws.rs.WebApplicationException) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) XMLObject(org.opensaml.core.xml.XMLObject) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) Document(org.w3c.dom.Document) DeflateEncoderDecoder(org.apache.cxf.rs.security.saml.DeflateEncoderDecoder) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) DataFormatException(java.util.zip.DataFormatException) IOException(java.io.IOException) Base64Exception(org.apache.cxf.common.util.Base64Exception) WebApplicationException(javax.ws.rs.WebApplicationException) Response(javax.ws.rs.core.Response) DataFormatException(java.util.zip.DataFormatException) ByteArrayInputStream(java.io.ByteArrayInputStream) Base64Exception(org.apache.cxf.common.util.Base64Exception)

Aggregations

Base64Exception (org.apache.cxf.common.util.Base64Exception)21 EncryptionException (com.evolveum.midpoint.prism.crypto.EncryptionException)4 ByteArrayInputStream (java.io.ByteArrayInputStream)4 Certificate (java.security.cert.Certificate)4 SimplePrincipal (org.apache.cxf.common.security.SimplePrincipal)4 Message (org.apache.cxf.message.Message)4 SecurityContext (org.apache.cxf.security.SecurityContext)4 IOException (java.io.IOException)3 InputStream (java.io.InputStream)3 CertificateException (java.security.cert.CertificateException)3 X509Certificate (java.security.cert.X509Certificate)3 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)3 InputStreamReader (java.io.InputStreamReader)2 Principal (java.security.Principal)2 PrivateKey (java.security.PrivateKey)2 RSAPublicKey (java.security.interfaces.RSAPublicKey)2 DataFormatException (java.util.zip.DataFormatException)2 Cipher (javax.crypto.Cipher)2 Response (javax.ws.rs.core.Response)2 AuthorizationPolicy (org.apache.cxf.configuration.security.AuthorizationPolicy)2