Java Code Examples for javax.security.sasl.SaslException

The following examples show how to use javax.security.sasl.SaslException. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: Bats   Source File: AuthenticationOutcomeListener.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public <CC extends ClientConnection> SaslMessage process(SaslChallengeContext<CC> context) throws Exception {
  final SaslClient saslClient = context.connection.getSaslClient();

  if (saslClient.isComplete()) {
    handleSuccess(context);
    return null;
  } else {
    // server completed before client; so try once, fail otherwise
    evaluateChallenge(context.ugi, saslClient, context.challenge.getData().toByteArray()); // discard response

    if (saslClient.isComplete()) {
      handleSuccess(context);
      return null;
    } else {
      throw new SaslException("Server allegedly succeeded authentication, but client did not. Suspicious?");
    }
  }
}
 
Example 2
Source Project: openjdk-jdk9   Source File: SaslInputStream.java    License: GNU General Public License v2.0 6 votes vote down vote up
SaslInputStream(SaslClient sc, InputStream in) throws SaslException {
    super();
    this.in = in;
    this.sc = sc;

    String str = (String) sc.getNegotiatedProperty(Sasl.MAX_BUFFER);
    if (str != null) {
        try {
            recvMaxBufSize = Integer.parseInt(str);
        } catch (NumberFormatException e) {
            throw new SaslException(Sasl.MAX_BUFFER +
                " property must be numeric string: " + str);
        }
    }
    saslBuffer = new byte[recvMaxBufSize];
}
 
Example 3
Source Project: hono   Source File: AmqpConnectionIT.java    License: Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the adapter rejects connection attempts from devices
 * using wrong credentials.
 *
 * @param ctx The test context
 */
@Test
public void testConnectFailsForWrongCredentials(final VertxTestContext ctx) {

    // GIVEN a registered device
    final String tenantId = helper.getRandomTenantId();
    final String deviceId = helper.getRandomDeviceId(tenantId);
    final String password = "secret";
    final Tenant tenant = new Tenant();

    helper.registry
            .addDeviceForTenant(tenantId, tenant, deviceId, password)
    // WHEN the device tries to connect using a wrong password
    .compose(ok -> connectToAdapter(IntegrationTestSupport.getUsername(deviceId, tenantId), "wrong password"))
    .onComplete(ctx.failing(t -> {
        // THEN the connection is refused
        ctx.verify(() -> assertThat(t).isInstanceOf(SaslException.class));
        ctx.completeNow();
    }));
}
 
Example 4
Source Project: herddb   Source File: SaslNettyClient.java    License: Apache License 2.0 6 votes vote down vote up
private Subject loginClient() throws SaslException, PrivilegedActionException, LoginException {
    String clientSection = "HerdDBClient";
    AppConfigurationEntry[] entries = Configuration.getConfiguration().getAppConfigurationEntry(clientSection);
    if (entries == null) {
        LOG.log(Level.FINEST, "No JAAS Configuration found with section HerdDBClient");
        return null;
    }
    try {
        LoginContext loginContext = new LoginContext(clientSection, new ClientCallbackHandler(null));
        loginContext.login();
        LOG.log(Level.SEVERE, "Using JAAS Configuration subject: " + loginContext.getSubject());
        return loginContext.getSubject();
    } catch (LoginException error) {
        LOG.log(Level.SEVERE, "Error JAAS Configuration subject: " + error, error);
        return null;
    }
}
 
Example 5
Source Project: galaxy-sdk-java   Source File: TSaslTransport.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Read from the underlying transport. Unwraps the contents if a QOP was
 * negotiated during the SASL handshake.
 */
@Override
public int read(byte[] buf, int off, int len) throws TTransportException {
  if (!isOpen())
    throw new TTransportException("SASL authentication not complete");

  int got = readBuffer.read(buf, off, len);
  if (got > 0) {
    return got;
  }

  // Read another frame of data
  try {
    readFrame();
  } catch (SaslException e) {
    throw new TTransportException(e);
  }

  return readBuffer.read(buf, off, len);
}
 
Example 6
Source Project: hono   Source File: AmqpConnectionIT.java    License: Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the adapter rejects connection attempts from an unknown device for which auto-provisioning is
 * disabled.
 *
 * @param ctx The test context
 */
@Test
public void testConnectFailsIfAutoProvisioningIsDisabled(final VertxTestContext ctx) {
    final String tenantId = helper.getRandomTenantId();
    final SelfSignedCertificate deviceCert = SelfSignedCertificate.create(UUID.randomUUID().toString());

    // GIVEN a tenant configured with a trust anchor that does not allow auto-provisioning
    helper.getCertificate(deviceCert.certificatePath())
            .compose(cert -> {
                final var tenant = Tenants.createTenantForTrustAnchor(cert);
                tenant.getTrustedCertificateAuthorities().get(0).setAutoProvisioningEnabled(false);
                return helper.registry.addTenant(tenantId, tenant);
            })
            // WHEN a unknown device tries to connect to the adapter
            // using a client certificate with the trust anchor 
            // registered for the device's tenant
            .compose(ok -> connectToAdapter(deviceCert))
            .onComplete(ctx.failing(t -> {
                // THEN the connection is refused
                ctx.verify(() -> assertThat(t).isInstanceOf(SaslException.class));
                ctx.completeNow();
            }));
}
 
Example 7
Source Project: tutorials   Source File: SaslUnitTest.java    License: MIT License 6 votes vote down vote up
@Test
public void givenHandlers_whenStarted_thenAutenticationWorks() throws SaslException {

    byte[] challenge;
    byte[] response;

    challenge = saslServer.evaluateResponse(new byte[0]);
    response = saslClient.evaluateChallenge(challenge);

    challenge = saslServer.evaluateResponse(response);
    response = saslClient.evaluateChallenge(challenge);

    assertTrue(saslServer.isComplete());
    assertTrue(saslClient.isComplete());

    String qop = (String) saslClient.getNegotiatedProperty(Sasl.QOP);
    assertEquals("auth-conf", qop);

    byte[] outgoing = "Baeldung".getBytes();
    byte[] secureOutgoing = saslClient.wrap(outgoing, 0, outgoing.length);

    byte[] secureIncoming = secureOutgoing;
    byte[] incoming = saslServer.unwrap(secureIncoming, 0, secureIncoming.length);
    assertEquals("Baeldung", new String(incoming, StandardCharsets.UTF_8));
}
 
Example 8
SaslOutputStream(SaslClient sc, OutputStream out) throws SaslException {
    super(out);
    this.sc = sc;

    if (debug) {
        System.err.println("SaslOutputStream: " + out);
    }

    String str = (String) sc.getNegotiatedProperty(Sasl.RAW_SEND_SIZE);
    if (str != null) {
        try {
            rawSendSize = Integer.parseInt(str);
        } catch (NumberFormatException e) {
            throw new SaslException(Sasl.RAW_SEND_SIZE +
                " property must be numeric string: " + str);
        }
    }
}
 
Example 9
Source Project: jdk8u60   Source File: SaslOutputStream.java    License: GNU General Public License v2.0 6 votes vote down vote up
SaslOutputStream(SaslClient sc, OutputStream out) throws SaslException {
    super(out);
    this.sc = sc;

    if (debug) {
        System.err.println("SaslOutputStream: " + out);
    }

    String str = (String) sc.getNegotiatedProperty(Sasl.RAW_SEND_SIZE);
    if (str != null) {
        try {
            rawSendSize = Integer.parseInt(str);
        } catch (NumberFormatException e) {
            throw new SaslException(Sasl.RAW_SEND_SIZE +
                " property must be numeric string: " + str);
        }
    }
}
 
Example 10
Source Project: galaxy-sdk-java   Source File: TSaslServerTransport.java    License: 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 11
Source Project: mongodb-async-driver   Source File: ScramSaslClient.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Parses the message into the fields and returns the map of field names
 * (one character each) and values.
 *
 * @param message
 *            The message to parse.
 * @return The parsed fields from the message.
 * @throws SaslException
 *             In an invalid field is encountered.
 */
private Map<String, String> parse(final String message)
        throws SaslException {
    final Map<String, String> results = new HashMap<String, String>();

    final StringTokenizer tokens = new StringTokenizer(message, ",");
    while (tokens.hasMoreTokens()) {
        final String token = tokens.nextToken();

        if ((token.length() > 1) && (token.charAt(1) == '=')) {
            results.put(token.substring(0, 1), token.substring(2));
        }
        else {
            throw new SaslException("Invalid field ('" + token
                    + "') in the message: '" + message + "'.");
        }
    }

    return results;
}
 
Example 12
Source Project: big-c   Source File: TestSaslRPC.java    License: Apache License 2.0 6 votes vote down vote up
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());
}
 
Example 13
SaslOutputStream(SaslClient sc, OutputStream out) throws SaslException {
    super(out);
    this.sc = sc;

    if (debug) {
        System.err.println("SaslOutputStream: " + out);
    }

    String str = (String) sc.getNegotiatedProperty(Sasl.RAW_SEND_SIZE);
    if (str != null) {
        try {
            rawSendSize = Integer.parseInt(str);
        } catch (NumberFormatException e) {
            throw new SaslException(Sasl.RAW_SEND_SIZE +
                " property must be numeric string: " + str);
        }
    }
}
 
Example 14
SaslOutputStream(SaslClient sc, OutputStream out) throws SaslException {
    super(out);
    this.sc = sc;

    if (debug) {
        System.err.println("SaslOutputStream: " + out);
    }

    String str = (String) sc.getNegotiatedProperty(Sasl.RAW_SEND_SIZE);
    if (str != null) {
        try {
            rawSendSize = Integer.parseInt(str);
        } catch (NumberFormatException e) {
            throw new SaslException(Sasl.RAW_SEND_SIZE +
                " property must be numeric string: " + str);
        }
    }
}
 
Example 15
Source Project: herddb   Source File: SaslNettyClient.java    License: Apache License 2.0 6 votes vote down vote up
public byte[] evaluateChallenge(final byte[] saslToken) throws SaslException {
    if (saslToken == null) {
        throw new SaslException("saslToken is null.");
    }

    if (clientSubject != null) {
        try {
            final byte[] retval =
                    Subject.doAs(clientSubject, new PrivilegedExceptionAction<byte[]>() {
                        public byte[] run() throws SaslException {
                            return saslClient.evaluateChallenge(saslToken);
                        }
                    });
            return retval;
        } catch (PrivilegedActionException e) {
            e.printStackTrace();
            throw new SaslException("SASL/JAAS error", e);
        }
    } else {
        return saslClient.evaluateChallenge(saslToken);
    }
}
 
Example 16
/**
 * 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 17
Source Project: big-c   Source File: SaslRpcServer.java    License: 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 18
SaslInputStream(SaslClient sc, InputStream in) throws SaslException {
    super();
    this.in = in;
    this.sc = sc;

    String str = (String) sc.getNegotiatedProperty(Sasl.MAX_BUFFER);
    if (str != null) {
        try {
            recvMaxBufSize = Integer.parseInt(str);
        } catch (NumberFormatException e) {
            throw new SaslException(Sasl.MAX_BUFFER +
                " property must be numeric string: " + str);
        }
    }
    saslBuffer = new byte[recvMaxBufSize];
}
 
Example 19
protected void assertAuthenticationFails(String message, Class<? extends Exception> secondCauseClass, boolean withTls) {
    if (message == null) {
        message = "The failure of :whoami operation execution was expected, but the call passed";
    }
    final long startTime = System.currentTimeMillis();
    try {
        executeWhoAmI(withTls);
        fail(message);
    } catch (IOException | GeneralSecurityException e) {
        assertTrue("Connection reached its timeout (hang).",
                startTime + CONNECTION_TIMEOUT_IN_MS > System.currentTimeMillis());
        Throwable cause = e.getCause();
        assertThat("ConnectionException was expected as a cause when authentication fails", cause,
                is(instanceOf(ConnectException.class)));
        assertThat("Unexpected type of inherited exception for authentication failure", cause.getCause(),
                anyOf(is(instanceOf(SSLException.class)), is(instanceOf(SaslException.class)),
                        is(instanceOf(RedirectException.class))));
    }
}
 
Example 20
Source Project: galaxy-sdk-java   Source File: TSaslTransport.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Read a single frame of data from the underlying transport, unwrapping if
 * necessary.
 * 
 * @throws TTransportException
 *           Thrown if there's an error reading from the underlying transport.
 * @throws SaslException
 *           Thrown if there's an error unwrapping the data.
 */
private void readFrame() throws TTransportException, SaslException {
  int dataLength = readLength();

  if (dataLength < 0)
    throw new TTransportException("Read a negative frame size (" + dataLength + ")!");

  byte[] buff = new byte[dataLength];
  LOGGER.debug("{}: reading data length: {}", getRole(), dataLength);
  underlyingTransport.readAll(buff, 0, dataLength);
  if (shouldWrap) {
    buff = sasl.unwrap(buff, 0, buff.length);
    LOGGER.debug("data length after unwrap: {}", buff.length);
  }
  readBuffer.reset(buff);
}
 
Example 21
Source Project: openjdk-8   Source File: SaslOutputStream.java    License: GNU General Public License v2.0 6 votes vote down vote up
SaslOutputStream(SaslClient sc, OutputStream out) throws SaslException {
    super(out);
    this.sc = sc;

    if (debug) {
        System.err.println("SaslOutputStream: " + out);
    }

    String str = (String) sc.getNegotiatedProperty(Sasl.RAW_SEND_SIZE);
    if (str != null) {
        try {
            rawSendSize = Integer.parseInt(str);
        } catch (NumberFormatException e) {
            throw new SaslException(Sasl.RAW_SEND_SIZE +
                " property must be numeric string: " + str);
        }
    }
}
 
Example 22
Source Project: jdk8u_jdk   Source File: ClientServerTest.java    License: 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 23
Source Project: incubator-retired-blur   Source File: TSaslTransport.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Read from the underlying transport. Unwraps the contents if a QOP was
 * negotiated during the SASL handshake.
 */
@Override
public int read(byte[] buf, int off, int len) throws TTransportException {
  if (!isOpen())
    throw new TTransportException("SASL authentication not complete");

  int got = readBuffer.read(buf, off, len);
  if (got > 0) {
    return got;
  }

  // Read another frame of data
  try {
    readFrame();
  } catch (SaslException e) {
    throw new TTransportException(e);
  }

  return readBuffer.read(buf, off, len);
}
 
Example 24
@Test
public void testIncompleteExchange() throws Exception {
    Mechanism mechanism = getConfiguredMechanism();

    byte[] clientInitialResponse = mechanism.getInitialResponse();
    assertArrayEquals(expectedClientInitialResponse, clientInitialResponse);

    byte[] clientFinalMessage = mechanism.getChallengeResponse(serverFirstMessage);
    assertArrayEquals(expectedClientFinalMessage, clientFinalMessage);

    try {
        mechanism.verifyCompletion();
        fail("Exception not thrown");
    } catch (SaslException e) {
        // PASS
    }
}
 
Example 25
Source Project: mongodb-async-driver   Source File: ScramSaslClientTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Test method for {@link ScramSaslClient#createProof(byte[])}.
 *
 * @throws SaslException
 *             On a test failure.
 */
@Test()
public void testCreateProofWithMissingSalt() throws SaslException {
    final CallbackHandler handler = new TestHandler("user", "pencil");

    final ScramSaslClient client = new ScramSaslClient(handler);

    // To create the client nonce.
    final byte[] initial = client.createInitialMessage();
    final String initialMessage = new String(initial, ScramSaslClient.UTF_8);
    final String clientNonce = initialMessage.substring(initialMessage
            .indexOf(",r=") + 3);

    try {
        client.createProof(("r=" + clientNonce + "abcd,i=4096")
                .getBytes(ScramSaslClient.UTF_8));
        fail("Should have thrown a SaslException.");
    }
    catch (final SaslException expected) {
        assertThat(expected.getMessage(),
                is("Could not find the server's salt: 'r=" + clientNonce
                        + "abcd,i=4096'."));
    }
}
 
Example 26
Source Project: big-c   Source File: SaslOutputStream.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Disposes of any system resources or security-sensitive information Sasl
 * might be using.
 * 
 * @exception SaslException
 *              if a SASL error occurs.
 */
private void disposeSasl() throws SaslException {
  if (saslClient != null) {
    saslClient.dispose();
  }
  if (saslServer != null) {
    saslServer.dispose();
  }
}
 
Example 27
public void negotiate(SampleServer server) throws SaslException {

        byte[] challenge;
        byte[] response;

        response = (saslClient.hasInitialResponse () ?
                  saslClient.evaluateChallenge (new byte [0]) : new byte [0]);

        while (! saslClient.isComplete()) {
            challenge = server.evaluate(response);
            response = saslClient.evaluateChallenge(challenge);
        }
   }
 
Example 28
Source Project: jdk8u_jdk   Source File: CramMD5Base.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
  * Wraps the outgoing buffer. CRAM-MD5 supports no security layer.
  *
  * @throws SaslException If attempt to use this method.
  */
public byte[] wrap(byte[] outgoing, int offset, int len) throws SaslException {
    if (completed) {
        throw new IllegalStateException(
            "CRAM-MD5 supports neither integrity nor privacy");
    } else {
        throw new IllegalStateException(
            "CRAM-MD5 authentication not completed");
    }
}
 
Example 29
Source Project: SSMBlogv2   Source File: LoginController.java    License: MIT License 5 votes vote down vote up
@RequestMapping(value="/validatellogin")
public String validatelogin(@RequestParam(value="username", required=false)String username,
		@RequestParam(value="password",required=false)String password, HttpServletRequest request,
		HttpServletResponse response) throws SaslException {
		if(request.getSession().getAttribute("username") != null) {
			return "admin/backadmin";
		}
		if(service.validate(username, password)) {
			HttpSession session = request.getSession();
			session.setAttribute("username", username);
			return "admin/backadmin";
		}
		return "admin/loginfail";
}
 
Example 30
Source Project: hbase   Source File: SaslUtil.java    License: 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);
  }
}