Example usage for javax.security.sasl SaslException SaslException

List of usage examples for javax.security.sasl SaslException SaslException

Introduction

In this page you can find the example usage for javax.security.sasl SaslException SaslException.

Prototype

public SaslException(String detail) 

Source Link

Document

Constructs a new instance of SaslException with a detailed message.

Usage

From source file:com.delphix.session.impl.sasl.AnonymousSasl.java

public static void validate(String name) throws SaslException {
    if (name == null) {
        throw new SaslException("email or token required");
    }/*ww w . j  a  v  a 2s.  com*/

    EmailValidator validator = EmailValidator.getInstance();

    if (!validator.isValid(name)) {
        int length = name.length();

        if (length < MIN_TOKEN_LENGTH || length > MAX_TOKEN_LENGTH) {
            throw new SaslException("token length limit exceeded");
        } else if (name.contains(ILLEGAL_TOKEN_CHARS)) {
            throw new SaslException("token contains illegal characters");
        }
    }
}

From source file:com.delphix.session.impl.sasl.AnonymousSasl.java

public static void validate(byte[] message) throws SaslException {
    if (message == null) {
        throw new SaslException("sasl message expected");
    }/*ww  w .  ja  va2s. co m*/

    if (message.length > MAX_TOTAL_OCTETS) {
        throw new SaslException("sasl message length exceeded");
    }

    if (message.length < MIN_TOTAL_OCTETS) {
        throw new SaslException("invalid sasl message");
    }
}

From source file:com.delphix.session.impl.sasl.PlainSaslServer.java

@Override
protected byte[] evaluate(byte[] message) throws SaslException {
    // Parse the SASL message
    String[] userInfo = parse(message);

    // Perform authentication
    String prompt = getMechanismName() + " authentication ID: ";
    NameCallback nc = new NameCallback(prompt, userInfo[1]);
    AuthenticateCallback ac = new AuthenticateCallback(userInfo[2]);

    invokeCallbacks(nc, ac);/*from www . j a v  a2  s.  c o  m*/

    if (!ac.isAuthenticated()) {
        throw new SaslException("sasl authentication failed");
    }

    // Perform authorization
    AuthorizeCallback az = new AuthorizeCallback(userInfo[1], userInfo[0]);

    invokeCallbacks(az);

    if (az.isAuthorized()) {
        authorizationId = az.getAuthorizedID();
    } else {
        throw new SaslException();
    }

    // Mark the SASL server completed
    setComplete();

    return null;
}

From source file:de.tbosch.tools.googleapps.oauth2.OAuth2SaslClient.java

@Override
public byte[] evaluateChallenge(byte[] challenge) throws SaslException {
    if (isComplete) {
        // Empty final response from server, just ignore it.
        return new byte[] {};
    }/*w w  w  . ja  va  2 s .  c  o m*/

    NameCallback nameCallback = new NameCallback("Enter name");
    Callback[] callbacks = new Callback[] { nameCallback };
    try {
        callbackHandler.handle(callbacks);
    } catch (UnsupportedCallbackException e) {
        throw new SaslException("Unsupported callback: " + e);
    } catch (IOException e) {
        throw new SaslException("Failed to execute callback: " + e);
    }
    String email = nameCallback.getName();

    byte[] response = String.format("user=%s\1auth=Bearer %s\1\1", email, oauthToken).getBytes();
    isComplete = true;
    return response;
}

From source file:com.delphix.session.impl.sasl.PlainSaslServer.java

public String[] parse(byte[] message) throws SaslException {
    // Validate the SASL message
    PlainSasl.validate(message);/*  w w w .  j a va  2s .co  m*/

    // Append separator to the end of the message
    message = ArrayUtils.add(message, PlainSasl.SEPARATOR_BYTE);

    // Parse the user info formatted as value + SEPARATOR
    String[] userInfo = new String[3];

    byte[] segment;
    int beginIndex = 0;
    int endIndex;

    for (int i = 0; i < userInfo.length; i++) {
        endIndex = ArrayUtils.indexOf(message, PlainSasl.SEPARATOR_BYTE, beginIndex);

        if (endIndex < 0) {
            throw new SaslException("invalid sasl message");
        } else {
            segment = ArrayUtils.subarray(message, beginIndex, endIndex);
            userInfo[i] = fromUTF(segment);
        }

        beginIndex = endIndex + 1;
    }

    // Check if there is anything else beyond the last separator
    if (beginIndex < message.length) {
        throw new SaslException("invalid sasl message");
    }

    // Validate the user info
    PlainSasl.validate(userInfo);

    return userInfo;
}

From source file:StringUtilities.java

/**
 * Parses digest-challenge string, extracting each token and value(s). Each token
 * is a directive.//  ww  w.  j  a  va 2 s . c om
 *
 * @param buf A non-null digest-challenge string.
 * @throws UnsupportedEncodingException 
 * @throws SaslException if the String cannot be parsed according to RFC 2831
 */
public static HashMap<String, String> parseDirectives(byte[] buf) throws SaslException {
    HashMap<String, String> map = new HashMap<String, String>();
    boolean gettingKey = true;
    boolean gettingQuotedValue = false;
    boolean expectSeparator = false;
    byte bch;

    ByteArrayOutputStream key = new ByteArrayOutputStream(10);
    ByteArrayOutputStream value = new ByteArrayOutputStream(10);

    int i = skipLws(buf, 0);
    while (i < buf.length) {
        bch = buf[i];

        if (gettingKey) {
            if (bch == ',') {
                if (key.size() != 0) {
                    throw new SaslException("Directive key contains a ',':" + key);
                }

                // Empty element, skip separator and lws
                i = skipLws(buf, i + 1);
            } else if (bch == '=') {
                if (key.size() == 0) {
                    throw new SaslException("Empty directive key");
                }

                gettingKey = false; // Termination of key
                i = skipLws(buf, i + 1); // Skip to next non whitespace

                // Check whether value is quoted
                if (i < buf.length) {
                    if (buf[i] == '"') {
                        gettingQuotedValue = true;
                        ++i; // Skip quote
                    }
                } else {
                    throw new SaslException("Valueless directive found: " + key.toString());
                }
            } else if (isLws(bch)) {
                // LWS that occurs after key
                i = skipLws(buf, i + 1);

                // Expecting '='
                if (i < buf.length) {
                    if (buf[i] != '=') {
                        throw new SaslException("'=' expected after key: " + key.toString());
                    }
                } else {
                    throw new SaslException("'=' expected after key: " + key.toString());
                }
            } else {
                key.write(bch); // Append to key
                ++i; // Advance
            }
        } else if (gettingQuotedValue) {
            // Getting a quoted value
            if (bch == '\\') {
                // quoted-pair = "\" CHAR ==> CHAR
                ++i; // Skip escape
                if (i < buf.length) {
                    value.write(buf[i]);
                    ++i; // Advance
                } else {
                    // Trailing escape in a quoted value
                    throw new SaslException("Unmatched quote found for directive: " + key.toString()
                            + " with value: " + value.toString());
                }
            } else if (bch == '"') {
                // closing quote
                ++i; // Skip closing quote
                gettingQuotedValue = false;
                expectSeparator = true;
            } else {
                value.write(bch);
                ++i; // Advance
            }
        } else if (isLws(bch) || bch == ',') {
            // Value terminated
            extractDirective(map, key.toString(), value.toString());
            key.reset();
            value.reset();
            gettingKey = true;
            gettingQuotedValue = expectSeparator = false;
            i = skipLws(buf, i + 1); // Skip separator and LWS
        } else if (expectSeparator) {
            throw new SaslException(
                    "Expecting comma or linear whitespace after quoted string: \"" + value.toString() + "\"");
        } else {
            value.write(bch); // Unquoted value
            ++i; // Advance
        }
    }

    if (gettingQuotedValue) {
        throw new SaslException(
                "Unmatched quote found for directive: " + key.toString() + " with value: " + value.toString());
    }

    // Get last pair
    if (key.size() > 0) {
        extractDirective(map, key.toString(), value.toString());
    }

    return map;
}

From source file:StringUtilities.java

/**
 * Processes directive/value pairs from the digest-challenge and
 * fill out the provided map./*from   w w w.jav  a 2  s . co m*/
 * 
 * @param key A non-null String challenge token name.
 * @param value A non-null String token value.
 * @throws SaslException if either the key or the value is null or
 * if the key already has a value. 
 */
private static void extractDirective(HashMap<String, String> map, String key, String value)
        throws SaslException {
    if (map.get(key) != null) {
        throw new SaslException("Peer sent more than one " + key + " directive");
    }

    map.put(key, value);
}

From source file:com.zimbra.cs.mailclient.smtp.SmtpConnection.java

@Override
protected void sendAuthenticate(boolean ir) throws IOException {
    Reply reply;//from  w w w.  java2  s  . c  om
    if (authenticator.hasInitialResponse()) {
        reply = sendCommand(AUTH, authenticator.getMechanism() + ' '
                + Ascii.toString(Base64.encodeBase64(authenticator.getInitialResponse())));
    } else {
        reply = sendCommand(AUTH, authenticator.getMechanism());
    }

    while (true) {
        switch (reply.code) {
        case 235: // success
            if (authenticator.isComplete()) {
                return;
            } else {
                throw new SaslException("SASL client auth not complete yet S: " + reply.toString());
            }
        case 334: // continue
            byte[] challenge = Strings.isNullOrEmpty(reply.text) ? new byte[0]
                    : Base64.decodeBase64(reply.text);
            byte[] response = authenticator.evaluateChallenge(challenge);
            if (response != null) {
                reply = sendCommand(Ascii.toString(Base64.encodeBase64(response)), null);
            } else {
                reply = sendCommand("", null);
            }
            continue;
        default:
            throw new CommandFailedException(AUTH, reply.toString());
        }
    }
}

From source file:org.wso2.andes.server.security.auth.manager.PrincipalDatabaseAuthenticationManagerTest.java

/**
 * Test SASL implementation used to test the authenticate() method.
 *//*  w  w  w.  j  a  va  2  s .c o  m*/
private SaslServer createTestSaslServer(final boolean complete, final boolean throwSaslException) {
    return new SaslServer() {
        public String getMechanismName() {
            return null;
        }

        public byte[] evaluateResponse(byte[] response) throws SaslException {
            if (throwSaslException) {
                throw new SaslException("Mocked exception");
            }
            return null;
        }

        public boolean isComplete() {
            return complete;
        }

        public String getAuthorizationID() {
            return complete ? "guest" : null;
        }

        public byte[] unwrap(byte[] incoming, int offset, int len) throws SaslException {
            return null;
        }

        public byte[] wrap(byte[] outgoing, int offset, int len) throws SaslException {
            return null;
        }

        public Object getNegotiatedProperty(String propName) {
            return null;
        }

        public void dispose() throws SaslException {
        }
    };
}