@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);
  }
  @Test
  public void testServerNotTrustedByClient() throws Exception {
    final SaslClientFactory clientFactory = obtainSaslClientFactory(EntitySaslClientFactory.class);
    assertNotNull(clientFactory);

    final SaslServer saslServer =
        createSaslServer(
            SaslMechanismInformation.Names.IEC_ISO_9798_M_RSA_SHA1_ENC,
            "testserver1.example.com",
            getX509KeyManager(serverKeyStore, KEYSTORE_PASSWORD),
            getX509TrustManager(serverTrustStore));

    final String[] mechanisms =
        new String[] {SaslMechanismInformation.Names.IEC_ISO_9798_M_RSA_SHA1_ENC};
    CallbackHandler cbh =
        createClientCallbackHandler(
            mechanisms, clientKeyStore, CLIENT_KEYSTORE_ALIAS, KEYSTORE_PASSWORD, null);
    final SaslClient saslClient =
        clientFactory.createSaslClient(
            mechanisms,
            null,
            "test",
            "testserver1.example.com",
            Collections.<String, Object>emptyMap(),
            cbh);

    byte[] message = saslServer.evaluateResponse(new byte[0]);
    message = saslClient.evaluateChallenge(message);
    message = saslServer.evaluateResponse(message);
    try {
      saslClient.evaluateChallenge(message);
      fail("Expected SaslException not thrown");
    } catch (SaslException expected) {
    }
  }
 void receiveAuthResponse(final int id, final byte[] response) {
   log.tracef("Received authentication response for ID %08x", id);
   if (id == 0 || id == 1) {
     // ignore
     return;
   }
   getExecutor()
       .execute(
           () -> {
             Auth auth = authMap.get(id);
             if (auth == null) {
               auth = authMap.putIfAbsent(new Auth(id, new RejectingSaslServer()));
               if (auth == null) {
                 // reject
                 try {
                   connectionHandler.sendAuthReject(id);
                 } catch (IOException e1) {
                   log.trace("Failed to send auth reject", e1);
                 }
                 return;
               }
             }
             final SaslServer saslServer = auth.getSaslServer();
             final byte[] challenge;
             try {
               challenge = saslServer.evaluateResponse(response);
             } catch (SaslException e) {
               try {
                 connectionHandler.sendAuthReject(id);
               } catch (IOException e1) {
                 authMap.remove(auth);
                 auth.dispose();
                 log.trace("Failed to send auth reject", e1);
               }
               return;
             }
             if (saslServer.isComplete()) {
               try {
                 connectionHandler.sendAuthSuccess(id, challenge);
               } catch (IOException e) {
                 authMap.remove(auth);
                 auth.dispose();
                 log.trace("Failed to send auth success", e);
               }
               return;
             } else {
               try {
                 connectionHandler.sendAuthChallenge(id, challenge);
               } catch (IOException e) {
                 authMap.remove(auth);
                 auth.dispose();
                 log.trace("Failed to send auth challenge", e);
               }
               return;
             }
           });
 }
Example #4
0
 @Override
 public boolean needsWrapping() {
   if (server.isComplete()) {
     String qop = (String) server.getNegotiatedProperty(Sasl.QOP);
     return (qop != null
         && (qop.equalsIgnoreCase("auth-int") || qop.equalsIgnoreCase("auth-conf")));
   } else {
     return false;
   }
 }
Example #5
0
 @Override
 public Message nextMessage(Address address, SaslHeader header) throws SaslException {
   Message message = new Message(address).setFlag(Message.Flag.OOB);
   byte[] challenge = server.evaluateResponse(header.getPayload());
   if (server.isComplete()) {
     latch.countDown();
   }
   if (challenge != null) {
     return message.putHeader(SASL.SASL_ID, new SaslHeader(Type.RESPONSE, challenge));
   } else {
     return null;
   }
 }
 void dispose() {
   try {
     saslServer.dispose();
   } catch (SaslException se) {
     log.trace("Failed to dispose SASL mechanism", se);
   }
 }
Example #7
0
 @Override
 public void dispose() {
   try {
     server.dispose();
   } catch (SaslException e) {
   }
 }
  @Test
  public void testMutualAuthenticationWithDNSInCNField() throws Exception {
    // Although specifying a DNS name using the Common Name field has been deprecated, it is
    // still used in practice (e.g., see http://tools.ietf.org/html/rfc2818). This test makes
    // sure that general name matching during authentication still works in this case.
    final SaslClientFactory clientFactory = obtainSaslClientFactory(EntitySaslClientFactory.class);
    assertNotNull(clientFactory);

    final KeyStore keyStore = loadKeyStore(serverKeyStore);
    final Certificate[] certificateChain = keyStore.getCertificateChain("dnsInCNServer");
    final SaslServer saslServer =
        createSaslServer(
            SaslMechanismInformation.Names.IEC_ISO_9798_M_DSA_SHA1,
            "testserver2.example.com",
            getX509TrustManager(serverTrustStore),
            (PrivateKey) keyStore.getKey("dnsInCNServer", KEYSTORE_PASSWORD),
            Arrays.copyOf(certificateChain, certificateChain.length, X509Certificate[].class));

    final String[] mechanisms =
        new String[] {SaslMechanismInformation.Names.IEC_ISO_9798_M_DSA_SHA1};
    CallbackHandler cbh =
        createClientCallbackHandler(
            mechanisms,
            clientKeyStore,
            "dnsInCNClient",
            KEYSTORE_PASSWORD,
            getX509TrustManager(clientTrustStore));
    final SaslClient saslClient =
        clientFactory.createSaslClient(
            mechanisms,
            null,
            "test",
            "testserver2.example.com",
            Collections.<String, Object>emptyMap(),
            cbh);
    assertFalse(saslServer.isComplete());
    assertFalse(saslClient.isComplete());

    byte[] message = saslServer.evaluateResponse(new byte[0]);
    assertFalse(saslServer.isComplete());
    assertFalse(saslClient.isComplete());

    message = saslClient.evaluateChallenge(message);
    assertFalse(saslServer.isComplete());
    assertFalse(saslClient.isComplete());

    message = saslServer.evaluateResponse(message);
    assertNotNull(message);

    message = saslClient.evaluateChallenge(message);
    assertNull(message);
    assertTrue(saslClient.isComplete());
    assertTrue(saslServer.isComplete());
    assertEquals(
        "cn=testclient2.example.com,ou=jboss,o=red hat,l=raleigh,st=north carolina,c=us",
        saslServer.getAuthorizationID());
  }
  public SaslOutputStream(SaslServer server, OutputStream dest) throws IOException {
    super();

    this.server = server;
    maxRawSendSize = Integer.parseInt((String) server.getNegotiatedProperty(Sasl.RAW_SEND_SIZE));
    client = null;
    this.dest = dest;
  }
Example #10
0
  public void receiveSaslInit(final SaslInit saslInit) {
    Symbol mechanism = saslInit.getMechanism();
    final Binary initialResponse = saslInit.getInitialResponse();
    byte[] response = initialResponse == null ? new byte[0] : initialResponse.getArray();

    try {
      _saslServer = _saslServerProvider.getSaslServer(mechanism.toString(), "localhost");

      // Process response from the client
      byte[] challenge = _saslServer.evaluateResponse(response != null ? response : new byte[0]);

      if (_saslServer.isComplete()) {
        SaslOutcome outcome = new SaslOutcome();

        outcome.setCode(SaslCode.OK);
        _saslFrameOutput.send(new SASLFrame(outcome), null);
        synchronized (getLock()) {
          _saslComplete = true;
          _authenticated = true;
          getLock().notifyAll();
        }

        if (_onSaslCompleteTask != null) {
          _onSaslCompleteTask.run();
        }

      } else {
        SaslChallenge challengeBody = new SaslChallenge();
        challengeBody.setChallenge(new Binary(challenge));
        _saslFrameOutput.send(new SASLFrame(challengeBody), null);
      }
    } catch (SaslException e) {
      SaslOutcome outcome = new SaslOutcome();

      outcome.setCode(SaslCode.AUTH);
      _saslFrameOutput.send(new SASLFrame(outcome), null);
      synchronized (getLock()) {
        _saslComplete = true;
        _authenticated = false;
        getLock().notifyAll();
      }
      if (_onSaslCompleteTask != null) {
        _onSaslCompleteTask.run();
      }
    }
  }
Example #11
0
  public AuthenticationResult authenticate(SaslServer server, byte[] response) {
    try {
      // Process response from the client
      byte[] challenge = server.evaluateResponse(response != null ? response : new byte[0]);

      if (server.isComplete()) {
        final Subject subject = new Subject();
        subject.getPrincipals().add(new UsernamePrincipal(server.getAuthorizationID()));
        return new AuthenticationResult(subject);
      } else {
        return new AuthenticationResult(
            challenge, AuthenticationResult.AuthenticationStatus.CONTINUE);
      }
    } catch (SaslException e) {
      return new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR, e);
    }
  }
  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
  }
Example #13
0
  public void receiveSaslResponse(final SaslResponse saslResponse) {
    final Binary responseBinary = saslResponse.getResponse();
    byte[] response = responseBinary == null ? new byte[0] : responseBinary.getArray();

    try {

      // Process response from the client
      byte[] challenge = _saslServer.evaluateResponse(response != null ? response : new byte[0]);

      if (_saslServer.isComplete()) {
        SaslOutcome outcome = new SaslOutcome();

        outcome.setCode(SaslCode.OK);
        _saslFrameOutput.send(new SASLFrame(outcome), null);
        synchronized (getLock()) {
          _saslComplete = true;
          _authenticated = true;
          getLock().notifyAll();
        }
        if (_onSaslCompleteTask != null) {
          _onSaslCompleteTask.run();
        }

      } else {
        SaslChallenge challengeBody = new SaslChallenge();
        challengeBody.setChallenge(new Binary(challenge));
        _saslFrameOutput.send(new SASLFrame(challengeBody), null);
      }
    } catch (SaslException e) {
      SaslOutcome outcome = new SaslOutcome();

      outcome.setCode(SaslCode.AUTH);
      _saslFrameOutput.send(new SASLFrame(outcome), null);
      synchronized (getLock()) {
        _saslComplete = true;
        _authenticated = false;
        getLock().notifyAll();
      }
      if (_onSaslCompleteTask != null) {
        _onSaslCompleteTask.run();
      }
    }
  }
Example #14
0
 /**
  * Used by SaslTokenMessage::processToken() to respond to server SASL tokens.
  *
  * @param token Server's SASL token
  * @return token to send back to the server.
  */
 public byte[] response(byte[] token) {
   try {
     LOG.debug("response: Responding to input token of length: " + token.length);
     byte[] retval = saslServer.evaluateResponse(token);
     LOG.debug("response: Response token length: " + retval.length);
     return retval;
   } catch (SaslException e) {
     LOG.error("response: Failed to evaluate client token of length: " + token.length + " : " + e);
     return null;
   }
 }
  @Ignore // todo: this test could be modified to use the wrong key of the write algorithm, or it
          // could be removed
  @Test
  public void testServerPrivateKeyPublicKeyMismatch() throws Exception {
    final SaslClientFactory clientFactory = obtainSaslClientFactory(EntitySaslClientFactory.class);
    assertNotNull(clientFactory);

    // A certificate that does not correspond to the server's private key will be used
    final KeyStore keyStore = loadKeyStore(serverKeyStore);
    final Certificate[] certificateChain = keyStore.getCertificateChain(WRONG_KEYSTORE_ALIAS);
    final SaslServer saslServer =
        createSaslServer(
            SaslMechanismInformation.Names.IEC_ISO_9798_M_RSA_SHA1_ENC,
            "testserver1.example.com",
            getX509TrustManager(serverTrustStore),
            (PrivateKey) keyStore.getKey(SERVER_KEYSTORE_ALIAS, KEYSTORE_PASSWORD),
            Arrays.copyOf(certificateChain, certificateChain.length, X509Certificate[].class));

    final String[] mechanisms =
        new String[] {SaslMechanismInformation.Names.IEC_ISO_9798_M_RSA_SHA1_ENC};
    CallbackHandler cbh =
        createClientCallbackHandler(
            mechanisms,
            clientKeyStore,
            CLIENT_KEYSTORE_ALIAS,
            KEYSTORE_PASSWORD,
            getX509TrustManager(clientTrustStore));
    final SaslClient saslClient =
        clientFactory.createSaslClient(
            mechanisms, null, "test", "", Collections.<String, Object>emptyMap(), cbh);

    byte[] message = saslServer.evaluateResponse(new byte[0]);
    message = saslClient.evaluateChallenge(message);
    message = saslServer.evaluateResponse(message);
    try {
      saslClient.evaluateChallenge(message);
      fail("Expected SaslException not thrown");
    } catch (SaslException expected) {
    }
  }
  @Test
  public void testSimpleMutualSha1WithRsaAuthentication() throws Exception {
    final SaslClientFactory clientFactory = obtainSaslClientFactory(EntitySaslClientFactory.class);
    assertNotNull(clientFactory);

    final SaslServer saslServer =
        createSaslServer(
            SaslMechanismInformation.Names.IEC_ISO_9798_M_RSA_SHA1_ENC,
            "testserver1.example.com",
            getX509KeyManager(serverKeyStore, KEYSTORE_PASSWORD),
            getX509TrustManager(serverTrustStore));

    final String[] mechanisms =
        new String[] {SaslMechanismInformation.Names.IEC_ISO_9798_M_RSA_SHA1_ENC};
    CallbackHandler cbh =
        createClientCallbackHandler(
            mechanisms,
            clientKeyStore,
            CLIENT_KEYSTORE_ALIAS,
            KEYSTORE_PASSWORD,
            getX509TrustManager(clientTrustStore));
    final SaslClient saslClient =
        clientFactory.createSaslClient(
            mechanisms,
            null,
            "test",
            "testserver1.example.com",
            Collections.<String, Object>emptyMap(),
            cbh);
    assertFalse(saslServer.isComplete());
    assertFalse(saslClient.isComplete());

    byte[] message = saslServer.evaluateResponse(new byte[0]);
    assertFalse(saslServer.isComplete());
    assertFalse(saslClient.isComplete());

    message = saslClient.evaluateChallenge(message);
    assertFalse(saslServer.isComplete());
    assertFalse(saslClient.isComplete());

    message = saslServer.evaluateResponse(message);
    assertNotNull(message);
    message = saslClient.evaluateChallenge(message);
    assertNull(message);
    assertTrue(saslClient.isComplete());
    assertTrue(saslServer.isComplete());
    assertEquals(
        "cn=test client 1,ou=jboss,o=red hat,l=raleigh,st=north carolina,c=us",
        saslServer.getAuthorizationID());
  }
Example #17
0
    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);
    }
  @Test
  public void testRfc3163Example() throws Exception {
    // This test uses the example from page 10 in RFC 3163
    // (https://tools.ietf.org/html/rfc3163#section-5)
    mockRandom(new byte[] {18, 56, -105, 88, 121, -121, 71, -104});

    KeyStore emptyTrustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    emptyTrustStore.load(null, null);
    final SaslServer saslServer =
        createSaslServer(
            SaslMechanismInformation.Names.IEC_ISO_9798_U_RSA_SHA1_ENC,
            "",
            getX509KeyManager(serverKeyStore, KEYSTORE_PASSWORD),
            getX509TrustManager(emptyTrustStore));
    assertNotNull(saslServer);
    assertFalse(saslServer.isComplete());

    byte[] tokenBA1 = saslServer.evaluateResponse(new byte[0]);
    byte[] expectedTokenBA1 = CodePointIterator.ofString("MAoECBI4l1h5h0eY").base64Decode().drain();
    assertArrayEquals(expectedTokenBA1, tokenBA1);
    assertFalse(saslServer.isComplete());

    byte[] tokenAB =
        CodePointIterator.ofString(
                "MIIBAgQIIxh5I0h5RYegD4INc2FzbC1yLXVzLmNvbaFPFk1odHRwOi8vY2VydHMtci11cy5jb20vY2VydD9paD1odmNOQVFFRkJRQURnWUVBZ2hBR2hZVFJna0ZqJnNuPUVQOXVFbFkzS0RlZ2pscjCBkzANBgkqhkiG9w0BAQUFAAOBgQCkuC2GgtYcxGG1NEzLA4bh5lqJGOZySACMmc+mDrV7A7KAgbpO2OuZpMCl7zvNt/L3OjQZatiX8d1XbuQ40l+g2TJzJt06o7ogomxdDwqlA/3zp2WMohlI0MotHmfDSWEDZmEYDEA3/eGgkWyi1v1lEVdFuYmrTr8E4wE9hxdQrA==")
            .base64Decode()
            .drain();
    try {
      saslServer.evaluateResponse(tokenAB);
      fail("Expected SaslException not thrown");
    } catch (SaslException expected) {
      // The example specifies the client's certificate using a fake URL
      // (http://certs-r-us.com/cert?ih=hvcNAQEFBQADgYEAghAGhYTRgkFj&sn=EP9uElY3KDegjlr)
      // so we can actually make use of it.
      assertTrue(expected.getCause().getMessage().contains("certificate"));
    }
    assertFalse(saslServer.isComplete());
  }
 public void receiveAuthRequest(
     final int id, final String mechName, final byte[] initialResponse) {
   log.tracef("Received authentication request for ID %08x, mech %s", id, mechName);
   if (id == 0 || id == 1) {
     // ignore
     return;
   }
   getExecutor()
       .execute(
           () -> {
             final SaslServer saslServer;
             final IntIndexHashMap<Auth> authMap = this.authMap;
             try {
               saslServer =
                   authenticationFactory.createMechanism(
                       mechName, f -> new ServerNameSaslServerFactory(f, endpoint.getName()));
             } catch (SaslException e) {
               log.trace("Authentication failed at mechanism creation", e);
               try {
                 Auth oldAuth = authMap.put(new Auth(id, new RejectingSaslServer()));
                 if (oldAuth != null) oldAuth.dispose();
                 connectionHandler.sendAuthReject(id);
               } catch (IOException e1) {
                 log.trace("Failed to send auth reject", e1);
               }
               return;
             }
             // clear out any old auth
             final Auth auth = new Auth(id, saslServer);
             Auth oldAuth = authMap.put(auth);
             if (oldAuth != null) oldAuth.dispose();
             final byte[] challenge;
             try {
               challenge = saslServer.evaluateResponse(initialResponse);
             } catch (SaslException e) {
               log.trace("Authentication failed at response evaluation", e);
               try {
                 connectionHandler.sendAuthReject(id);
               } catch (IOException e1) {
                 authMap.remove(auth);
                 auth.dispose();
                 log.trace("Failed to send auth reject", e1);
               }
               return;
             }
             if (saslServer.isComplete()) {
               try {
                 connectionHandler.sendAuthSuccess(id, challenge);
               } catch (IOException e) {
                 authMap.remove(auth);
                 auth.dispose();
                 log.trace("Failed to send auth success", e);
               }
               return;
             } else {
               try {
                 connectionHandler.sendAuthChallenge(id, challenge);
               } catch (IOException e) {
                 authMap.remove(auth);
                 auth.dispose();
                 log.trace("Failed to send auth challenge", e);
               }
               return;
             }
           });
 }
Example #20
0
 public String getUserName() {
   return saslServer.getAuthorizationID();
 }
Example #21
0
 public boolean isComplete() {
   return saslServer.isComplete();
 }
  /**
   * When writing octets to the resulting stream, if a security layer has been negotiated, each
   * piece of data written (by a single invocation of <code>write()</code>) will be encapsulated as
   * a SASL buffer, as defined in RFC 2222, and then written to the underlying <i>dest</i> output
   * stream.
   */
  public void write(byte[] b, int off, int len) throws IOException {
    if (b == null) {
      throw new NullPointerException("b");
    }
    if ((off < 0)
        || (off > b.length)
        || (len < 0)
        || ((off + len) > b.length)
        || ((off + len) < 0)) {
      throw new IndexOutOfBoundsException(
          "off="
              + String.valueOf(off)
              + ", len="
              + String.valueOf(len)
              + ", b.length="
              + String.valueOf(b.length));
    }
    if (len == 0) {
      return;
    }
    if (DEBUG && debuglevel > 8) debug(TRACE, "==> write()");

    int chunckSize, length, chunck = 1;
    byte[] output = null, result;
    if (DEBUG && debuglevel > 6)
      debug(TRACE, "About to wrap " + String.valueOf(len) + " byte(s)...");
    while (len > 0) {
      chunckSize = (len > maxRawSendSize ? maxRawSendSize : len);

      if (DEBUG && debuglevel > 6)
        debug(
            TRACE,
            "Outgoing buffer (before security) (hex): " + Util.dumpString(b, off, chunckSize));
      if (DEBUG && debuglevel > 6)
        debug(
            TRACE,
            "Outgoing buffer (before security) (str): \"" + new String(b, off, chunckSize) + "\"");

      if (client != null) output = client.wrap(b, off, chunckSize);
      else output = server.wrap(b, off, chunckSize);

      if (DEBUG && debuglevel > 6)
        debug(TRACE, "Outgoing buffer (after security) (hex): " + Util.dumpString(output));
      if (DEBUG && debuglevel > 6)
        debug(TRACE, "Outgoing buffer (after security) (str): \"" + new String(output) + "\"");

      length = output.length;
      result = new byte[length + 4];
      result[0] = (byte) (length >>> 24);
      result[1] = (byte) (length >>> 16);
      result[2] = (byte) (length >>> 8);
      result[3] = (byte) length;
      System.arraycopy(output, 0, result, 4, length);

      dest.write(result);

      off += chunckSize;
      len -= chunckSize;
      if (DEBUG && debuglevel > 6) debug(TRACE, "Wrapped chunck #" + String.valueOf(chunck));
      chunck++;
    }

    dest.flush();
    if (DEBUG && debuglevel > 8) debug(TRACE, "<== write()");
  }
Example #23
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);
   }
 }
Example #24
0
 @Override
 public boolean isSuccessful() {
   return server.isComplete();
 }
Example #25
0
 @Override
 public byte[] wrap(byte[] outgoing, int offset, int len) throws SaslException {
   return server.wrap(outgoing, offset, len);
 }
Example #26
0
 @Override
 public byte[] unwrap(byte[] incoming, int offset, int len) throws SaslException {
   return server.unwrap(incoming, offset, len);
 }
Example #27
0
 public String getAuthorizationID() {
   return server.getAuthorizationID();
 }
Example #28
0
 @After
 public void dispose() throws Exception {
   if (client != null) client.dispose();
   if (server != null) server.dispose();
   if (testKdc != null) testKdc.stopAll();
 }
  public static void main(String[] args) throws Exception {
    if (args.length == 0) {
      namesfile = null;
      auto = true;
    } else {
      int i = 0;
      if (args[i].equals("-m")) {
        i++;
        auto = false;
      }
      if (args.length > i) {
        namesfile = args[i++];
        if (args.length > i) {
          proxyfile = args[i];
        }
      } else {
        namesfile = null;
      }
    }

    CallbackHandler clntCbh = null;
    final CallbackHandler srvCbh = new PropertiesFileCallbackHandler(null, namesfile, proxyfile);

    Subject clntSubj = doLogin("client");
    Subject srvSubj = doLogin("server");
    final HashMap clntprops = new HashMap();
    final HashMap srvprops = new HashMap();

    clntprops.put(Sasl.QOP, "auth");
    srvprops.put(Sasl.QOP, "auth,auth-int,auth-conf");

    final SaslClient clnt =
        (SaslClient)
            Subject.doAs(
                clntSubj,
                new PrivilegedExceptionAction() {
                  public Object run() throws Exception {
                    return Sasl.createSaslClient(
                        new String[] {MECH}, null, PROTOCOL, SERVER_FQDN, clntprops, null);
                  }
                });

    if (verbose) {
      System.out.println(clntSubj);
      System.out.println(srvSubj);
    }
    final SaslServer srv =
        (SaslServer)
            Subject.doAs(
                srvSubj,
                new PrivilegedExceptionAction() {
                  public Object run() throws Exception {
                    return Sasl.createSaslServer(MECH, PROTOCOL, SERVER_FQDN, srvprops, srvCbh);
                  }
                });

    if (clnt == null) {
      throw new IllegalStateException("Unable to find client impl for " + MECH);
    }
    if (srv == null) {
      throw new IllegalStateException("Unable to find server impl for " + MECH);
    }

    byte[] response;
    byte[] challenge;

    response =
        (byte[])
            Subject.doAs(
                clntSubj,
                new PrivilegedExceptionAction() {
                  public Object run() throws Exception {
                    return (clnt.hasInitialResponse() ? clnt.evaluateChallenge(EMPTY) : EMPTY);
                  }
                });

    while (!clnt.isComplete() || !srv.isComplete()) {
      final byte[] responseCopy = response;
      challenge =
          (byte[])
              Subject.doAs(
                  srvSubj,
                  new PrivilegedExceptionAction() {
                    public Object run() throws Exception {
                      return srv.evaluateResponse(responseCopy);
                    }
                  });

      if (challenge != null) {
        final byte[] challengeCopy = challenge;
        response =
            (byte[])
                Subject.doAs(
                    clntSubj,
                    new PrivilegedExceptionAction() {
                      public Object run() throws Exception {
                        return clnt.evaluateChallenge(challengeCopy);
                      }
                    });
      }
    }

    if (clnt.isComplete() && srv.isComplete()) {
      if (verbose) {
        System.out.println("SUCCESS");
        System.out.println("authzid is " + srv.getAuthorizationID());
      }
    } else {
      throw new IllegalStateException(
          "FAILURE: mismatched state:"
              + " client complete? "
              + clnt.isComplete()
              + " server complete? "
              + srv.isComplete());
    }

    if (verbose) {
      System.out.println(clnt.getNegotiatedProperty(Sasl.QOP));
    }

    // Now try to use security layer

    byte[] clntBuf = new byte[] {0, 1, 2, 3};
    try {
      byte[] wrapped = clnt.wrap(clntBuf, 0, clntBuf.length);
      throw new Exception("clnt wrap should not be allowed w/no security layer");
    } catch (IllegalStateException e) {
      // expected
    }

    byte[] srvBuf = new byte[] {10, 11, 12, 13};
    try {
      byte[] wrapped = srv.wrap(srvBuf, 0, srvBuf.length);
      throw new Exception("srv wrap should not be allowed w/no security layer");
    } catch (IllegalStateException e) {
      // expected
    }

    try {
      byte[] unwrapped = clnt.unwrap(clntBuf, 0, clntBuf.length);
      throw new Exception("clnt wrap should not be allowed w/no security layer");
    } catch (IllegalStateException e) {
      // expected
    }

    try {
      byte[] unwrapped = srv.unwrap(srvBuf, 0, srvBuf.length);
      throw new Exception("srv wrap should not be allowed w/no security layer");
    } catch (IllegalStateException e) {
      // expected
    }
  }