javax.security.sasl.Sasl Java Examples

The following examples show how to use javax.security.sasl.Sasl. 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: SaslUnitTest.java    From tutorials with 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 #2
Source File: SaslInputStream.java    From dragonwell8_jdk with 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 File: FastSaslClientFactory.java    From Bats with Apache License 2.0 6 votes vote down vote up
private void refresh() {
  final Enumeration<SaslClientFactory> factories = Sasl.getSaslClientFactories();
  final Map<String, List<SaslClientFactory>> map = Maps.newHashMap();

  while (factories.hasMoreElements()) {
    final SaslClientFactory factory = factories.nextElement();
    // Passing null so factory is populated with all possibilities.  Properties passed when
    // instantiating a client are what really matter. See createSaslClient.
    for (final String mechanismName : factory.getMechanismNames(null)) {
      if (!map.containsKey(mechanismName)) {
        map.put(mechanismName, new ArrayList<SaslClientFactory>());
      }
      map.get(mechanismName).add(factory);
    }
  }

  clientFactories = ImmutableMap.copyOf(map);
  if (logger.isDebugEnabled()) {
    logger.debug("Registered sasl client factories: {}", clientFactories.keySet());
  }
}
 
Example #4
Source File: TestSaslRPC.java    From big-c with 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 #5
Source File: FastSaslServerFactory.java    From Bats with Apache License 2.0 6 votes vote down vote up
private void refresh() {
  final Enumeration<SaslServerFactory> factories = Sasl.getSaslServerFactories();
  final Map<String, List<SaslServerFactory>> map = Maps.newHashMap();

  while (factories.hasMoreElements()) {
    final SaslServerFactory factory = factories.nextElement();
    // Passing null so factory is populated with all possibilities.  Properties passed when
    // instantiating a server are what really matter. See createSaslServer.
    for (final String mechanismName : factory.getMechanismNames(null)) {
      if (!map.containsKey(mechanismName)) {
        map.put(mechanismName, new ArrayList<SaslServerFactory>());
      }
      map.get(mechanismName).add(factory);
    }
  }

  serverFactories = ImmutableMap.copyOf(map);
  if (logger.isDebugEnabled()) {
    logger.debug("Registered sasl server factories: {}", serverFactories.keySet());
  }
}
 
Example #6
Source File: GssSaslServerAuthenticationProvider.java    From hbase with Apache License 2.0 6 votes vote down vote up
@Override
public AttemptingUserProvidingSaslServer createServer(
    SecretManager<TokenIdentifier> secretManager,
    Map<String, String> saslProps) throws IOException {
  UserGroupInformation current = UserGroupInformation.getCurrentUser();
  String fullName = current.getUserName();
  LOG.debug("Server's Kerberos principal name is {}", fullName);
  String[] names = SaslUtil.splitKerberosName(fullName);
  if (names.length != 3) {
    throw new AccessDeniedException(
        "Kerberos principal does NOT contain an instance (hostname): " + fullName);
  }
  try {
    return current.doAs(new PrivilegedExceptionAction<AttemptingUserProvidingSaslServer>() {
      @Override
      public AttemptingUserProvidingSaslServer run() throws SaslException {
        return new AttemptingUserProvidingSaslServer(Sasl.createSaslServer(
            getSaslAuthMethod().getSaslMechanism(), names[0], names[1], saslProps,
            new SaslGssCallbackHandler()), () -> null);
      }
    });
  } catch (InterruptedException e) {
    Thread.currentThread().interrupt();
    throw new RuntimeException("Failed to construct GSS SASL server");
  }
}
 
Example #7
Source File: SaslInputStream.java    From TencentKona-8 with 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 #8
Source File: TSaslServerTransport.java    From incubator-retired-blur with 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 #9
Source File: TestSaslRPC.java    From hadoop with 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 #10
Source File: SaslInputStream.java    From hottub with 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 #11
Source File: FanOutOneBlockAsyncDFSOutputSaslHelper.java    From hbase with Apache License 2.0 6 votes vote down vote up
private void checkSaslComplete() throws IOException {
  if (!saslClient.isComplete()) {
    throw new IOException("Failed to complete SASL handshake");
  }
  Set<String> requestedQop =
      ImmutableSet.copyOf(Arrays.asList(saslProps.get(Sasl.QOP).split(",")));
  String negotiatedQop = getNegotiatedQop();
  LOG.debug(
    "Verifying QOP, requested QOP = " + requestedQop + ", negotiated QOP = " + negotiatedQop);
  if (!requestedQop.contains(negotiatedQop)) {
    throw new IOException(String.format("SASL handshake completed, but "
        + "channel does not have acceptable quality of protection, "
        + "requested = %s, negotiated = %s",
      requestedQop, negotiatedQop));
  }
}
 
Example #12
Source File: SaslOutputStream.java    From jdk8u60 with 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 #13
Source File: SaslOutputStream.java    From openjdk-8-source with 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 #14
Source File: TSaslServerTransport.java    From incubator-retired-blur with 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 #15
Source File: SaslOutputStream.java    From hottub with 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 #16
Source File: SaslOutputStream.java    From openjdk-jdk8u with 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 #17
Source File: SaslOutputStream.java    From openjdk-8 with 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 #18
Source File: CustomSaslAuthenticationProviderTestBase.java    From hbase with Apache License 2.0 5 votes vote down vote up
@Override
public AttemptingUserProvidingSaslServer
  createServer(SecretManager<TokenIdentifier> secretManager, Map<String, String> saslProps)
    throws IOException {
  return new AttemptingUserProvidingSaslServer(
    Sasl.createSaslServer(getSaslAuthMethod().getSaslMechanism(), null,
      SaslUtil.SASL_DEFAULT_REALM, saslProps, new InMemoryServerProviderCallbackHandler()),
    () -> null);
}
 
Example #19
Source File: CheckNegotiatedQOPs.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public SampleClient(String requestedQOPs) throws SaslException {

        Map<String,String> properties = new HashMap<String,String>();

        if (requestedQOPs != null) {
            properties.put(Sasl.QOP, requestedQOPs);
        }
        saslClient = Sasl.createSaslClient(new String[]{ DIGEST_MD5 }, null,
            "local", "127.0.0.1", properties, new SampleCallbackHandler());
    }
 
Example #20
Source File: PolicyUtils.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Determines whether a mechanism's characteristics, as defined in flags,
 * fits the security policy properties found in props.
 * @param flags The mechanism's security characteristics
 * @param props The security policy properties to check
 * @return true if passes; false if fails
 */
public static boolean checkPolicy(int flags, Map<String, ?> props) {
    if (props == null) {
        return true;
    }

    if ("true".equalsIgnoreCase((String)props.get(Sasl.POLICY_NOPLAINTEXT))
        && (flags&NOPLAINTEXT) == 0) {
        return false;
    }
    if ("true".equalsIgnoreCase((String)props.get(Sasl.POLICY_NOACTIVE))
        && (flags&NOACTIVE) == 0) {
        return false;
    }
    if ("true".equalsIgnoreCase((String)props.get(Sasl.POLICY_NODICTIONARY))
        && (flags&NODICTIONARY) == 0) {
        return false;
    }
    if ("true".equalsIgnoreCase((String)props.get(Sasl.POLICY_NOANONYMOUS))
        && (flags&NOANONYMOUS) == 0) {
        return false;
    }
    if ("true".equalsIgnoreCase((String)props.get(Sasl.POLICY_FORWARD_SECRECY))
        && (flags&FORWARD_SECRECY) == 0) {
        return false;
    }
    if ("true".equalsIgnoreCase((String)props.get(Sasl.POLICY_PASS_CREDENTIALS))
        && (flags&PASS_CREDENTIALS) == 0) {
        return false;
    }

    return true;
}
 
Example #21
Source File: CheckNegotiatedQOPs.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private void execute(boolean expectException) throws Exception {

        System.err.println ("Case #" + caseNumber);
        System.err.println ("client requested QOPs=" + requestedQOPs);
        System.err.println ("server supported QOPs=" + supportedQOPs);

        try {
            client.negotiate(server);

            if (expectException) {
                throw new
                    Exception("An exception was expected but none was thrown");
            }

        } catch (SaslException e) {

            if (expectException) {
                System.err.println(e);
                return;

            } else {
                throw e;
            }
        }

        System.err.println("client negotiated QOP=" +
            client.getSaslClient ().getNegotiatedProperty (Sasl.QOP));

        System.err.println("server negotiated QOP=" +
            server.getSaslServer ().getNegotiatedProperty (Sasl.QOP));

        System.err.println();
    }
 
Example #22
Source File: GssSaslClientAuthenticationProvider.java    From hbase with Apache License 2.0 5 votes vote down vote up
@Override
public SaslClient createClient(Configuration conf, InetAddress serverAddr,
    SecurityInfo securityInfo, Token<? extends TokenIdentifier> token, boolean fallbackAllowed,
    Map<String, String> saslProps) throws IOException {
  String serverPrincipal = getServerPrincipal(conf, securityInfo, serverAddr);
  LOG.debug("Setting up Kerberos RPC to server={}", serverPrincipal);
  String[] names = SaslUtil.splitKerberosName(serverPrincipal);
  if (names.length != 3) {
    throw new IOException("Kerberos principal '" + serverPrincipal
        + "' does not have the expected format");
  }
  return Sasl.createSaslClient(new String[] { getSaslAuthMethod().getSaslMechanism() }, null,
      names[0], names[1], saslProps, null);
}
 
Example #23
Source File: CheckNegotiatedQOPs.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public SampleServer(String supportedQOPs) throws SaslException {

        Map<String,String> properties = new HashMap<String,String>();

        if (supportedQOPs != null) {
            properties.put(Sasl.QOP, supportedQOPs);
        }
        saslServer = Sasl.createSaslServer(DIGEST_MD5, "local", "127.0.0.1",
            properties, new SampleCallbackHandler());
    }
 
Example #24
Source File: SaslRpcClient.java    From big-c with Apache License 2.0 5 votes vote down vote up
/**
 * Get SASL wrapped OutputStream if SASL QoP requires wrapping,
 * otherwise return original stream.  Can be called only after
 * saslConnect() has been called.
 * 
 * @param in - InputStream used to make the connection
 * @return InputStream that may be using SASL unwrap
 * @throws IOException
 */
public OutputStream getOutputStream(OutputStream out) throws IOException {
  if (useWrap()) {
    // the client and server negotiate a maximum buffer size that can be
    // wrapped
    String maxBuf = (String)saslClient.getNegotiatedProperty(Sasl.RAW_SEND_SIZE);
    out = new BufferedOutputStream(new WrappedOutputStream(out),
                                   Integer.parseInt(maxBuf));
  }
  return out;
}
 
Example #25
Source File: SaslRpcClient.java    From hadoop with Apache License 2.0 5 votes vote down vote up
/**
 * Get SASL wrapped OutputStream if SASL QoP requires wrapping,
 * otherwise return original stream.  Can be called only after
 * saslConnect() has been called.
 * 
 * @param in - InputStream used to make the connection
 * @return InputStream that may be using SASL unwrap
 * @throws IOException
 */
public OutputStream getOutputStream(OutputStream out) throws IOException {
  if (useWrap()) {
    // the client and server negotiate a maximum buffer size that can be
    // wrapped
    String maxBuf = (String)saslClient.getNegotiatedProperty(Sasl.RAW_SEND_SIZE);
    out = new BufferedOutputStream(new WrappedOutputStream(out),
                                   Integer.parseInt(maxBuf));
  }
  return out;
}
 
Example #26
Source File: ClientServerTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private SaslServer createSaslServer(String mechanism)
        throws SaslException {
    Map<String, String> props = new HashMap<>();
    props.put(Sasl.QOP, qop);
    return Sasl.createSaslServer(mechanism, PROTOCOL, host, props,
            callback);
}
 
Example #27
Source File: CustomSaslAuthenticationProviderTestBase.java    From hbase with Apache License 2.0 5 votes vote down vote up
@Override
public SaslClient createClient(Configuration conf, InetAddress serverAddr,
  SecurityInfo securityInfo, Token<? extends TokenIdentifier> token, boolean fallbackAllowed,
  Map<String, String> saslProps) throws IOException {
  return Sasl.createSaslClient(new String[] { MECHANISM }, null, null,
    SaslUtil.SASL_DEFAULT_REALM, saslProps, new InMemoryClientProviderCallbackHandler(token));
}
 
Example #28
Source File: CheckNegotiatedQOPs.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public SampleServer(String supportedQOPs) throws SaslException {

        Map<String,String> properties = new HashMap<String,String>();

        if (supportedQOPs != null) {
            properties.put(Sasl.QOP, supportedQOPs);
        }
        saslServer = Sasl.createSaslServer(DIGEST_MD5, "local", "127.0.0.1",
            properties, new SampleCallbackHandler());
    }
 
Example #29
Source File: CramMD5Base.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Retrieves the negotiated property.
 * This method can be called only after the authentication exchange has
 * completed (i.e., when <tt>isComplete()</tt> returns true); otherwise, a
 * <tt>SaslException</tt> is thrown.
 *
 * @return value of property; only QOP is applicable to CRAM-MD5.
 * @exception IllegalStateException if this authentication exchange has not completed
 */
public Object getNegotiatedProperty(String propName) {
    if (completed) {
        if (propName.equals(Sasl.QOP)) {
            return "auth";
        } else {
            return null;
        }
    } else {
        throw new IllegalStateException(
            "CRAM-MD5 authentication not completed");
    }
}
 
Example #30
Source File: SaslParticipant.java    From hadoop with Apache License 2.0 5 votes vote down vote up
/**
 * After successful SASL negotation, returns the negotiated quality of
 * protection.
 *
 * @return negotiated quality of protection
 */
public String getNegotiatedQop() {
  if (saslClient != null) {
    return (String) saslClient.getNegotiatedProperty(Sasl.QOP);
  } else {
    return (String) saslServer.getNegotiatedProperty(Sasl.QOP);
  }
}