Пример #1
0
  @Test
  public void testServerAuthIndirect_Server() throws Exception {
    Map<String, Object> props = new HashMap<String, Object>();

    // No properties are set, an appropriate EntitySaslServer should be returned
    SaslServer server =
        Sasl.createSaslServer(
            SaslMechanismInformation.Names.IEC_ISO_9798_U_RSA_SHA1_ENC,
            "TestProtocol",
            "TestServer",
            props,
            null);
    assertEquals(EntitySaslServer.class, server.getClass());
    assertEquals(
        SaslMechanismInformation.Names.IEC_ISO_9798_U_RSA_SHA1_ENC, server.getMechanismName());

    // If we set SERVER_AUTH to true even though a unilateral mechanism is specified, no server
    // should be returned
    props.put(Sasl.SERVER_AUTH, Boolean.toString(true));
    server =
        Sasl.createSaslServer(
            SaslMechanismInformation.Names.IEC_ISO_9798_U_RSA_SHA1_ENC,
            "TestProtocol",
            "TestServer",
            props,
            null);
    assertNull(server);
  }
Пример #2
0
  @Test
  public void testServerAuthIndirect_Client() throws Exception {
    Map<String, Object> props = new HashMap<String, Object>();

    // No properties are set, an appropriate EntitySaslClient should be returned
    SaslClient client =
        Sasl.createSaslClient(
            new String[] {SaslMechanismInformation.Names.IEC_ISO_9798_U_RSA_SHA1_ENC},
            "TestUser",
            "TestProtocol",
            "TestServer",
            props,
            null);
    assertEquals(EntitySaslClient.class, client.getClass());
    assertEquals(
        SaslMechanismInformation.Names.IEC_ISO_9798_U_RSA_SHA1_ENC, client.getMechanismName());

    // If we set SERVER_AUTH to true even though only unilateral mechanisms are specified, no client
    // should be returned
    props.put(Sasl.SERVER_AUTH, Boolean.toString(true));
    client =
        Sasl.createSaslClient(
            new String[] {
              SaslMechanismInformation.Names.IEC_ISO_9798_U_RSA_SHA1_ENC,
              SaslMechanismInformation.Names.IEC_ISO_9798_U_DSA_SHA1,
              SaslMechanismInformation.Names.IEC_ISO_9798_U_ECDSA_SHA1
            },
            "TestUser",
            "TestProtocol",
            "TestServer",
            props,
            null);
    assertNull(client);

    // If we set SERVER_AUTH to true, an appropriate EntitySaslClient should be returned
    props.put(Sasl.SERVER_AUTH, Boolean.toString(true));
    client =
        Sasl.createSaslClient(
            new String[] {
              SaslMechanismInformation.Names.IEC_ISO_9798_U_RSA_SHA1_ENC,
              SaslMechanismInformation.Names.IEC_ISO_9798_U_DSA_SHA1,
              SaslMechanismInformation.Names.IEC_ISO_9798_U_ECDSA_SHA1,
              SaslMechanismInformation.Names.IEC_ISO_9798_M_RSA_SHA1_ENC,
              SaslMechanismInformation.Names.IEC_ISO_9798_M_DSA_SHA1,
              SaslMechanismInformation.Names.IEC_ISO_9798_M_ECDSA_SHA1
            },
            "TestUser",
            "TestProtocol",
            "TestServer",
            props,
            null);
    assertEquals(EntitySaslClient.class, client.getClass());
    assertEquals(
        SaslMechanismInformation.Names.IEC_ISO_9798_M_RSA_SHA1_ENC, client.getMechanismName());
  }
Пример #3
0
 /**
  * Constructor
  *
  * @param secretManager supplied by SaslServerHandler.
  */
 public SaslNettyServer(JobTokenSecretManager secretManager) {
   if (LOG.isDebugEnabled()) {
     LOG.debug("SaslNettyServer: Secret manager is: " + secretManager);
   }
   /*if[HADOOP_1_SECRET_MANAGER]
   else[HADOOP_1_SECRET_MANAGER]*/
   try {
     secretManager.checkAvailableForRead();
   } catch (StandbyException e) {
     LOG.error("SaslNettyServer: Could not read secret manager: " + e);
   }
   /*end[HADOOP_1_SECRET_MANAGER]*/
   try {
     SaslDigestCallbackHandler ch = new SaslNettyServer.SaslDigestCallbackHandler(secretManager);
     saslServer =
         Sasl.createSaslServer(
             SaslNettyServer.AuthMethod.DIGEST.getMechanismName(),
             null,
             SaslRpcServer.SASL_DEFAULT_REALM,
             SaslRpcServer.SASL_PROPS,
             ch);
   } catch (SaslException e) {
     LOG.error("SaslNettyServer: Could not create SaslServer: " + e);
   }
 }
 public void authenticate(String username, String host, CallbackHandler cbh)
     throws IOException, XMPPException {
   String[] mechanisms = {"DIGEST-MD5"};
   Map<String, String> props = new HashMap<String, String>();
   sc = Sasl.createSaslClient(mechanisms, null, "xmpp", host, props, cbh);
   authenticate();
 }
Пример #5
0
 @Override
 protected SaslClient createSaslClient() {
   try {
     return Sasl.createSaslClient(
         new String[] {MongoCredential.PLAIN_MECHANISM},
         credential.getUserName(),
         DEFAULT_PROTOCOL,
         serverAddress().getHost(),
         null,
         new CallbackHandler() {
           @Override
           public void handle(final Callback[] callbacks)
               throws IOException, UnsupportedCallbackException {
             for (Callback callback : callbacks) {
               if (callback instanceof PasswordCallback) {
                 ((PasswordCallback) callback).setPassword(credential.getPassword());
               } else if (callback instanceof NameCallback) {
                 ((NameCallback) callback).setName(credential.getUserName());
               }
             }
           }
         });
   } catch (SaslException e) {
     throw new MongoException("Exception initializing SASL client", e);
   }
 }
  protected void authenticate() throws IOException, XMPPException {
    String[] mechanisms = {getName()};
    Map<String, String> props = new HashMap<String, String>();
    sc = Sasl.createSaslClient(mechanisms, null, "xmpp", hostname, props, this);

    super.authenticate();
  }
  public void authenticate(String apiKeyAndSessionKey, String host, String sessionSecret)
      throws IOException, XMPPException {
    if (apiKeyAndSessionKey == null || sessionSecret == null) {
      throw new IllegalStateException("Invalid parameters!");
    }

    String[] keyArray = apiKeyAndSessionKey.split("\\|");

    if (keyArray == null || keyArray.length != 2) {
      throw new IllegalStateException("Api key or session key is not present!");
    }

    this.apiKey = keyArray[0];
    this.sessionKey = keyArray[1];
    this.sessionSecret = sessionSecret;

    this.authenticationId = sessionKey;
    this.password = sessionSecret;
    this.hostname = host;

    String[] mechanisms = {"DIGEST-MD5"};
    Map<String, String> props = new HashMap<String, String>();
    sc = Sasl.createSaslClient(mechanisms, null, "xmpp", host, props, this);
    authenticate();
  }
Пример #8
0
 public SaslServerContext(
     final String mech,
     final String serverName,
     final CallbackHandler callback_handler,
     final Map<String, String> props,
     final Subject subject)
     throws SaslException {
   this.subject = subject;
   if (this.subject != null) {
     try {
       server =
           Subject.doAs(
               this.subject,
               new PrivilegedExceptionAction<SaslServer>() {
                 @Override
                 public SaslServer run() throws Exception {
                   return Sasl.createSaslServer(
                       mech, "jgroups", serverName, props, callback_handler);
                 }
               });
     } catch (PrivilegedActionException e) {
       throw (SaslException)
           e.getCause(); // The createSaslServer will only throw this type of exception
     }
   } else {
     server = Sasl.createSaslServer(mech, "jgroups", serverName, props, callback_handler);
   }
 }
Пример #9
0
 public SaslServer createSaslServer(String mechanism, String localFQDN) throws SaslException {
   return Sasl.createSaslServer(
       mechanism,
       "AMQP",
       localFQDN,
       _serverCreationProperties.get(mechanism),
       _callbackHandlerMap.get(mechanism));
 }
  public void authenticate(String username, String host, String password)
      throws IOException, XMPPException {
    this.authenticationId = username;
    this.password = password;
    this.hostname = host;

    String[] mechanisms = {getName()};
    Map<String, String> props = new HashMap<String, String>();
    sc = Sasl.createSaslClient(mechanisms, null, "xmpp", host, props, this);
    super.authenticate();
  }
Пример #11
0
  /**
   * Builds and sends the <tt>auth</tt> stanza to the server. Note that this method of
   * authentication is not recommended, since it is very inflexable. Use {@link
   * #authenticate(String, String, CallbackHandler)} whenever possible.
   *
   * @param username the username of the user being authenticated.
   * @param host the hostname where the user account resides.
   * @param password the password for this account.
   * @throws IOException If a network error occurs while authenticating.
   * @throws XMPPException If a protocol error occurs or the user is not authenticated.
   */
  public void authenticate(String username, String host, String password)
      throws IOException, XMPPException {
    // Since we were not provided with a CallbackHandler, we will use our own with the given
    // information

    // Set the authenticationID as the username, since they must be the same in this case.
    this.authenticationId = username;
    this.password = password;
    this.hostname = host;

    String[] mechanisms = {getName()};
    Map<String, String> props = new HashMap<String, String>();
    sc = Sasl.createSaslClient(mechanisms, username, "xmpp", host, props, this);
    authenticate();
  }
Пример #12
0
  public void initiateSASL() {
    SaslMechanisms mechanisms = new SaslMechanisms();
    final Enumeration<SaslServerFactory> saslServerFactories = Sasl.getSaslServerFactories();

    SaslServerFactory f;
    ArrayList<Symbol> mechanismsList = new ArrayList<Symbol>();
    while (saslServerFactories.hasMoreElements()) {
      f = saslServerFactories.nextElement();
      final String[] mechanismNames = f.getMechanismNames(null);
      for (String name : mechanismNames) {
        mechanismsList.add(Symbol.valueOf(name));
      }
    }
    mechanisms.setSaslServerMechanisms(mechanismsList.toArray(new Symbol[mechanismsList.size()]));
    _saslFrameOutput.send(new SASLFrame(mechanisms), null);
  }
Пример #13
0
  private boolean saslAuth(final Map<String, Object> props) throws AuthorizationException {
    try {
      SaslServer ss = (SaslServer) props.get("SaslServer");

      if (ss == null) {
        Map<String, String> sasl_props = new TreeMap<String, String>();

        sasl_props.put(Sasl.QOP, "auth");
        ss =
            Sasl.createSaslServer(
                (String) props.get(MACHANISM_KEY),
                "xmpp",
                (String) props.get(SERVER_NAME_KEY),
                sasl_props,
                new SaslCallbackHandler(props));
        props.put("SaslServer", ss);
      } // end of if (ss == null)

      String data_str = (String) props.get(DATA_KEY);
      byte[] in_data = ((data_str != null) ? Base64.decode(data_str) : new byte[0]);

      if (log.isLoggable(Level.FINEST)) {
        log.finest("response: " + new String(in_data));
      }

      byte[] challenge = ss.evaluateResponse(in_data);

      if (log.isLoggable(Level.FINEST)) {
        log.finest("challenge: " + ((challenge != null) ? new String(challenge) : "null"));
      }

      String challenge_str =
          (((challenge != null) && (challenge.length > 0)) ? Base64.encode(challenge) : null);

      props.put(RESULT_KEY, challenge_str);

      if (ss.isComplete()) {
        return true;
      } else {
        return false;
      } // end of if (ss.isComplete()) else
    } catch (SaslException e) {
      throw new AuthorizationException("Sasl exception.", e);
    } // end of try-catch
  }
Пример #14
0
 /**
  * Constructor
  *
  * @param secretManager supplied by SaslServerHandler.
  * @param authMethod Authentication method
  */
 public SaslNettyServer(JobTokenSecretManager secretManager, AuthMethod authMethod)
     throws IOException {
   /*if[HADOOP_1_SECRET_MANAGER]
   else[HADOOP_1_SECRET_MANAGER]*/
   super(authMethod);
   /*end[HADOOP_1_SECRET_MANAGER]*/
   if (LOG.isDebugEnabled()) {
     LOG.debug(
         "SaslNettyServer: Secret manager is: "
             + secretManager
             + " with authmethod "
             + authMethod);
   }
   /*if[HADOOP_1_SECRET_MANAGER]
   else[HADOOP_1_SECRET_MANAGER]*/
   try {
     secretManager.checkAvailableForRead();
   } catch (StandbyException e) {
     LOG.error("SaslNettyServer: Could not read secret manager: " + e);
   }
   /*end[HADOOP_1_SECRET_MANAGER]*/
   try {
     SaslDigestCallbackHandler ch = new SaslNettyServer.SaslDigestCallbackHandler(secretManager);
     /*if[STATIC_SASL_SYMBOL]
           saslServer =
               Sasl.createSaslServer(
                   SaslNettyServer.AuthMethod.DIGEST.getMechanismName(), null,
                   SaslRpcServer.SASL_DEFAULT_REALM, SaslRpcServer.SASL_PROPS, ch);
     else[STATIC_SASL_SYMBOL]*/
     SaslPropertiesResolver saslPropsResolver =
         SaslPropertiesResolver.getInstance(new Configuration());
     saslServer =
         Sasl.createSaslServer(
             SaslNettyServer.AuthMethod.DIGEST.getMechanismName(),
             null,
             SaslRpcServer.SASL_DEFAULT_REALM,
             saslPropsResolver.getDefaultProperties(),
             ch);
     /*end[STATIC_SASL_SYMBOL]*/
   } catch (SaslException e) {
     LOG.error("SaslNettyServer: Could not create SaslServer: " + e);
   }
 }
Пример #15
0
 public OcsConnection(final String domain, final OcsAccount account, int key) {
   this.domain = domain;
   this.addr = Util.cast2SocketAddress(domain);
   this.account = account;
   this.setKey(key);
   if (account.isExemptPassword() == false) {
     this.plainHandler = new OcsPlainHandler(account.getUsername(), account.getPassword());
     mech = new String[] {"PLAIN"};
     try {
       SaslClient sc =
           Sasl.createSaslClient(mech, null, "memcached", addr.toString(), null, plainHandler);
       evaluate = sc.evaluateChallenge(/* empty bytes */ new byte[0]);
       mechanism = sc.getMechanismName();
     } catch (SaslException e) {
       logger.error("SaslClient exception", e);
       throw new RuntimeException("SaslClient exception", e);
     }
   }
   channel = null;
 }
Пример #16
0
    @Override
    protected SaslClient createSaslClient() {
      try {
        Map<String, Object> props = new HashMap<String, Object>();
        props.put(Sasl.CREDENTIALS, getGSSCredential(credential.getUserName()));

        return Sasl.createSaslClient(
            new String[] {GSSAPI_MECHANISM},
            credential.getUserName(),
            credential.getMechanismProperty(SERVICE_NAME_KEY, SERVICE_NAME_DEFAULT_VALUE),
            getHostName(),
            props,
            null);
      } catch (SaslException e) {
        throw new MongoException("Exception initializing SASL client", e);
      } catch (GSSException e) {
        throw new MongoException("Exception initializing GSSAPI credentials", e);
      } catch (UnknownHostException e) {
        throw new MongoException("Unknown host " + serverAddress().getHost(), e);
      }
    }
Пример #17
0
 @Override
 public boolean auth(Auth auth, JIDContext context) {
   try {
     context.write(
         new Challenge(
             this.saslServers
                 .push(
                     context,
                     Sasl.createSaslServer(
                         mechanism,
                         this.protocol,
                         context.domain(),
                         this.props,
                         new ServerCallbackHandler(context)))
                 .evaluateResponse(new byte[0])));
     return true;
   } catch (Exception e) {
     this.log.error(e.toString());
     Trace.trace(this.log, e);
     return false;
   }
 }
Пример #18
0
  SaslNettyServer(String topologyName, byte[] token) throws IOException {
    LOG.debug(
        "SaslNettyServer: Topology token is: "
            + topologyName
            + " with authmethod "
            + SaslUtils.AUTH_DIGEST_MD5);

    try {

      SaslDigestCallbackHandler ch =
          new SaslNettyServer.SaslDigestCallbackHandler(topologyName, token);

      saslServer =
          Sasl.createSaslServer(
              SaslUtils.AUTH_DIGEST_MD5,
              null,
              SaslUtils.DEFAULT_REALM,
              SaslUtils.getSaslProps(),
              ch);

    } catch (SaslException e) {
      LOG.error("SaslNettyServer: Could not create SaslServer: " + e);
    }
  }
  public boolean authenticate(
      String[] mechs, final String realm, final String authzid, final String u, final String p)
      throws ProtocolException {

    synchronized (pr) { // authenticate method should be synchronized
      List<Response> v = new ArrayList<Response>();
      String tag = null;
      Response r = null;
      boolean done = false;
      if (logger.isLoggable(Level.FINE)) {
        logger.fine("SASL Mechanisms:");
        for (int i = 0; i < mechs.length; i++) logger.fine(" " + mechs[i]);
        logger.fine("");
      }

      SaslClient sc;
      CallbackHandler cbh =
          new CallbackHandler() {
            public void handle(Callback[] callbacks) {
              if (logger.isLoggable(Level.FINE))
                logger.fine("SASL callback length: " + callbacks.length);
              for (int i = 0; i < callbacks.length; i++) {
                if (logger.isLoggable(Level.FINE))
                  logger.fine("SASL callback " + i + ": " + callbacks[i]);
                if (callbacks[i] instanceof NameCallback) {
                  NameCallback ncb = (NameCallback) callbacks[i];
                  ncb.setName(u);
                } else if (callbacks[i] instanceof PasswordCallback) {
                  PasswordCallback pcb = (PasswordCallback) callbacks[i];
                  pcb.setPassword(p.toCharArray());
                } else if (callbacks[i] instanceof RealmCallback) {
                  RealmCallback rcb = (RealmCallback) callbacks[i];
                  rcb.setText(realm != null ? realm : rcb.getDefaultText());
                } else if (callbacks[i] instanceof RealmChoiceCallback) {
                  RealmChoiceCallback rcb = (RealmChoiceCallback) callbacks[i];
                  if (realm == null) rcb.setSelectedIndex(rcb.getDefaultChoice());
                  else {
                    // need to find specified realm in list
                    String[] choices = rcb.getChoices();
                    for (int k = 0; k < choices.length; k++) {
                      if (choices[k].equals(realm)) {
                        rcb.setSelectedIndex(k);
                        break;
                      }
                    }
                  }
                }
              }
            }
          };

      try {
        sc = Sasl.createSaslClient(mechs, authzid, name, host, (Map) props, cbh);
      } catch (SaslException sex) {
        logger.log(Level.FINE, "Failed to create SASL client", sex);
        throw new UnsupportedOperationException(sex.getMessage(), sex);
      }
      if (sc == null) {
        logger.fine("No SASL support");
        throw new UnsupportedOperationException("No SASL support");
      }
      if (logger.isLoggable(Level.FINE)) logger.fine("SASL client " + sc.getMechanismName());

      try {
        Argument args = new Argument();
        args.writeAtom(sc.getMechanismName());
        if (pr.hasCapability("SASL-IR") && sc.hasInitialResponse()) {
          String irs;
          byte[] ba = sc.evaluateChallenge(new byte[0]);
          if (ba.length > 0) {
            ba = BASE64EncoderStream.encode(ba);
            irs = ASCIIUtility.toString(ba, 0, ba.length);
          } else irs = "=";
          args.writeAtom(irs);
        }
        tag = pr.writeCommand("AUTHENTICATE", args);
      } catch (Exception ex) {
        logger.log(Level.FINE, "SASL AUTHENTICATE Exception", ex);
        return false;
      }

      OutputStream os = pr.getIMAPOutputStream(); // stream to IMAP server

      /*
       * Wrap a BASE64Encoder around a ByteArrayOutputstream
       * to craft b64 encoded username and password strings
       *
       * Note that the encoded bytes should be sent "as-is" to the
       * server, *not* as literals or quoted-strings.
       *
       * Also note that unlike the B64 definition in MIME, CRLFs
       * should *not* be inserted during the encoding process. So, I
       * use Integer.MAX_VALUE (0x7fffffff (> 1G)) as the bytesPerLine,
       * which should be sufficiently large !
       */

      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      byte[] CRLF = {(byte) '\r', (byte) '\n'};

      // Hack for Novell GroupWise XGWTRUSTEDAPP authentication mechanism
      // http://www.novell.com/developer/documentation/gwimap/?
      //   page=/developer/documentation/gwimap/gwimpenu/data/al7te9j.html
      boolean isXGWTRUSTEDAPP =
          sc.getMechanismName().equals("XGWTRUSTEDAPP")
              && PropUtil.getBooleanProperty(
                  props, "mail." + name + ".sasl.xgwtrustedapphack.enable", true);
      while (!done) { // loop till we are done
        try {
          r = pr.readResponse();
          if (r.isContinuation()) {
            byte[] ba = null;
            if (!sc.isComplete()) {
              ba = r.readByteArray().getNewBytes();
              if (ba.length > 0) ba = BASE64DecoderStream.decode(ba);
              if (logger.isLoggable(Level.FINE))
                logger.fine("SASL challenge: " + ASCIIUtility.toString(ba, 0, ba.length) + " :");
              ba = sc.evaluateChallenge(ba);
            }
            if (ba == null) {
              logger.fine("SASL no response");
              os.write(CRLF); // write out empty line
              os.flush(); // flush the stream
              bos.reset(); // reset buffer
            } else {
              if (logger.isLoggable(Level.FINE))
                logger.fine("SASL response: " + ASCIIUtility.toString(ba, 0, ba.length) + " :");
              ba = BASE64EncoderStream.encode(ba);
              if (isXGWTRUSTEDAPP) bos.write(ASCIIUtility.getBytes("XGWTRUSTEDAPP "));
              bos.write(ba);

              bos.write(CRLF); // CRLF termination
              os.write(bos.toByteArray()); // write out line
              os.flush(); // flush the stream
              bos.reset(); // reset buffer
            }
          } else if (r.isTagged() && r.getTag().equals(tag))
            // Ah, our tagged response
            done = true;
          else if (r.isBYE()) // outta here
          done = true;
          else // hmm .. unsolicited response here ?!
          v.add(r);
        } catch (Exception ioex) {
          logger.log(Level.FINE, "SASL Exception", ioex);
          // convert this into a BYE response
          r = Response.byeResponse(ioex);
          done = true;
          // XXX - ultimately return true???
        }
      }

      if (sc.isComplete() /*&& res.status == SUCCESS*/) {
        String qop = (String) sc.getNegotiatedProperty(Sasl.QOP);
        if (qop != null
            && (qop.equalsIgnoreCase("auth-int") || qop.equalsIgnoreCase("auth-conf"))) {
          // XXX - NOT SUPPORTED!!!
          logger.fine("SASL Mechanism requires integrity or confidentiality");
          return false;
        }
      }

      /* Dispatch untagged responses.
       * NOTE: in our current upper level IMAP classes, we add the
       * responseHandler to the Protocol object only *after* the
       * connection has been authenticated. So, for now, the below
       * code really ends up being just a no-op.
       */
      Response[] responses = v.toArray(new Response[v.size()]);
      pr.notifyResponseHandlers(responses);

      // Handle the final OK, NO, BAD or BYE response
      pr.handleResult(r);
      pr.setCapabilities(r);

      /*
       * If we're using the Novell Groupwise XGWTRUSTEDAPP mechanism
       * to run as a specified authorization ID, we have to issue a
       * LOGIN command to select the user we want to operate as.
       */
      if (isXGWTRUSTEDAPP && authzid != null) {
        Argument args = new Argument();
        args.writeString(authzid);

        responses = pr.command("LOGIN", args);

        // dispatch untagged responses
        pr.notifyResponseHandlers(responses);

        // Handle result of this command
        pr.handleResult(responses[responses.length - 1]);
        // If the response includes a CAPABILITY response code, process it
        pr.setCapabilities(responses[responses.length - 1]);
      }
      return true;
    }
  }
Пример #20
0
  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);
        }
      }
    }
  }
Пример #21
0
 public static void main(String[] args) throws Exception {
   try {
     Sasl.createSaslClient(
         new String[] {"NTLM"}, "abc", "ldap", "server", new HashMap<String, Object>(), null);
   } catch (SaslException se) {
     System.out.println(se);
   }
   try {
     Sasl.createSaslServer("NTLM", "ldap", "server", new HashMap<String, Object>(), null);
   } catch (SaslException se) {
     System.out.println(se);
   }
   try {
     Sasl.createSaslClient(
         new String[] {"NTLM"},
         "abc",
         "ldap",
         "server",
         null,
         new CallbackHandler() {
           @Override
           public void handle(Callback[] callbacks)
               throws IOException, UnsupportedCallbackException {}
         });
   } catch (SaslException se) {
     System.out.println(se);
   }
   try {
     SaslServer saslServer =
         Sasl.createSaslServer(
             "NTLM",
             "ldap",
             "abc",
             null,
             new CallbackHandler() {
               @Override
               public void handle(Callback[] callbacks)
                   throws IOException, UnsupportedCallbackException {}
             });
     System.err.println("saslServer = " + saslServer);
     System.err.println("saslServer.isComplete() = " + saslServer.isComplete());
     // IllegalStateException is expected here
     saslServer.getNegotiatedProperty("prop");
     System.err.println("No IllegalStateException");
   } catch (IllegalStateException se) {
     System.out.println(se);
   }
   try {
     SaslServer saslServer =
         Sasl.createSaslServer(
             "NTLM",
             "ldap",
             "abc",
             null,
             new CallbackHandler() {
               @Override
               public void handle(Callback[] callbacks)
                   throws IOException, UnsupportedCallbackException {}
             });
     System.err.println("saslServer = " + saslServer);
     System.err.println("saslServer.isComplete() = " + saslServer.isComplete());
     // IllegalStateException is expected here
     saslServer.getAuthorizationID();
     System.err.println("No IllegalStateException");
   } catch (IllegalStateException se) {
     System.out.println(se);
   }
   try {
     SaslServer saslServer =
         Sasl.createSaslServer(
             "NTLM",
             "ldap",
             "abc",
             null,
             new CallbackHandler() {
               @Override
               public void handle(Callback[] callbacks)
                   throws IOException, UnsupportedCallbackException {}
             });
     System.err.println("saslServer = " + saslServer);
     System.err.println("saslServer.isComplete() = " + saslServer.isComplete());
     // IllegalStateException is expected here
     saslServer.wrap(new byte[0], 0, 0);
     System.err.println("No IllegalStateException");
   } catch (IllegalStateException se) {
     System.out.println(se);
   }
 }