@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; }
@Override public void handle(ChannelHandlerContext ctx, AmqpConnectionHandler connectionHandler) { ctx.fireChannelRead((BlockingTask) () -> { try { SaslServer saslServer = connectionHandler.getSaslServer(); if (saslServer != null) { byte[] challenge = saslServer.evaluateResponse(response.getBytes()); if (saslServer.isComplete()) { ctx.writeAndFlush(new ConnectionTune(256, 65535, 0)); } else { ctx.writeAndFlush(new ConnectionSecure(getChannel(), LongString.parse(challenge))); } } else { throw new SaslException("Sasl server hasn't been set during connection start"); } } catch (SaslException e) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Exception occurred while authenticating incoming connection ", e); } String replyText = "Authentication Failed"; ctx.writeAndFlush(new ConnectionClose(403, ShortString.parseString(replyText), 10, 21)); } }); }
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()); }
private void createSaslServer(String mechanism) throws IOException { this.saslMechanism = mechanism; if (!ScramMechanism.isScram(mechanism)) callbackHandler = new SaslServerCallbackHandler(jaasContext, kerberosNamer); else callbackHandler = new ScramServerCallbackHandler(credentialCache.cache(mechanism, ScramCredential.class)); callbackHandler.configure(configs, Mode.SERVER, subject, saslMechanism); if (mechanism.equals(SaslConfigs.GSSAPI_MECHANISM)) { saslServer = createSaslKerberosServer(callbackHandler, configs, subject); } else { try { saslServer = Subject.doAs(subject, new PrivilegedExceptionAction<SaslServer>() { public SaslServer run() throws SaslException { // 调用createSaslServer return Sasl.createSaslServer(saslMechanism, "kafka", host, configs, callbackHandler); } }); } catch (PrivilegedActionException e) { throw new SaslException("Kafka Server failed to create a SaslServer to interact with a client during session authentication", e.getCause()); } } }
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()); } } }
private void createSaslServer(String mechanism) throws IOException { this.saslMechanism = mechanism; callbackHandler = new SaslServerCallbackHandler(Configuration.getConfiguration(), kerberosNamer); callbackHandler.configure(configs, Mode.SERVER, subject, saslMechanism); if (mechanism.equals(SaslConfigs.GSSAPI_MECHANISM)) { if (subject.getPrincipals().isEmpty()) throw new IllegalArgumentException("subject must have at least one principal"); saslServer = createSaslKerberosServer(callbackHandler, configs); } else { try { saslServer = Subject.doAs(subject, new PrivilegedExceptionAction<SaslServer>() { public SaslServer run() throws SaslException { return Sasl.createSaslServer(saslMechanism, "kafka", host, configs, callbackHandler); } }); } catch (PrivilegedActionException e) { throw new SaslException("Kafka Server failed to create a SaslServer to interact with a client during session authentication", e.getCause()); } } }
public SaslServer createSaslServer(String mechanism, String protocol, String serverName, Map props, CallbackHandler cbh) throws SaslException { ServerMechanism result = getInstance(mechanism); if (result != null) { HashMap attributes = new HashMap(); if (props != null) attributes.putAll(props); attributes.put(Registry.SASL_PROTOCOL, protocol); attributes.put(Registry.SASL_SERVER_NAME, serverName); attributes.put(Registry.SASL_CALLBACK_HANDLER, cbh); result.init(attributes); } return result; }
@Override public <S extends ServerConnection<S>, T extends EnumLite> void process(SaslResponseContext<S, T> context) throws Exception { final SaslMessage.Builder challenge = SaslMessage.newBuilder(); final SaslServer saslServer = context.connection.getSaslServer(); final byte[] challengeBytes = evaluateResponse(saslServer, context.saslResponse.getData().toByteArray()); if (saslServer.isComplete()) { challenge.setStatus(SaslStatus.SASL_SUCCESS); if (challengeBytes != null) { challenge.setData(ByteString.copyFrom(challengeBytes)); } handleSuccess(context, challenge, saslServer); } else { challenge.setStatus(SaslStatus.SASL_IN_PROGRESS) .setData(ByteString.copyFrom(challengeBytes)); context.sender.send(new Response(context.saslResponseType, challenge.build())); } }
public SaslServerContext(final SaslServerFactory saslServerFactory, 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 saslServerFactory.createSaslServer(mech, SASL.SASL_PROTOCOL_NAME, serverName, props, callback_handler); } }); } catch (PrivilegedActionException e) { throw (SaslException)e.getCause(); // The createSaslServer will only throw this type of exception } } else { server = saslServerFactory.createSaslServer(mech, SASL.SASL_PROTOCOL_NAME, serverName, props, callback_handler); } }
@Override 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); }
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); }
/** * 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) { throw 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) { throw sendAndThrowMessage(NegotiationStatus.BAD, "Unsupported mechanism type " + mechanismName); } SaslServer saslServer = Sasl.createSaslServer(serverDefinition.mechanism, serverDefinition.protocol, serverDefinition.serverName, serverDefinition.props, serverDefinition.cbh); setSaslServer(saslServer); }
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 for <code>createSaslServer(String mechanism, * String protocol, String serverName, * Map prop, CallbackHandler cbh))</code> method * * Assertions: * returns SaslServer; * throws SaslServer for MECH-1 mechanism * * All providers are previously removed and * 1 new provider was added. */ public void testCreateServer04() throws SaslException { mProv = new Provider[] { (new SpiEngUtils()).new MyProvider( "MySaslServerProvider1", "Testing provider SaslServerFactory - 1", SRVSSRV .concat("MECH-1"), fServerClass) }; mProv[0].put(SRVSSRV.concat("MECH-2"), fServerClass); addProviders(); CallbackHandler cbH = new Sasl3Test.cbHandN(); SaslServer saslS = Sasl.createSaslServer("MECH-2", "protocol", null, null, cbH); assertNotNull("Null result for MECH-2", saslS); assertFalse("Incorrect isComplete() result", saslS.isComplete()); // try to create Server for wrong mechanism try { saslS = Sasl .createSaslServer("MECH-1", "protocol", null, null, cbH); fail("SaslException sould be thrown"); } catch (SaslException e) { } }
@Override public SaslServer createSaslServer(final String mechanism, final String protocol, final String serverName, final Map<String, ?> props, final CallbackHandler callbackHandler) throws SaslException { switch (mechanism) { case SaslSCRAM.NAME: return new SaslSCRAM(props, callbackHandler); case SaslSCRAMPlus.NAME: return new SaslSCRAMPlus(props, callbackHandler); case "PLAIN": return new SaslPLAIN(props, callbackHandler); case "ANONYMOUS": return new SaslANONYMOUS(props, callbackHandler); case "EXTERNAL": return new SaslEXTERNAL(props, callbackHandler); default: throw new SaslException("Mechanism not supported yet."); } }
/** * Creates a <code>SaslServer</code> implementing a supported mechanism using the parameters supplied. * * @param mechanism The non-null IANA-registered named of a SASL mechanism. * @param protocol The non-null string name of the protocol for which the authentication is being performed (e.g., "ldap"). * @param serverName The non-null fully qualified host name of the server to authenticate to. * @param props The possibly null set of properties used to select the SASL mechanism and to configure the authentication exchange of the selected mechanism. * @param cbh The possibly null callback handler to used by the SASL mechanisms to get further information from the application/library to complete the authentication. * @return A possibly null SaslServer created using the parameters supplied. If null, this factory cannot produce a SaslServer using the parameters supplied. * @throws SaslException If cannot create a SaslServer because of an error. */ public SaslServer createSaslServer(String mechanism, String protocol, String serverName, Map<String, ?> props, CallbackHandler cbh) throws SaslException { if (mechanism.equals(myMechs[PLAIN]) && PolicyUtils.checkPolicy(mechPolicies[PLAIN], props)) { if (cbh == null) { throw new SaslException("CallbackHandler with support for Password, Name, and AuthorizeCallback required"); } return new SaslServerPlainImpl(protocol, serverName, props, cbh); } else if (mechanism.equals(myMechs[CLEARSPACE]) && PolicyUtils.checkPolicy(mechPolicies[CLEARSPACE], props)) { if (cbh == null) { throw new SaslException("CallbackHandler with support for AuthorizeCallback required"); } return new ClearspaceSaslServer(); } return null; }
/** * @see org.wso2.andes.server.security.auth.manager.AuthenticationManager#authenticate(SaslServer, byte[]) */ 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 void disposeSaslServer(AMQProtocolSession ps) { SaslServer ss = ps.getSaslServer(); if (ss != null) { ps.setSaslServer(null); try { ss.dispose(); } catch (SaslException e) { _logger.error("Error disposing of Sasl server: " + e); } } }
protected void secure(final SaslServer ss, final Connection conn, final byte[] response) { final AuthenticationResult authResult = _appRegistry.getAuthenticationManager().authenticate(ss, response); final ServerConnection sconn = (ServerConnection) conn; if (AuthenticationStatus.SUCCESS.equals(authResult.getStatus())) { tuneAuthorizedConnection(sconn); sconn.setAuthorizedSubject(authResult.getSubject()); } else if (AuthenticationStatus.CONTINUE.equals(authResult.getStatus())) { connectionAuthContinue(sconn, authResult.getChallenge()); } else { connectionAuthFailed(sconn, authResult.getCause()); } }
protected void secure(final SaslServer ss, final Connection conn, final byte[] response) { try { byte[] challenge = ss.evaluateResponse(response); if (ss.isComplete()) { ss.dispose(); tuneAuthorizedConnection(conn); } else { connectionAuthContinue(conn, challenge); } } catch (SaslException e) { connectionAuthFailed(conn, e); } }