Package javax.security.sasl

Examples of javax.security.sasl.SaslClient


        }
    }

    @Override public void connectionSecure(Connection conn, ConnectionSecure secure)
    {
        SaslClient sc = conn.getSaslClient();
        try
        {
            byte[] response = sc.evaluateChallenge(secure.getChallenge());
            conn.connectionSecureOk(response);
        }
        catch (SaslException e)
        {
            conn.exception(e);
View Full Code Here


                }

                byte[] saslResponse;
                try
                {
                    SaslClient sc =
                        Sasl.createSaslClient(new String[] { mechanism }, null, "AMQP", "localhost", null,
                            createCallbackHandler(mechanism, session));
                    if (sc == null)
                    {
                        throw new AMQException(null, "Client SASL configuration error: no SaslClient could be created for mechanism " + mechanism
                            + ". Please ensure all factories are registered. See DynamicSaslRegistrar for "
                            + " details of how to register non-standard SASL client providers.", null);
                    }

                    session.setSaslClient(sc);
                    saslResponse = (sc.hasInitialResponse() ? sc.evaluateChallenge(new byte[0]) : null);
                }
                catch (SaslException e)
                {
                    session.setSaslClient(null);
                    throw new AMQException(null, "Unable to create SASL client: " + e, e);
View Full Code Here

    }

    public void methodReceived(AMQProtocolSession session, ConnectionSecureBody body, int channelId)
                throws AMQException
    {
        SaslClient client = session.getSaslClient();
        if (client == null)
        {
            throw new AMQException(null, "No SASL client set up - cannot proceed with authentication", null);
        }



        try
        {
            // Evaluate server challenge
            byte[] response = client.evaluateChallenge(body.getChallenge());

            ConnectionSecureOkBody secureOkBody = session.getMethodRegistry().createConnectionSecureOkBody(response);

            session.writeFrame(secureOkBody.generateFrame(channelId));
        }
View Full Code Here

   * protocol. Generates and sends the initial response to the server, including
   * which mechanism this client wants to use.
   */
  @Override
  protected void handleSaslStartMessage() throws TTransportException, SaslException {
    SaslClient saslClient = getSaslClient();

    byte[] initialResponse = new byte[0];
    if (saslClient.hasInitialResponse())
      initialResponse = saslClient.evaluateChallenge(initialResponse);

    LOGGER.debug("Sending mechanism name {} and initial response of length {}", mechanism,
        initialResponse.length);

    byte[] mechanismBytes = mechanism.getBytes();
    sendSaslMessage(NegotiationStatus.START,
                    mechanismBytes);
    // Send initial response
    sendSaslMessage(saslClient.isComplete() ? NegotiationStatus.COMPLETE : NegotiationStatus.OK,
                    initialResponse);
    underlyingTransport.flush();
  }
View Full Code Here

  private void runNegotiation(CallbackHandler clientCbh,
                              CallbackHandler serverCbh)
                                  throws SaslException {
    String mechanism = AuthMethod.PLAIN.getMechanismName();

    SaslClient saslClient = Sasl.createSaslClient(
        new String[]{ mechanism }, null, null, null, null, clientCbh);
    assertNotNull(saslClient);

    SaslServer saslServer = Sasl.createSaslServer(
        mechanism, null, "localhost", null, serverCbh);
    assertNotNull("failed to find PLAIN server", saslServer);
   
    byte[] response = saslClient.evaluateChallenge(new byte[0]);
    assertNotNull(response);
    assertTrue(saslClient.isComplete());

    response = saslServer.evaluateResponse(response);
    assertNull(response);
    assertTrue(saslServer.isComplete());
    assertNotNull(saslServer.getAuthorizationID());
View Full Code Here

    if (server != null) return;
    server = new SaslSocketServer
      (new TestResponder(), new InetSocketAddress(0), DIGEST_MD5_MECHANISM,
       SERVICE, HOST, DIGEST_MD5_PROPS, new TestSaslCallbackHandler());
    server.start();
    SaslClient saslClient = Sasl.createSaslClient
      (new String[]{DIGEST_MD5_MECHANISM}, PRINCIPAL, SERVICE, HOST,
       DIGEST_MD5_PROPS, new TestSaslCallbackHandler());
    client = new SaslSocketTransceiver(new InetSocketAddress(server.getPort()),
                                       saslClient);
    requestor = new GenericRequestor(PROTOCOL, client);
View Full Code Here

  public void testWrongPassword() throws Exception {
    Server s = new SaslSocketServer
      (new TestResponder(), new InetSocketAddress(0), DIGEST_MD5_MECHANISM,
       SERVICE, HOST, DIGEST_MD5_PROPS, new TestSaslCallbackHandler());
    s.start();
    SaslClient saslClient = Sasl.createSaslClient
      (new String[]{DIGEST_MD5_MECHANISM}, PRINCIPAL, SERVICE, HOST,
       DIGEST_MD5_PROPS, new WrongPasswordCallbackHandler());
    Transceiver c = new SaslSocketTransceiver
      (new InetSocketAddress(server.getPort()), saslClient);
    GenericRequestor requestor = new GenericRequestor(PROTOCOL, c);
View Full Code Here

                // createSaslClient() must be declared synchronized so that login is initialized only once.
                login = new Login(loginContext, new ClientCallbackHandler(null));
                login.startThreadIfNeeded();
            }
            Subject subject = login.getSubject();
            SaslClient saslClient;
            // Use subject.getPrincipals().isEmpty() as an indication of which SASL mechanism to use:
            // if empty, use DIGEST-MD5; otherwise, use GSSAPI.
            if (subject.getPrincipals().isEmpty()) {
                // no principals: must not be GSSAPI: use DIGEST-MD5 mechanism instead.
                LOG.info("Client will use DIGEST-MD5 as SASL mechanism.");
                String[] mechs = {"DIGEST-MD5"};
                String username = (String)(subject.getPublicCredentials().toArray()[0]);
                String password = (String)(subject.getPrivateCredentials().toArray()[0]);
                // "zk-sasl-md5" is a hard-wired 'domain' parameter shared with zookeeper server code (see ServerCnxnFactory.java)
                saslClient = Sasl.createSaslClient(mechs, username, "zookeeper", "zk-sasl-md5", null, new ClientCallbackHandler(password));
                return saslClient;
            }
            else { // GSSAPI.
                final Object[] principals = subject.getPrincipals().toArray();
                // determine client principal from subject.
                final Principal clientPrincipal = (Principal)principals[0];
                final KerberosName clientKerberosName = new KerberosName(clientPrincipal.getName());
                // assume that server and client are in the same realm (by default; unless the system property
                // "zookeeper.server.realm" is set).
                String serverRealm = System.getProperty("zookeeper.server.realm",clientKerberosName.getRealm());
                KerberosName serviceKerberosName = new KerberosName(servicePrincipal+"@"+serverRealm);
                final String serviceName = serviceKerberosName.getServiceName();
                final String serviceHostname = serviceKerberosName.getHostName();
                final String clientPrincipalName = clientKerberosName.toString();
                try {
                    saslClient = Subject.doAs(subject,new PrivilegedExceptionAction<SaslClient>() {
                        public SaslClient run() throws SaslException {
                            LOG.info("Client will use GSSAPI as SASL mechanism.");
                            String[] mechs = {"GSSAPI"};
                            LOG.debug("creating sasl client: client="+clientPrincipalName+";service="+serviceName+";serviceHostname="+serviceHostname);
                            SaslClient saslClient = Sasl.createSaslClient(mechs,clientPrincipalName,serviceName,serviceHostname,null,new ClientCallbackHandler(null));
                            return saslClient;
                        }
                    });
                    return saslClient;
                }
View Full Code Here

            {
                properties.put( Sasl.SERVER_AUTH, "true" );
            }

            // Creating a SASL Client
            SaslClient sc = Sasl.createSaslClient(
                new String[]
                    { bindRequest.getSaslMechanism() },
                saslRequest.getAuthorizationId(),
                "ldap",
                config.getLdapHost(),
                properties,
                new SaslCallbackHandler( saslRequest ) );

            // If the SaslClient wasn't created, that means we can't create the SASL client
            // for the requested mechanism. We then produce an Exception
            if ( sc == null )
            {
                String message = "Cannot find a SASL factory for the " + bindRequest.getSaslMechanism() + " mechanism";
                LOG.error( message );
                throw new LdapException( message );
            }

            // Corner case : the SASL mech might send an initial challenge, and we have to
            // deal with it immediately.
            if ( sc.hasInitialResponse() )
            {
                byte[] challengeResponse = sc.evaluateChallenge( new byte[0] );

                // Stores the challenge's response, and send it to the server
                bindRequest.setCredentials( challengeResponse );
                writeBindRequest( bindRequest );

                // Get the server's response, blocking
                bindResponse = bindFuture.get( timeout, TimeUnit.MILLISECONDS );

                if ( bindResponse == null )
                {
                    // We didn't received anything : this is an error
                    LOG.error( "bind failed : timeout occured" );
                    throw new LdapException( TIME_OUT_ERROR );
                }

                result = bindResponse.getLdapResult().getResultCode();
            }
            else
            {
                // Copy the bindRequest without setting the credentials
                BindRequest bindRequestCopy = new BindRequestImpl();
                bindRequestCopy.setMessageId( newId );

                bindRequestCopy.setName( bindRequest.getName() );
                bindRequestCopy.setSaslMechanism( bindRequest.getSaslMechanism() );
                bindRequestCopy.setSimple( bindRequest.isSimple() );
                bindRequestCopy.setVersion3( bindRequest.getVersion3() );
                bindRequestCopy.addAllControls( bindRequest.getControls().values().toArray( new Control[0] ) );

                writeBindRequest( bindRequestCopy );

                bindResponse = bindFuture.get( timeout, TimeUnit.MILLISECONDS );

                if ( bindResponse == null )
                {
                    // We didn't received anything : this is an error
                    LOG.error( "bind failed : timeout occured" );
                    throw new LdapException( TIME_OUT_ERROR );
                }

                result = bindResponse.getLdapResult().getResultCode();
            }

            while ( !sc.isComplete()
                && ( ( result == ResultCodeEnum.SASL_BIND_IN_PROGRESS ) || ( result == ResultCodeEnum.SUCCESS ) ) )
            {
                response = sc.evaluateChallenge( bindResponse.getServerSaslCreds() );

                if ( result == ResultCodeEnum.SUCCESS )
                {
                    if ( response != null )
                    {
View Full Code Here

    }

  }

  private void doAuth() {
    SaslClient saslClient = null;
    try {
      saslClient = Sasl.createSaslClient(authInfo.getMechanisms(), null,
          "memcached", memcachedTCPSession.getRemoteSocketAddress()
              .toString(), null, this.authInfo
              .getCallbackHandler());

      final AtomicBoolean done = new AtomicBoolean(false);
      byte[] response = saslClient.hasInitialResponse() ? saslClient
          .evaluateChallenge(EMPTY_BYTES) : EMPTY_BYTES;
      CountDownLatch latch = new CountDownLatch(1);
      Command command = this.commandFactory.createAuthStartCommand(
          saslClient.getMechanismName(), latch, response);
      if (!this.memcachedTCPSession.isClosed())
        this.memcachedTCPSession.write(command);
      else {
        log
            .error("Authentication fail,because the connection has been closed");
        throw new RuntimeException(
            "Authentication fai,connection has been close");
      }

      while (!done.get()) {
        try {
          latch.await();
        } catch (InterruptedException e) {
          Thread.currentThread().interrupt();
          done.set(true);
        }
        ResponseStatus responseStatus = ((BaseBinaryCommand) command)
            .getResponseStatus();
        switch (responseStatus) {
        case NO_ERROR:
          done.set(true);
          log.info("Authentication to "
              + this.memcachedTCPSession.getRemoteSocketAddress()
              + " successfully");
          break;
        case AUTH_REQUIRED:
          log
              .error("Authentication failed to "
                  + this.memcachedTCPSession
                      .getRemoteSocketAddress());
          log.warn("Reopen connection to "
              + this.memcachedTCPSession.getRemoteSocketAddress()
              + ",beacause auth fail");
          this.memcachedTCPSession.setAuthFailed(true);

          // It it is not first time,try to sleep 1 second
          if (!this.authInfo.isFirstTime()) {
            Thread.sleep(1000);
          }
          this.memcachedTCPSession.close();
          done.set(true);
          break;
        case FUTHER_AUTH_REQUIRED:
          String result = (String) command.getResult();
          response = saslClient.evaluateChallenge(ByteUtils
              .getBytes(result));
          latch = new CountDownLatch(1);
          command = commandFactory.createAuthStepCommand(saslClient
              .getMechanismName(), latch, response);
          if (!this.memcachedTCPSession.isClosed())
            this.memcachedTCPSession.write(command);
          else {
            log
                .error("Authentication fail,because the connection has been closed");
            throw new RuntimeException(
                "Authentication fai,connection has been close");
          }

          break;
        default:
          done.set(true);
          log.error("Authentication failed to "
              + this.memcachedTCPSession.getRemoteSocketAddress()
              + ",response status=" + responseStatus);
          break;

        }

      }
    } catch (Exception e) {
      log.error("Create saslClient error", e);
    } finally {
      if (saslClient != null) {
        try {
          saslClient.dispose();
        } catch (SaslException e) {
          log.error("Dispose saslClient error", e);
        }
      }
    }
View Full Code Here

TOP

Related Classes of javax.security.sasl.SaslClient

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.