javax.security.sasl.SaslServer Java Examples

The following examples show how to use javax.security.sasl.SaslServer. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SaslRpcServer.java    From big-c with Apache License 2.0 6 votes vote down vote up
@Override
public SaslServer createSaslServer(String mechanism, String protocol,
    String serverName, Map<String,?> props, CallbackHandler cbh)
    throws SaslException {
  SaslServer saslServer = null;
  List<SaslServerFactory> factories = factoryCache.get(mechanism);
  if (factories != null) {
    for (SaslServerFactory factory : factories) {
      saslServer = factory.createSaslServer(
          mechanism, protocol, serverName, props, cbh);
      if (saslServer != null) {
        break;
      }
    }
  }
  return saslServer;
}
 
Example #2
Source File: AuthManager.java    From ballerina-message-broker with Apache License 2.0 6 votes vote down vote up
/**
 * Create sasl server for given mechanism.
 *
 * @param hostName  Hostname of the server
 * @param mechanism Sasl mechanism
 * @return Sasl server created for mechanism
 * @throws SaslException Throws if server does not support for given mechanism
 */
public SaslServer createSaslServer(String hostName, String mechanism) throws SaslException {
    SaslServerBuilder saslServerBuilder = saslMechanisms.get(mechanism);
    if (saslServerBuilder != null) {
        SaslServer saslServer = Sasl.createSaslServer(mechanism, AMQP_PROTOCOL_IDENTIFIER,
                                                      hostName,
                                                      saslServerBuilder.getProperties(),
                                                      saslServerBuilder.getCallbackHandler());
        if (saslServer != null) {
            return saslServer;
        } else {
            throw new SaslException("Sasl server cannot be found for mechanism: " + mechanism);
        }
    } else {
        throw new SaslException("Server does not support for mechanism: " + mechanism);
    }
}
 
Example #3
Source File: SaslAuthenticationStrategy.java    From ballerina-message-broker with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(int channel, ChannelHandlerContext ctx, AmqpConnectionHandler connectionHandler,
                   ShortString mechanism, LongString response) throws BrokerException {
    try {
        SaslServer saslServer = authManager
                .createSaslServer(hostName, mechanism.toString());
        byte[] challenge = saslServer.evaluateResponse(response.getBytes());
        if (saslServer.isComplete()) {
            Subject subject = UsernamePrincipal.createSubject(saslServer.getAuthorizationID());
            connectionHandler.attachBroker(brokerFactory.getBroker(subject));
            ctx.writeAndFlush(new ConnectionTune(256, 65535, 0));
        } else {
            ctx.channel().attr(AttributeKey.valueOf(SASL_SERVER_ATTRIBUTE)).set(saslServer);
            ctx.writeAndFlush(new ConnectionSecure(channel, LongString.parse(challenge)));
        }
    } catch (SaslException e) {
        throw new BrokerException("Exception occurred while handling authentication with Sasl", e);
    }
}
 
Example #4
Source File: ClientServerTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
private void processConnection(SaslEndpoint endpoint)
        throws SaslException, IOException, ClassNotFoundException {
    System.out.println("process connection");
    endpoint.send(SUPPORT_MECHS);
    Object o = endpoint.receive();
    if (!(o instanceof String)) {
        throw new RuntimeException("Received unexpected object: " + o);
    }
    String mech = (String) o;
    SaslServer saslServer = createSaslServer(mech);
    Message msg = getMessage(endpoint.receive());
    while (!saslServer.isComplete()) {
        byte[] data = processData(msg.getData(), endpoint,
                saslServer);
        if (saslServer.isComplete()) {
            System.out.println("server is complete");
            endpoint.send(new Message(SaslStatus.SUCCESS, data));
        } else {
            System.out.println("server continues");
            endpoint.send(new Message(SaslStatus.CONTINUE, data));
            msg = getMessage(endpoint.receive());
        }
    }
}
 
Example #5
Source File: TSaslServerTransport.java    From incubator-retired-blur with Apache License 2.0 6 votes vote down vote up
/**
 * Performs the server side of the initial portion of the Thrift SASL protocol.
 * Receives the initial response from the client, creates a SASL server using
 * the mechanism requested by the client (if this server supports it), and
 * sends the first challenge back to the client.
 */
@Override
protected void handleSaslStartMessage() throws TTransportException, SaslException {
  SaslResponse message = receiveSaslMessage();

  LOGGER.debug("Received start message with status {}", message.status);
  if (message.status != NegotiationStatus.START) {
    sendAndThrowMessage(NegotiationStatus.ERROR, "Expecting START status, received " + message.status);
  }

  // Get the mechanism name.
  String mechanismName = new String(message.payload);
  TSaslServerDefinition serverDefinition = serverDefinitionMap.get(mechanismName);
  LOGGER.debug("Received mechanism name '{}'", mechanismName);

  if (serverDefinition == null) {
    sendAndThrowMessage(NegotiationStatus.BAD, "Unsupported mechanism type " + mechanismName);
  }
  SaslServer saslServer = Sasl.createSaslServer(serverDefinition.mechanism,
      serverDefinition.protocol, serverDefinition.serverName, serverDefinition.props,
      serverDefinition.cbh);
  setSaslServer(saslServer);
}
 
Example #6
Source File: ClientServerTest.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
private void processConnection(SaslEndpoint endpoint)
        throws SaslException, IOException, ClassNotFoundException {
    System.out.println("process connection");
    endpoint.send(SUPPORT_MECHS);
    Object o = endpoint.receive();
    if (!(o instanceof String)) {
        throw new RuntimeException("Received unexpected object: " + o);
    }
    String mech = (String) o;
    SaslServer saslServer = createSaslServer(mech);
    Message msg = getMessage(endpoint.receive());
    while (!saslServer.isComplete()) {
        byte[] data = processData(msg.getData(), endpoint,
                saslServer);
        if (saslServer.isComplete()) {
            System.out.println("server is complete");
            endpoint.send(new Message(SaslStatus.SUCCESS, data));
        } else {
            System.out.println("server continues");
            endpoint.send(new Message(SaslStatus.CONTINUE, data));
            msg = getMessage(endpoint.receive());
        }
    }
}
 
Example #7
Source File: SaslTransportPlugin.java    From jstorm with Apache License 2.0 6 votes vote down vote up
public boolean process(final TProtocol inProt, final TProtocol outProt) throws TException {
    // populating request context
    ReqContext req_context = ReqContext.context();

    TTransport trans = inProt.getTransport();
    // Sasl transport
    TSaslServerTransport saslTrans = (TSaslServerTransport) trans;
    // remote address
    TSocket tsocket = (TSocket) saslTrans.getUnderlyingTransport();
    Socket socket = tsocket.getSocket();
    req_context.setRemoteAddress(socket.getInetAddress());

    // remote subject
    SaslServer saslServer = saslTrans.getSaslServer();
    String authId = saslServer.getAuthorizationID();
    Subject remoteUser = new Subject();
    remoteUser.getPrincipals().add(new User(authId));
    req_context.setSubject(remoteUser);

    // invoke service handler
    return wrapped.process(inProt, outProt);
}
 
Example #8
Source File: AbstractSaslServerNegotiator.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
@Override
public void dispose()
{
    SaslServer saslServer = getSaslServer();
    if (saslServer != null)
    {
        try
        {
            saslServer.dispose();
        }
        catch (SaslException e)
        {
            LOGGER.warn("Disposing of SaslServer failed", e);
        }
    }
}
 
Example #9
Source File: AbstractCramMd5Negotiator.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
AbstractCramMd5Negotiator(final PasswordCredentialManagingAuthenticationProvider<?> authenticationProvider,
                          String localFQDN,
                          final PasswordSource passwordSource,
                          final PasswordTransformer passwordTransformer)
{
    _authenticationProvider = authenticationProvider;
    SaslServer saslServer = null;
    SaslException exception = null;
    try
    {
        saslServer = Sasl.createSaslServer("CRAM-MD5",
                                           "AMQP",
                                           localFQDN,
                                           null,
                                           new ServerCallbackHandler(passwordSource, passwordTransformer));
    }
    catch (SaslException e)
    {
        exception = e;
        LOGGER.warn("Creation of SASL server for mechanism '{}' failed.", "CRAM-MD5", e);
    }
    _saslServer = saslServer;
    _exception = exception;
}
 
Example #10
Source File: SaslTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void testSaslAuthenticationScram() throws Exception {
    init();
    ServiceName serviceName = Capabilities.SASL_AUTHENTICATION_FACTORY_RUNTIME_CAPABILITY.getCapabilityServiceName("MySaslAuth");
    SaslAuthenticationFactory authFactory = (SaslAuthenticationFactory) services.getContainer().getService(serviceName).getValue();

    SaslServer server = authFactory.createMechanism(SaslMechanismInformation.Names.SCRAM_SHA_1);
    SaslClient client = Sasl.createSaslClient(new String[]{SaslMechanismInformation.Names.SCRAM_SHA_1},
            "firstUser", "protocol", "TestServer", Collections.<String, Object>emptyMap(), clientCallbackHandler("firstUser", "ScramRealm", "clearPassword"));

    testSaslServerClient(server, client);
}
 
Example #11
Source File: SaslTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void testSaslServerDigest() throws Exception {
    init();
    ServiceName serviceNameServer = Capabilities.SASL_SERVER_FACTORY_RUNTIME_CAPABILITY.getCapabilityServiceName("MySaslServer");
    SaslServerFactory serverFactory = (SaslServerFactory) services.getContainer().getService(serviceNameServer).getValue();

    Map<String, Object> serverClientProps = new HashMap<String, Object>();
    serverClientProps.put("javax.security.sasl.qop", "auth-conf");
    SaslServer server = serverFactory.createSaslServer(SaslMechanismInformation.Names.DIGEST_MD5,
            "protocol", "TestingRealm1", serverClientProps, serverCallbackHandler("user1", "TestingRealm1", "password1"));
    SaslClient client = Sasl.createSaslClient(new String[]{SaslMechanismInformation.Names.DIGEST_MD5},
            "user1", "protocol", "TestingRealm1", serverClientProps, clientCallbackHandler("user1", "TestingRealm1", "password1"));

    testSaslServerClient(server, client);
}
 
Example #12
Source File: ClientServerTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private byte[] processData(byte[] data, SaslEndpoint endpoint,
        SaslServer server) throws SaslException, IOException {
    try {
        return server.evaluateResponse(data);
    } catch (SaslException e) {
        endpoint.send(new Message(SaslStatus.FAILURE, null));
        System.out.println("Error while processing data");
        throw e;
    }
}
 
Example #13
Source File: ClientServerTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private SaslServer createSaslServer(String mechanism)
        throws SaslException {
    Map<String, String> props = new HashMap<>();
    props.put(Sasl.QOP, qop);
    return Sasl.createSaslServer(mechanism, PROTOCOL, host, props,
            callback);
}
 
Example #14
Source File: FastSaslServerFactory.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override
public SaslServer createSaslServer(String mechanism, String protocol, String serverName, Map<String, ?> props,
                                   CallbackHandler cbh) throws SaslException {
  final List<SaslServerFactory> factories = serverFactories.get(mechanism);
  if (factories != null) {
    for (final SaslServerFactory factory : factories) {
      final SaslServer saslServer = factory.createSaslServer(mechanism, protocol, serverName, props, cbh);
      if (saslServer != null) {
        return saslServer;
      }
    }
  }
  return null;
}
 
Example #15
Source File: ClientServerTest.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private byte[] processData(byte[] data, SaslEndpoint endpoint,
        SaslServer server) throws SaslException, IOException {
    try {
        return server.evaluateResponse(data);
    } catch (SaslException e) {
        endpoint.send(new Message(SaslStatus.FAILURE, null));
        System.out.println("Error while processing data");
        throw e;
    }
}
 
Example #16
Source File: ClientServerTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private SaslServer createSaslServer(String mechanism)
        throws SaslException {
    Map<String, String> props = new HashMap<>();
    props.put(Sasl.QOP, qop);
    return Sasl.createSaslServer(mechanism, PROTOCOL, host, props,
            callback);
}
 
Example #17
Source File: DisabledMechanisms.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        String authorizationId = "username";
        String protocol = "ldap";
        String serverName = "server1";
        Map props = Collections.emptyMap();

        String disabled = System.getProperty("disabledMechanisms");
        if (disabled != null) {
            Security.setProperty("jdk.sasl.disabledMechanisms", disabled);
        }

        CallbackHandler callbackHandler = callbacks -> {
            for (Callback cb : callbacks) {
                if (cb instanceof PasswordCallback) {
                    ((PasswordCallback) cb).setPassword("password".toCharArray());
                }
            }
        };

        SaslClient client = Sasl.createSaslClient(
                new String[]{"DIGEST-MD5", "NTLM"}, authorizationId,
                protocol, serverName, props, callbackHandler);
        Asserts.assertEQ(client == null ? null : client.getMechanismName(),
                args[0].equals("null") ? null : args[0]);

        SaslServer server = Sasl.createSaslServer(
                "DIGEST-MD5", protocol, serverName, props, callbackHandler);
        Asserts.assertEQ(server == null ? null : server.getMechanismName(),
                args[1].equals("null") ? null : args[1]);
    }
 
Example #18
Source File: GSSAPIServerSASL.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] processSASL(byte[] bytes) {
   try {
      if (jaasId == null) {
         // populate subject with acceptor private credentials
         LoginContext loginContext = new LoginContext(loginConfigScope);
         loginContext.login();
         jaasId = loginContext.getSubject();
      }

      if (saslServer == null) {
         saslServer = Subject.doAs(jaasId, (PrivilegedExceptionAction<SaslServer>) () -> Sasl.createSaslServer(NAME, null, null, new HashMap<String, String>(), new CallbackHandler() {
            @Override
            public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
               for (Callback callback : callbacks) {
                  if (callback instanceof AuthorizeCallback) {
                     AuthorizeCallback authorizeCallback = (AuthorizeCallback) callback;
                     // only ok to authenticate as self
                     authorizeCallback.setAuthorized(authorizeCallback.getAuthenticationID().equals(authorizeCallback.getAuthorizationID()));
                  }
               }
            }
         }));
      }

      byte[] challenge = Subject.doAs(jaasId, (PrivilegedExceptionAction<byte[]>) () -> saslServer.evaluateResponse(bytes));
      if (saslServer.isComplete()) {
         result = new PrincipalSASLResult(true, new KerberosPrincipal(saslServer.getAuthorizationID()));
      }
      return challenge;

   } catch (Exception outOfHere) {
      log.info("Error on sasl input: " + outOfHere.toString(), outOfHere);
      result = new PrincipalSASLResult(false, null);
   }
   return null;
}
 
Example #19
Source File: DigestSaslServerAuthenticationProvider.java    From hbase with Apache License 2.0 5 votes vote down vote up
@Override
public AttemptingUserProvidingSaslServer createServer(
    SecretManager<TokenIdentifier> secretManager,
    Map<String, String> saslProps) throws IOException {
  if (secretManager == null) {
    throw new AccessDeniedException("Server is not configured to do DIGEST authentication.");
  }
  final SaslServer server = Sasl.createSaslServer(getSaslAuthMethod().getSaslMechanism(), null,
    SaslUtil.SASL_DEFAULT_REALM, saslProps,
    new SaslDigestCallbackHandler(secretManager, attemptingUser));

  return new AttemptingUserProvidingSaslServer(server, () -> attemptingUser.get());
}
 
Example #20
Source File: PlainSaslServerFactory.java    From ballerina-message-broker with Apache License 2.0 5 votes vote down vote up
@Override
public SaslServer createSaslServer(String mechanism, String protocol, String serverName, Map<String, ?> props,
        CallbackHandler cbh) throws SaslException {
    Authenticator authenticator = (Authenticator) props.get(BrokerAuthConstants.PROPERTY_AUTHENTICATOR_INSTANCE);
    return (PlainSaslServer.PLAIN_MECHANISM.equals(mechanism)) ?
            new PlainSaslServer(authenticator) :
            null;
}
 
Example #21
Source File: SaslAuthenticationStrategy.java    From ballerina-message-broker with Apache License 2.0 5 votes vote down vote up
private byte[] evaluateResponse(LongString response, SaslServer saslServer) throws BrokerException {
    try {
        return saslServer.evaluateResponse(response.getBytes());
    } catch (SaslException e) {
        throw new BrokerException("Exception occurred while handling authentication with Sasl", e);
    }
}
 
Example #22
Source File: ClientServerTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private SaslServer createSaslServer(String mechanism)
        throws SaslException {
    Map<String, String> props = new HashMap<>();
    props.put(Sasl.QOP, qop);
    return Sasl.createSaslServer(mechanism, PROTOCOL, host, props,
            callback);
}
 
Example #23
Source File: ClientServerTest.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
private byte[] processData(byte[] data, SaslEndpoint endpoint,
        SaslServer server) throws SaslException, IOException {
    try {
        return server.evaluateResponse(data);
    } catch (SaslException e) {
        endpoint.send(new Message(SaslStatus.FAILURE, null));
        System.out.println("Error while processing data");
        throw e;
    }
}
 
Example #24
Source File: SaslTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void testSaslServerClient(SaslServer server, SaslClient client) throws SaslException {
    byte[] message = new byte[]{};
    if (client.hasInitialResponse()) message = client.evaluateChallenge(message);
    while(!server.isComplete() || !client.isComplete()) {
        if (!server.isComplete()) message = server.evaluateResponse(message);
        if (!client.isComplete()) message = client.evaluateChallenge(message);
    }
}
 
Example #25
Source File: SaslOutputStream.java    From hadoop with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs a SASLOutputStream from an OutputStream and a SaslServer <br>
 * Note: if the specified OutputStream or SaslServer is null, a
 * NullPointerException may be thrown later when they are used.
 * 
 * @param outStream
 *          the OutputStream to be processed
 * @param saslServer
 *          an initialized SaslServer object
 */
public SaslOutputStream(OutputStream outStream, SaslServer saslServer) {
  this.saslServer = saslServer;
  this.saslClient = null;
  String qop = (String) saslServer.getNegotiatedProperty(Sasl.QOP);
  this.useWrap = qop != null && !"auth".equalsIgnoreCase(qop);
  if (useWrap) {
    this.outStream = new BufferedOutputStream(outStream, 64*1024);
  } else {
    this.outStream = outStream;
  }
}
 
Example #26
Source File: SaslUtil.java    From hbase with Apache License 2.0 5 votes vote down vote up
static void safeDispose(SaslServer saslServer) {
  try {
    saslServer.dispose();
  } catch (SaslException e) {
    LOG.error("Error disposing of SASL server", e);
  }
}
 
Example #27
Source File: ClientServerTest.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private byte[] processData(byte[] data, SaslEndpoint endpoint,
        SaslServer server) throws SaslException, IOException {
    try {
        return server.evaluateResponse(data);
    } catch (SaslException e) {
        endpoint.send(new Message(SaslStatus.FAILURE, null));
        System.out.println("Error while processing data");
        throw e;
    }
}
 
Example #28
Source File: PlainSaslServer.java    From incubator-retired-blur with Apache License 2.0 5 votes vote down vote up
public SaslServer createSaslServer(
  String mechanism, String protocol, String serverName, Map<String,?> props, CallbackHandler cbh)
{
  if ("PLAIN".equals(mechanism)) {
    try {
      return new PlainSaslServer(cbh, protocol);
    } catch (SaslException e) {
      return null;
    }
  }
  return null;
}
 
Example #29
Source File: AbstractSaslServerNegotiator.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Override
public AuthenticationResult handleResponse(final byte[] response)
{
    SaslServer saslServer = getSaslServer();
    if (saslServer == null)
    {
        return new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR, getSaslServerCreationException());
    }
    try
    {

        byte[] challenge = saslServer.evaluateResponse(response != null ? response : new byte[0]);

        if (saslServer.isComplete())
        {
            final String userId = saslServer.getAuthorizationID();
            return new AuthenticationResult(new UsernamePrincipal(userId, getAuthenticationProvider()),
                                            challenge);
        }
        else
        {
            return new AuthenticationResult(challenge, AuthenticationResult.AuthenticationStatus.CONTINUE);
        }
    }
    catch (SaslException | IllegalStateException e)
    {
        return new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR, e);
    }
}
 
Example #30
Source File: ClientServerTest.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private byte[] processData(byte[] data, SaslEndpoint endpoint,
        SaslServer server) throws SaslException, IOException {
    try {
        return server.evaluateResponse(data);
    } catch (SaslException e) {
        endpoint.send(new Message(SaslStatus.FAILURE, null));
        System.out.println("Error while processing data");
        throw e;
    }
}