javax.security.sasl.SaslException Java Examples
The following examples show how to use
javax.security.sasl.SaslException.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SaslOutputStream.java From openjdk-8 with GNU General Public License v2.0 | 6 votes |
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 #2
Source File: TSaslTransport.java From galaxy-sdk-java with Apache License 2.0 | 6 votes |
/** * 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 #3
Source File: AuthenticationOutcomeListener.java From Bats with Apache License 2.0 | 6 votes |
@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 #4
Source File: SaslInputStream.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
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 #5
Source File: ScramSaslClientTest.java From mongodb-async-driver with Apache License 2.0 | 6 votes |
/** * 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 #6
Source File: SaslNettyClient.java From herddb with Apache License 2.0 | 6 votes |
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 #7
Source File: AmqpConnectionIT.java From hono with Eclipse Public License 2.0 | 6 votes |
/** * 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 #8
Source File: AmqpConnectionIT.java From hono with Eclipse Public License 2.0 | 6 votes |
/** * 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 #9
Source File: AbstractScramSHAMechanismTestBase.java From qpid-jms with Apache License 2.0 | 6 votes |
@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 #10
Source File: SaslUnitTest.java From tutorials with MIT License | 6 votes |
@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 #11
Source File: SaslOutputStream.java From jdk8u-dev-jdk with GNU General Public License v2.0 | 6 votes |
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 #12
Source File: SaslOutputStream.java From jdk8u60 with GNU General Public License v2.0 | 6 votes |
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 #13
Source File: TSaslServerTransport.java From galaxy-sdk-java with Apache License 2.0 | 6 votes |
/** * 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 #14
Source File: TestSaslRPC.java From big-c with Apache License 2.0 | 6 votes |
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 #15
Source File: TSaslTransport.java From incubator-retired-blur with Apache License 2.0 | 6 votes |
/** * 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 #16
Source File: ClientServerTest.java From jdk8u_jdk with GNU General Public License v2.0 | 6 votes |
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 #17
Source File: TSaslTransport.java From galaxy-sdk-java with Apache License 2.0 | 6 votes |
/** * 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 #18
Source File: AbstractKerberosMgmtSaslTestBase.java From wildfly-core with GNU Lesser General Public License v2.1 | 6 votes |
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 #19
Source File: SaslInputStream.java From openjdk-jdk8u with GNU General Public License v2.0 | 6 votes |
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 #20
Source File: SaslRpcServer.java From big-c with Apache License 2.0 | 6 votes |
@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 #21
Source File: TSaslServerTransport.java From incubator-retired-blur with Apache License 2.0 | 6 votes |
/** * 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 #22
Source File: SaslNettyClient.java From herddb with Apache License 2.0 | 6 votes |
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 #23
Source File: SaslOutputStream.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 6 votes |
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 #24
Source File: SaslOutputStream.java From dragonwell8_jdk with GNU General Public License v2.0 | 6 votes |
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 #25
Source File: ScramSaslClient.java From mongodb-async-driver with Apache License 2.0 | 6 votes |
/** * 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 #26
Source File: CramMD5Base.java From jdk8u_jdk with GNU General Public License v2.0 | 5 votes |
/** * Unwraps the incoming buffer. CRAM-MD5 supports no security layer. * * @throws SaslException If attempt to use this method. */ public byte[] unwrap(byte[] incoming, 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 #27
Source File: CheckNegotiatedQOPs.java From dragonwell8_jdk with GNU General Public License v2.0 | 5 votes |
public byte[] evaluate(byte[] response) throws SaslException { if (saslServer.isComplete()) { throw new SaslException ("Server is already complete"); } return saslServer.evaluateResponse(response); }
Example #28
Source File: JiveSharedSecretSaslServer.java From Openfire with Apache License 2.0 | 5 votes |
@Override public byte[] wrap( byte[] outgoing, int offset, int len ) throws SaslException { if ( !isComplete() ) { throw new IllegalStateException( "Authentication exchange not completed." ); } throw new IllegalStateException( "SASL Mechanism '" + getMechanismName() + " does not support integrity nor privacy." ); }
Example #29
Source File: SaslResponseCallbackTest.java From mongodb-async-driver with Apache License 2.0 | 5 votes |
/** * Test method for {@link SaslResponseCallback#handle(Reply)}. * * @throws ExecutionException * On a test failure. * @throws InterruptedException * On a test failure. * @throws SaslException * On a test failure. */ @Test public void testHandleMissingDoneField() throws InterruptedException, ExecutionException, SaslException { final SaslClient mockClient = createMock(SaslClient.class); final Connection mockConnection = createMock(Connection.class); final FutureCallback<Boolean> results = new FutureCallback<Boolean>(); final SaslResponseCallback callback = new SaslResponseCallback( mockClient, mockConnection, results); expect(mockClient.evaluateChallenge(aryEq(new byte[1]))).andReturn( new byte[3]); final Document command = BuilderFactory.start().add("saslContinue", 1) .add("conversationId", 1L).add("payload", new byte[3]).build(); mockConnection.send(new Command(SaslResponseCallback.EXTERNAL, Command.COMMAND_COLLECTION, command), callback); expectLastCall(); replay(mockClient, mockConnection); final Document doc = BuilderFactory.start().add("ok", 1) .add("conversationId", 1L).add("payload", new byte[1]).build(); final Reply reply = new Reply(1, 0, 0, Collections.singletonList(doc), true, false, false, false); callback.handle(reply); verify(mockClient, mockConnection); try { results.get(1, TimeUnit.MICROSECONDS); fail("Should have timed out."); } catch (final TimeoutException good) { // Good. } }
Example #30
Source File: CramMD5Base.java From jdk8u-jdk with GNU General Public License v2.0 | 5 votes |
/** * Unwraps the incoming buffer. CRAM-MD5 supports no security layer. * * @throws SaslException If attempt to use this method. */ public byte[] unwrap(byte[] incoming, 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"); } }