Example usage for javax.security.sasl Sasl QOP

List of usage examples for javax.security.sasl Sasl QOP

Introduction

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

Prototype

String QOP

To view the source code for javax.security.sasl Sasl QOP.

Click Source Link

Document

The name of a property that specifies the quality-of-protection to use.

Usage

From source file:org.apache.accumulo.core.rpc.SaslConnectionParams.java

protected void updateFromConfiguration(ClientConfiguration conf) {
    // Get the quality of protection to use
    final String qopValue = conf.get(ClientProperty.RPC_SASL_QOP);
    this.qop = QualityOfProtection.get(qopValue);

    // Add in the SASL properties to a map so we don't have to repeatedly construct this map
    this.saslProperties.put(Sasl.QOP, this.qop.getQuality());

    // The primary from the KRB principal on each server (e.g. primary/instance@realm)
    this.kerberosServerPrimary = conf.get(ClientProperty.KERBEROS_SERVER_PRIMARY);
}

From source file:org.apache.directory.studio.connection.core.io.jndi.JNDIConnectionWrapper.java

private void doBind(final StudioProgressMonitor monitor) throws NamingException {
    if (context != null && isConnected) {
        // setup authentication methdod
        authMethod = AUTHMETHOD_NONE;//ww  w.  j  a  v  a2  s .c o  m
        if (connection.getConnectionParameter()
                .getAuthMethod() == ConnectionParameter.AuthenticationMethod.SIMPLE) {
            authMethod = AUTHMETHOD_SIMPLE;
        } else if (connection.getConnectionParameter()
                .getAuthMethod() == ConnectionParameter.AuthenticationMethod.SASL_DIGEST_MD5) {
            authMethod = AUTHMETHOD_DIGEST_MD5;
            saslRealm = connection.getConnectionParameter().getSaslRealm();
        } else if (connection.getConnectionParameter()
                .getAuthMethod() == ConnectionParameter.AuthenticationMethod.SASL_CRAM_MD5) {
            authMethod = AUTHMETHOD_CRAM_MD5;
        } else if (connection.getConnectionParameter()
                .getAuthMethod() == ConnectionParameter.AuthenticationMethod.SASL_GSSAPI) {
            authMethod = AUTHMETHOD_GSSAPI;
        }

        // No Authentication
        if (authMethod == AUTHMETHOD_NONE) {
            bindPrincipal = ""; //$NON-NLS-1$
            bindCredentials = ""; //$NON-NLS-1$
        } else {
            // setup credentials
            IAuthHandler authHandler = ConnectionCorePlugin.getDefault().getAuthHandler();
            if (authHandler == null) {
                NamingException namingException = new NamingException(Messages.model__no_auth_handler);
                monitor.reportError(Messages.model__no_auth_handler, namingException);
                throw namingException;
            }
            ICredentials credentials = authHandler.getCredentials(connection.getConnectionParameter());
            if (credentials == null) {
                CancelException cancelException = new CancelException();
                monitor.setCanceled(true);
                monitor.reportError(Messages.model__no_credentials, cancelException);
                throw cancelException;
            }
            if (credentials.getBindPrincipal() == null || credentials.getBindPassword() == null) {
                NamingException namingException = new NamingException(Messages.model__no_credentials);
                monitor.reportError(Messages.model__no_credentials, namingException);
                throw namingException;
            }
            bindPrincipal = credentials.getBindPrincipal();
            bindCredentials = credentials.getBindPassword();
        }

        InnerRunnable runnable = new InnerRunnable() {
            public void run() {
                try {
                    context.removeFromEnvironment(Context.SECURITY_AUTHENTICATION);
                    context.removeFromEnvironment(Context.SECURITY_PRINCIPAL);
                    context.removeFromEnvironment(Context.SECURITY_CREDENTIALS);
                    context.removeFromEnvironment(JAVA_NAMING_SECURITY_SASL_REALM);

                    context.addToEnvironment(Context.SECURITY_AUTHENTICATION, authMethod);

                    // SASL options
                    if (connection.getConnectionParameter()
                            .getAuthMethod() == AuthenticationMethod.SASL_CRAM_MD5
                            || connection.getConnectionParameter()
                                    .getAuthMethod() == AuthenticationMethod.SASL_DIGEST_MD5
                            || connection.getConnectionParameter()
                                    .getAuthMethod() == AuthenticationMethod.SASL_GSSAPI) {
                        // Request quality of protection
                        switch (connection.getConnectionParameter().getSaslQop()) {
                        case AUTH:
                            context.addToEnvironment(Sasl.QOP, SaslQoP.AUTH.getValue());
                            break;
                        case AUTH_INT:
                            context.addToEnvironment(Sasl.QOP, SaslQoP.AUTH_INT.getValue());
                            break;
                        case AUTH_CONF:
                            context.addToEnvironment(Sasl.QOP, SaslQoP.AUTH_CONF.getValue());
                            break;
                        }

                        // Request mutual authentication
                        if (connection.getConnectionParameter().isSaslMutualAuthentication()) {
                            context.addToEnvironment(Sasl.SERVER_AUTH, "true"); //$NON-NLS-1$
                        } else {
                            context.removeFromEnvironment(Sasl.SERVER_AUTH);
                        }

                        // Request cryptographic protection strength
                        switch (connection.getConnectionParameter().getSaslSecurityStrength()) {
                        case HIGH:
                            context.addToEnvironment(Sasl.STRENGTH, SaslSecurityStrength.HIGH.getValue());
                            break;
                        case MEDIUM:
                            context.addToEnvironment(Sasl.STRENGTH, SaslSecurityStrength.MEDIUM.getValue());
                            break;
                        case LOW:
                            context.addToEnvironment(Sasl.STRENGTH, SaslSecurityStrength.LOW.getValue());
                            break;
                        }
                    }

                    // Bind
                    if (connection.getConnectionParameter()
                            .getAuthMethod() == ConnectionParameter.AuthenticationMethod.SASL_GSSAPI) {
                        // GSSAPI
                        doGssapiBind(this);
                    } else {
                        // no GSSAPI
                        context.addToEnvironment(Context.SECURITY_PRINCIPAL, bindPrincipal);
                        context.addToEnvironment(Context.SECURITY_CREDENTIALS, bindCredentials);

                        if (connection.getConnectionParameter()
                                .getAuthMethod() == ConnectionParameter.AuthenticationMethod.SASL_DIGEST_MD5
                                && StringUtils.isNotEmpty(saslRealm)) {
                            context.addToEnvironment(JAVA_NAMING_SECURITY_SASL_REALM, saslRealm);
                        }

                        context.reconnect(context.getConnectControls());
                    }
                } catch (NamingException ne) {
                    namingException = ne;
                }
            }
        };

        runAndMonitor(runnable, monitor);

        if (runnable.getException() != null) {
            throw runnable.getException();
        } else if (context != null) {
            // all OK
        } else {
            throw new NamingException("???"); //$NON-NLS-1$
        }
    } else {
        throw new NamingException(NO_CONNECTION);
    }
}

From source file:org.apache.hadoop.hbase.io.asyncfs.FanOutOneBlockAsyncDFSOutputSaslHelper.java

private static Map<String, String> createSaslPropertiesForEncryption(String encryptionAlgorithm) {
    Map<String, String> saslProps = Maps.newHashMapWithExpectedSize(3);
    saslProps.put(Sasl.QOP, QualityOfProtection.PRIVACY.getSaslQop());
    saslProps.put(Sasl.SERVER_AUTH, "true");
    saslProps.put("com.sun.security.sasl.digest.cipher", encryptionAlgorithm);
    return saslProps;
}

From source file:org.apache.hadoop.hbase.security.HBaseSaslRpcClient.java

/**
 * Do client side SASL authentication with server via the given InputStream
 * and OutputStream//from  w  w w  .j  av  a 2  s . com
 * 
 * @param inS
 *          InputStream to use
 * @param outS
 *          OutputStream to use
 * @return true if connection is set up, or false if needs to switch 
 *             to simple Auth.
 * @throws IOException
 */
public boolean saslConnect(InputStream inS, OutputStream outS) throws IOException {
    DataInputStream inStream = new DataInputStream(new BufferedInputStream(inS));
    DataOutputStream outStream = new DataOutputStream(new BufferedOutputStream(outS));

    try {
        byte[] saslToken = new byte[0];
        if (saslClient.hasInitialResponse())
            saslToken = saslClient.evaluateChallenge(saslToken);
        if (saslToken != null) {
            outStream.writeInt(saslToken.length);
            outStream.write(saslToken, 0, saslToken.length);
            outStream.flush();
            if (LOG.isDebugEnabled())
                LOG.debug("Have sent token of size " + saslToken.length + " from initSASLContext.");
        }
        if (!saslClient.isComplete()) {
            readStatus(inStream);
            int len = inStream.readInt();
            if (len == SaslUtil.SWITCH_TO_SIMPLE_AUTH) {
                if (!fallbackAllowed) {
                    throw new IOException("Server asks us to fall back to SIMPLE auth, "
                            + "but this client is configured to only allow secure connections.");
                }
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Server asks us to fall back to simple auth.");
                }
                saslClient.dispose();
                return false;
            }
            saslToken = new byte[len];
            if (LOG.isDebugEnabled())
                LOG.debug("Will read input token of size " + saslToken.length
                        + " for processing by initSASLContext");
            inStream.readFully(saslToken);
        }

        while (!saslClient.isComplete()) {
            saslToken = saslClient.evaluateChallenge(saslToken);
            if (saslToken != null) {
                if (LOG.isDebugEnabled())
                    LOG.debug("Will send token of size " + saslToken.length + " from initSASLContext.");
                outStream.writeInt(saslToken.length);
                outStream.write(saslToken, 0, saslToken.length);
                outStream.flush();
            }
            if (!saslClient.isComplete()) {
                readStatus(inStream);
                saslToken = new byte[inStream.readInt()];
                if (LOG.isDebugEnabled())
                    LOG.debug("Will read input token of size " + saslToken.length
                            + " for processing by initSASLContext");
                inStream.readFully(saslToken);
            }
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("SASL client context established. Negotiated QoP: "
                    + saslClient.getNegotiatedProperty(Sasl.QOP));
        }
        return true;
    } catch (IOException e) {
        try {
            saslClient.dispose();
        } catch (SaslException ignored) {
            // ignore further exceptions during cleanup
        }
        throw e;
    }
}

From source file:org.apache.hadoop.hbase.security.NettyHBaseSaslRpcClient.java

public void setupSaslHandler(ChannelPipeline p) {
    String qop = (String) saslClient.getNegotiatedProperty(Sasl.QOP);
    if (LOG.isDebugEnabled()) {
        LOG.debug("SASL client context established. Negotiated QoP: " + qop);
    }// ww w.  ja v  a 2  s.  c o m
    if (qop == null || "auth".equalsIgnoreCase(qop)) {
        return;
    }
    // add wrap and unwrap handlers to pipeline.
    p.addFirst(new SaslWrapHandler(saslClient), new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4),
            new SaslUnwrapHandler(saslClient));
}

From source file:org.apache.hadoop.hbase.security.SaslClientHandler.java

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf in = (ByteBuf) msg;/*w w w  . ja v  a  2s . co m*/

    // If not complete, try to negotiate
    if (!saslClient.isComplete()) {
        while (!saslClient.isComplete() && in.isReadable()) {
            readStatus(in);
            int len = in.readInt();
            if (firstRead) {
                firstRead = false;
                if (len == SaslUtil.SWITCH_TO_SIMPLE_AUTH) {
                    if (!fallbackAllowed) {
                        throw new IOException("Server asks us to fall back to SIMPLE auth, " + "but this "
                                + "client is configured to only allow secure connections.");
                    }
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Server asks us to fall back to simple auth.");
                    }
                    saslClient.dispose();

                    ctx.pipeline().remove(this);
                    successfulConnectHandler.onSuccess(ctx.channel());
                    return;
                }
            }
            saslToken = new byte[len];
            if (LOG.isDebugEnabled()) {
                LOG.debug("Will read input token of size " + saslToken.length
                        + " for processing by initSASLContext");
            }
            in.readBytes(saslToken);

            saslToken = evaluateChallenge(saslToken);
            if (saslToken != null) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Will send token of size " + saslToken.length + " from initSASLContext.");
                }
                writeSaslToken(ctx, saslToken);
            }
        }

        if (saslClient.isComplete()) {
            String qop = (String) saslClient.getNegotiatedProperty(Sasl.QOP);

            if (LOG.isDebugEnabled()) {
                LOG.debug("SASL client context established. Negotiated QoP: " + qop);
            }

            boolean useWrap = qop != null && !"auth".equalsIgnoreCase(qop);

            if (!useWrap) {
                ctx.pipeline().remove(this);
            }
            successfulConnectHandler.onSuccess(ctx.channel());
        }
    }
    // Normal wrapped reading
    else {
        try {
            int length = in.readInt();
            if (LOG.isDebugEnabled()) {
                LOG.debug("Actual length is " + length);
            }
            saslToken = new byte[length];
            in.readBytes(saslToken);
        } catch (IndexOutOfBoundsException e) {
            return;
        }
        try {
            ByteBuf b = ctx.channel().alloc().buffer(saslToken.length);

            b.writeBytes(saslClient.unwrap(saslToken, 0, saslToken.length));
            ctx.fireChannelRead(b);

        } catch (SaslException se) {
            try {
                saslClient.dispose();
            } catch (SaslException ignored) {
                LOG.debug("Ignoring SASL exception", ignored);
            }
            throw se;
        }
    }
}

From source file:org.apache.hadoop.hbase.security.SaslUtil.java

static void initSaslProperties(String rpcProtection) {
    QualityOfProtection saslQOP = QualityOfProtection.AUTHENTICATION;
    if (QualityOfProtection.INTEGRITY.name().toLowerCase().equals(rpcProtection)) {
        saslQOP = QualityOfProtection.INTEGRITY;
    } else if (QualityOfProtection.PRIVACY.name().toLowerCase().equals(rpcProtection)) {
        saslQOP = QualityOfProtection.PRIVACY;
    }/*from  w ww.j av a  2  s.  co  m*/

    SaslUtil.SASL_PROPS.put(Sasl.QOP, saslQOP.getSaslQop());
    SaslUtil.SASL_PROPS.put(Sasl.SERVER_AUTH, "true");
}

From source file:org.apache.hadoop.hdfs.protocol.datatransfer.sasl.DataTransferSaslUtil.java

/**
 * Checks that SASL negotiation has completed for the given participant, and
 * the negotiated quality of protection is included in the given SASL
 * properties and therefore acceptable./*from www .j av a 2  s  . c o m*/
 *
 * @param sasl participant to check
 * @param saslProps properties of SASL negotiation
 * @throws IOException for any error
 */
public static void checkSaslComplete(SaslParticipant sasl, Map<String, String> saslProps) throws IOException {
    if (!sasl.isComplete()) {
        throw new IOException("Failed to complete SASL handshake");
    }
    Set<String> requestedQop = ImmutableSet.copyOf(Arrays.asList(saslProps.get(Sasl.QOP).split(",")));
    String negotiatedQop = sasl.getNegotiatedQop();
    LOG.debug("Verifying QOP, requested QOP = {}, negotiated QOP = {}", requestedQop, negotiatedQop);
    if (!requestedQop.contains(negotiatedQop)) {
        throw new IOException(String.format(
                "SASL handshake completed, but " + "channel does not have acceptable quality of protection, "
                        + "requested = %s, negotiated = %s",
                requestedQop, negotiatedQop));
    }
}

From source file:org.apache.hadoop.hdfs.protocol.datatransfer.sasl.DataTransferSaslUtil.java

/**
 * Check whether requested SASL Qop contains privacy.
 * // w w w.j av a2 s.  co  m
 * @param saslProps properties of SASL negotiation
 * @return boolean true if privacy exists
 */
public static boolean requestedQopContainsPrivacy(Map<String, String> saslProps) {
    Set<String> requestedQop = ImmutableSet.copyOf(Arrays.asList(saslProps.get(Sasl.QOP).split(",")));
    return requestedQop.contains("auth-conf");
}

From source file:org.apache.hadoop.hdfs.protocol.datatransfer.sasl.DataTransferSaslUtil.java

/**
 * Creates SASL properties required for an encrypted SASL negotiation.
 *
 * @param encryptionAlgorithm to use for SASL negotation
 * @return properties of encrypted SASL negotiation
 *///from  ww w  .  j  a  v  a2s  .c om
public static Map<String, String> createSaslPropertiesForEncryption(String encryptionAlgorithm) {
    Map<String, String> saslProps = Maps.newHashMapWithExpectedSize(3);
    saslProps.put(Sasl.QOP, QualityOfProtection.PRIVACY.getSaslQop());
    saslProps.put(Sasl.SERVER_AUTH, "true");
    saslProps.put("com.sun.security.sasl.digest.cipher", encryptionAlgorithm);
    return saslProps;
}