Java源码示例:org.apache.nifi.security.util.SslContextFactory

示例1
public SocketChannelDispatcher(final EventFactory<E> eventFactory,
                               final ChannelHandlerFactory<E, AsyncChannelDispatcher> handlerFactory,
                               final BlockingQueue<ByteBuffer> bufferPool,
                               final BlockingQueue<E> events,
                               final ComponentLog logger,
                               final int maxConnections,
                               final SSLContext sslContext,
                               final SslContextFactory.ClientAuth clientAuth,
                               final Charset charset) {
    this.eventFactory = eventFactory;
    this.handlerFactory = handlerFactory;
    this.bufferPool = bufferPool;
    this.events = events;
    this.logger = logger;
    this.maxConnections = maxConnections;
    this.keyQueue = new LinkedBlockingQueue<>(maxConnections);
    this.sslContext = sslContext;
    this.clientAuth = clientAuth;
    this.charset = charset;

    if (bufferPool == null || bufferPool.size() == 0 || bufferPool.size() != maxConnections) {
        throw new IllegalArgumentException(
                "A pool of available ByteBuffers equal to the maximum number of connections is required");
    }
}
 
示例2
@Override
protected ChannelDispatcher createDispatcher(final ProcessContext context, final BlockingQueue<StandardEvent> events)
        throws IOException {

    final int maxConnections = context.getProperty(MAX_CONNECTIONS).asInteger();
    final int bufferSize = context.getProperty(RECV_BUFFER_SIZE).asDataSize(DataUnit.B).intValue();
    final Charset charSet = Charset.forName(context.getProperty(CHARSET).getValue());

    // initialize the buffer pool based on max number of connections and the buffer size
    final BlockingQueue<ByteBuffer> bufferPool = createBufferPool(maxConnections, bufferSize);

    // if an SSLContextService was provided then create an SSLContext to pass down to the dispatcher
    SSLContext sslContext = null;
    SslContextFactory.ClientAuth clientAuth = null;

    final SSLContextService sslContextService = context.getProperty(SSL_CONTEXT_SERVICE).asControllerService(SSLContextService.class);
    if (sslContextService != null) {
        final String clientAuthValue = context.getProperty(CLIENT_AUTH).getValue();
        sslContext = sslContextService.createSSLContext(SSLContextService.ClientAuth.valueOf(clientAuthValue));
        clientAuth = SslContextFactory.ClientAuth.valueOf(clientAuthValue);
    }

    final EventFactory<StandardEvent> eventFactory = new StandardEventFactory();
    final ChannelHandlerFactory<StandardEvent<SocketChannel>, AsyncChannelDispatcher> handlerFactory = new SocketChannelHandlerFactory<>();
    return new SocketChannelDispatcher(eventFactory, handlerFactory, bufferPool, events, getLogger(), maxConnections, sslContext, clientAuth, charSet);
}
 
示例3
@Before
public void startServer() throws IOException, TlsException {
    tempConfigFilePath = "./target/TestHttpNotificationService-config.xml";

    Files.deleteIfExists(Paths.get(tempConfigFilePath));

    mockWebServer = new MockWebServer();

    TlsConfiguration tlsConfiguration = new TlsConfiguration("./src/test/resources/keystore.jks", "passwordpassword", null, "JKS",
            "./src/test/resources/truststore.jks", "passwordpassword", "JKS", CertificateUtils.getHighestCurrentSupportedTlsProtocolVersion());
    final SSLContext sslContext = SslContextFactory.createSslContext(tlsConfiguration, SslContextFactory.ClientAuth.REQUIRED);
    mockWebServer.useHttps(sslContext.getSocketFactory(), false);

    String configFileOutput = CONFIGURATION_FILE_TEXT.replace("${test.server}", String.valueOf(mockWebServer.url("/")));
    IOUtil.writeText(configFileOutput, new File(tempConfigFilePath));
}
 
示例4
public static SSLContext getConfiguredSslContext(final NonComponentConfigurationContext configurationContext) {
    final String rawKeystore = configurationContext.getProperty("TLS - Keystore");
    final String rawKeystorePassword = configurationContext.getProperty("TLS - Keystore Password");
    // TODO: Should support different key password
    final String rawKeystoreType = configurationContext.getProperty("TLS - Keystore Type");
    final String rawTruststore = configurationContext.getProperty("TLS - Truststore");
    final String rawTruststorePassword = configurationContext.getProperty("TLS - Truststore Password");
    final String rawTruststoreType = configurationContext.getProperty("TLS - Truststore Type");
    final String rawClientAuth = configurationContext.getProperty("TLS - Client Auth");
    final String rawProtocol = configurationContext.getProperty("TLS - Protocol");

    try {
        TlsConfiguration tlsConfiguration = new TlsConfiguration(rawKeystore, rawKeystorePassword, null, rawKeystoreType, rawTruststore, rawTruststorePassword, rawTruststoreType, rawProtocol);
        ClientAuth clientAuth = ClientAuth.isValidClientAuthType(rawClientAuth) ? ClientAuth.valueOf(rawClientAuth) : ClientAuth.NONE;
        return SslContextFactory.createSslContext(tlsConfiguration, clientAuth);
    } catch (TlsException e) {
        logger.error("Encountered an error configuring TLS for LDAP identity provider: {}", e.getLocalizedMessage());
        throw new ProviderCreationException("Error configuring TLS for LDAP identity provider", e);
    }
}
 
示例5
private SSLContext getConfiguredSslContext(final AuthorizerConfigurationContext configurationContext) {
    final String rawKeystore = configurationContext.getProperty("TLS - Keystore").getValue();
    final String rawKeystorePassword = configurationContext.getProperty("TLS - Keystore Password").getValue();
    final String rawKeystoreType = configurationContext.getProperty("TLS - Keystore Type").getValue();
    final String rawTruststore = configurationContext.getProperty("TLS - Truststore").getValue();
    final String rawTruststorePassword = configurationContext.getProperty("TLS - Truststore Password").getValue();
    final String rawTruststoreType = configurationContext.getProperty("TLS - Truststore Type").getValue();
    final String rawClientAuth = configurationContext.getProperty("TLS - Client Auth").getValue();
    final String rawProtocol = configurationContext.getProperty("TLS - Protocol").getValue();

    try {
        TlsConfiguration tlsConfiguration = new TlsConfiguration(rawKeystore, rawKeystorePassword, null, rawKeystoreType, rawTruststore, rawTruststorePassword, rawTruststoreType, rawProtocol);
        ClientAuth clientAuth = ClientAuth.isValidClientAuthType(rawClientAuth) ? ClientAuth.valueOf(rawClientAuth) : ClientAuth.NONE;
        return SslContextFactory.createSslContext(tlsConfiguration, clientAuth);
    } catch (TlsException e) {
        logger.error("Encountered an error configuring TLS for LDAP user group provider: {}", e.getLocalizedMessage());
        throw new ProviderCreationException("Error configuring TLS for LDAP user group provider", e);
    }
}
 
示例6
public SocketChannelDispatcher(final EventFactory<E> eventFactory,
                               final ChannelHandlerFactory<E, AsyncChannelDispatcher> handlerFactory,
                               final BlockingQueue<ByteBuffer> bufferPool,
                               final BlockingQueue<E> events,
                               final ComponentLog logger,
                               final int maxConnections,
                               final SSLContext sslContext,
                               final SslContextFactory.ClientAuth clientAuth,
                               final Charset charset) {
    this.eventFactory = eventFactory;
    this.handlerFactory = handlerFactory;
    this.bufferPool = bufferPool;
    this.events = events;
    this.logger = logger;
    this.maxConnections = maxConnections;
    this.keyQueue = new LinkedBlockingQueue<>(maxConnections);
    this.sslContext = sslContext;
    this.clientAuth = clientAuth;
    this.charset = charset;

    if (bufferPool == null || bufferPool.size() == 0 || bufferPool.size() != maxConnections) {
        throw new IllegalArgumentException(
                "A pool of available ByteBuffers equal to the maximum number of connections is required");
    }
}
 
示例7
public SocketChannelRecordReaderDispatcher(final ServerSocketChannel serverSocketChannel,
                                           final SSLContext sslContext,
                                           final SslContextFactory.ClientAuth clientAuth,
                                           final int socketReadTimeout,
                                           final int receiveBufferSize,
                                           final int maxConnections,
                                           final RecordReaderFactory readerFactory,
                                           final BlockingQueue<SocketChannelRecordReader> recordReaders,
                                           final ComponentLog logger) {
    this.serverSocketChannel = serverSocketChannel;
    this.sslContext = sslContext;
    this.clientAuth = clientAuth;
    this.socketReadTimeout = socketReadTimeout;
    this.receiveBufferSize = receiveBufferSize;
    this.maxConnections = maxConnections;
    this.readerFactory = readerFactory;
    this.recordReaders = recordReaders;
    this.logger = logger;
}
 
示例8
@Override
protected ChannelSender createSender(ProcessContext context) throws IOException {
    final int port = context.getProperty(PORT).evaluateAttributeExpressions().asInteger();
    final String host = context.getProperty(HOSTNAME).evaluateAttributeExpressions().getValue();
    final String protocol = context.getProperty(PROTOCOL).getValue();
    final int timeout = context.getProperty(TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue();
    final int maxSendBuffer = context.getProperty(MAX_SOCKET_SEND_BUFFER_SIZE).asDataSize(DataUnit.B).intValue();
    final SSLContextService sslContextService = context.getProperty(SSL_CONTEXT_SERVICE).asControllerService(SSLContextService.class);

    SSLContext sslContext = null;
    if (sslContextService != null) {
        sslContext = sslContextService.createSSLContext(SslContextFactory.ClientAuth.REQUIRED);
    }

    return createSender(protocol, host, port, timeout, maxSendBuffer, sslContext);
}
 
示例9
/**
 * Creates a concrete instance of a ChannelSender object to use for sending messages over a TCP stream.
 *
 * @param context
 *            - the current process context.
 *
 * @return ChannelSender object.
 */
@Override
protected ChannelSender createSender(final ProcessContext context) throws IOException {
    final String protocol = TCP_VALUE.getValue();
    final String hostname = context.getProperty(HOSTNAME).evaluateAttributeExpressions().getValue();
    final int port = context.getProperty(PORT).evaluateAttributeExpressions().asInteger();
    final int timeout = context.getProperty(TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue();
    final int bufferSize = context.getProperty(MAX_SOCKET_SEND_BUFFER_SIZE).asDataSize(DataUnit.B).intValue();
    final SSLContextService sslContextService = (SSLContextService) context.getProperty(SSL_CONTEXT_SERVICE).asControllerService();

    SSLContext sslContext = null;
    if (sslContextService != null) {
        sslContext = sslContextService.createSSLContext(SslContextFactory.ClientAuth.REQUIRED);
    }

    return createSender(protocol, hostname, port, timeout, bufferSize, sslContext);
}
 
示例10
protected ChannelDispatcher createChannelReader(final ProcessContext context, final String protocol, final BlockingQueue<ByteBuffer> bufferPool,
                                                final BlockingQueue<RawSyslogEvent> events, final int maxConnections,
                                                final SSLContextService sslContextService, final Charset charset) throws IOException {

    final EventFactory<RawSyslogEvent> eventFactory = new RawSyslogEventFactory();

    if (UDP_VALUE.getValue().equals(protocol)) {
        return new DatagramChannelDispatcher(eventFactory, bufferPool, events, getLogger());
    } else {
        // if an SSLContextService was provided then create an SSLContext to pass down to the dispatcher
        SSLContext sslContext = null;
        SslContextFactory.ClientAuth clientAuth = null;

        if (sslContextService != null) {
            final String clientAuthValue = context.getProperty(CLIENT_AUTH).getValue();
            sslContext = sslContextService.createSSLContext(SslContextFactory.ClientAuth.valueOf(clientAuthValue));
            clientAuth = SslContextFactory.ClientAuth.valueOf(clientAuthValue);
        }

        final ChannelHandlerFactory<RawSyslogEvent<SocketChannel>, AsyncChannelDispatcher> handlerFactory = new SocketChannelHandlerFactory<>();
        return new SocketChannelDispatcher(eventFactory, handlerFactory, bufferPool, events, getLogger(), maxConnections, sslContext, clientAuth, charset);
    }
}
 
示例11
@Override
protected ChannelDispatcher createDispatcher(final ProcessContext context, final BlockingQueue<StandardEvent> events)
        throws IOException {

    final int maxConnections = context.getProperty(MAX_CONNECTIONS).asInteger();
    final int bufferSize = context.getProperty(RECV_BUFFER_SIZE).asDataSize(DataUnit.B).intValue();
    final Charset charSet = Charset.forName(context.getProperty(CHARSET).getValue());

    // initialize the buffer pool based on max number of connections and the buffer size
    final BlockingQueue<ByteBuffer> bufferPool = createBufferPool(maxConnections, bufferSize);

    // if an SSLContextService was provided then create an SSLContext to pass down to the dispatcher
    SSLContext sslContext = null;
    SslContextFactory.ClientAuth clientAuth = null;

    final SSLContextService sslContextService = context.getProperty(SSL_CONTEXT_SERVICE).asControllerService(SSLContextService.class);
    if (sslContextService != null) {
        final String clientAuthValue = context.getProperty(CLIENT_AUTH).getValue();
        sslContext = sslContextService.createSSLContext(SslContextFactory.ClientAuth.valueOf(clientAuthValue));
        clientAuth = SslContextFactory.ClientAuth.valueOf(clientAuthValue);
    }

    final EventFactory<StandardEvent> eventFactory = new StandardEventFactory();
    final ChannelHandlerFactory<StandardEvent<SocketChannel>, AsyncChannelDispatcher> handlerFactory = new SocketChannelHandlerFactory<>();
    return new SocketChannelDispatcher(eventFactory, handlerFactory, bufferPool, events, getLogger(), maxConnections, sslContext, clientAuth, charSet);
}
 
示例12
protected ChannelSender createSender(final SSLContextService sslContextService, final String protocol, final String host,
                                     final int port, final int maxSendBufferSize, final int timeout)
        throws IOException {

    ChannelSender sender;
    if (protocol.equals(UDP_VALUE.getValue())) {
        sender = new DatagramChannelSender(host, port, maxSendBufferSize, getLogger());
    } else {
        // if an SSLContextService is provided then we make a secure sender
        if (sslContextService != null) {
            final SSLContext sslContext = sslContextService.createSSLContext(SslContextFactory.ClientAuth.REQUIRED);
            sender = new SSLSocketChannelSender(host, port, maxSendBufferSize, sslContext, getLogger());
        } else {
            sender = new SocketChannelSender(host, port, maxSendBufferSize, getLogger());
        }
    }
    sender.setTimeout(timeout);
    sender.open();
    return sender;
}
 
示例13
@Test
public void testTLSClientAuthRequiredAndClientCertProvided() throws InitializationException, IOException, InterruptedException, TlsException {

    runner.setProperty(ListenTCPRecord.CLIENT_AUTH, SslContextFactory.ClientAuth.REQUIRED.name());
    configureProcessorSslContextService();

    // Make an SSLContext with a key and trust store to send the test messages
    final SSLContext clientSslContext = SslContextFactory.createSslContext(clientTlsConfiguration);

    runTCP(DATA, 1, clientSslContext);

    final List<MockFlowFile> mockFlowFiles = runner.getFlowFilesForRelationship(ListenTCPRecord.REL_SUCCESS);
    Assert.assertEquals(1, mockFlowFiles.size());

    final String content = new String(mockFlowFiles.get(0).toByteArray(), StandardCharsets.UTF_8);
    Assert.assertNotNull(content);
    Assert.assertTrue(content.contains("This is a test " + 1));
    Assert.assertTrue(content.contains("This is a test " + 2));
    Assert.assertTrue(content.contains("This is a test " + 3));
}
 
示例14
@Test
public void testTLSClientAuthNoneAndClientCertNotProvided() throws InitializationException, IOException, InterruptedException, TlsException {

    runner.setProperty(ListenTCPRecord.CLIENT_AUTH, SslContextFactory.ClientAuth.NONE.name());
    configureProcessorSslContextService();

    // Make an SSLContext that only has the trust store, this should work since the processor has client auth NONE
    final SSLContext clientSslContext = SslContextFactory.createSslContext(trustOnlyTlsConfiguration);

    runTCP(DATA, 1, clientSslContext);

    final List<MockFlowFile> mockFlowFiles = runner.getFlowFilesForRelationship(ListenTCPRecord.REL_SUCCESS);
    Assert.assertEquals(1, mockFlowFiles.size());

    final String content = new String(mockFlowFiles.get(0).toByteArray(), StandardCharsets.UTF_8);
    Assert.assertNotNull(content);
    Assert.assertTrue(content.contains("This is a test " + 1));
    Assert.assertTrue(content.contains("This is a test " + 2));
    Assert.assertTrue(content.contains("This is a test " + 3));
}
 
示例15
@Test
public void testTLSClientAuthRequiredAndClientCertProvided() throws InitializationException, IOException, InterruptedException,
        TlsException {

    runner.setProperty(ListenTCP.CLIENT_AUTH, SslContextFactory.ClientAuth.REQUIRED.name());
    configureProcessorSslContextService();

    final List<String> messages = new ArrayList<>();
    messages.add("This is message 1\n");
    messages.add("This is message 2\n");
    messages.add("This is message 3\n");
    messages.add("This is message 4\n");
    messages.add("This is message 5\n");

    // Make an SSLContext with a key and trust store to send the test messages
    final SSLContext clientSslContext = SslContextFactory.createSslContext(clientTlsConfiguration, SslContextFactory.ClientAuth.NONE);

    runTCP(messages, messages.size(), clientSslContext);

    List<MockFlowFile> mockFlowFiles = runner.getFlowFilesForRelationship(ListenTCP.REL_SUCCESS);
    for (int i = 0; i < mockFlowFiles.size(); i++) {
        mockFlowFiles.get(i).assertContentEquals("This is message " + (i + 1));
    }
}
 
示例16
@Test
public void testTLSClientAuthRequiredAndClientCertNotProvided() throws InitializationException, TlsException {

    runner.setProperty(ListenTCP.CLIENT_AUTH, SslContextFactory.ClientAuth.REQUIRED.name());
    configureProcessorSslContextService();

    final List<String> messages = new ArrayList<>();
    messages.add("This is message 1\n");
    messages.add("This is message 2\n");
    messages.add("This is message 3\n");
    messages.add("This is message 4\n");
    messages.add("This is message 5\n");

    // Make an SSLContext that only has the trust store, this should not work since the processor has client auth REQUIRED
    final SSLContext clientSslContext = SslContextFactory.createSslContext(trustOnlyTlsConfiguration);

    try {
        runTCP(messages, messages.size(), clientSslContext);
        Assert.fail("Should have thrown exception");
    } catch (Exception e) {

    }
}
 
示例17
@Test
public void testTLSClientAuthNoneAndClientCertNotProvided() throws InitializationException, IOException, InterruptedException, TlsException {

    runner.setProperty(ListenTCP.CLIENT_AUTH, SslContextFactory.ClientAuth.NONE.name());
    configureProcessorSslContextService();

    final List<String> messages = new ArrayList<>();
    messages.add("This is message 1\n");
    messages.add("This is message 2\n");
    messages.add("This is message 3\n");
    messages.add("This is message 4\n");
    messages.add("This is message 5\n");

    // Make an SSLContext that only has the trust store, this should not work since the processor has client auth REQUIRED
    final SSLContext clientSslContext = SslContextFactory.createSslContext(trustOnlyTlsConfiguration);

    runTCP(messages, messages.size(), clientSslContext);

    List<MockFlowFile> mockFlowFiles = runner.getFlowFilesForRelationship(ListenTCP.REL_SUCCESS);
    for (int i = 0; i < mockFlowFiles.size(); i++) {
        mockFlowFiles.get(i).assertContentEquals("This is message " + (i + 1));
    }
}
 
示例18
@Override
protected ChannelDispatcher createDispatcher(final ProcessContext context, final BlockingQueue<LumberjackEvent> events) throws IOException {
    final EventFactory<LumberjackEvent> eventFactory = new LumberjackEventFactory();
    final ChannelHandlerFactory<LumberjackEvent, AsyncChannelDispatcher> handlerFactory = new LumberjackSocketChannelHandlerFactory<>();

    final int maxConnections = context.getProperty(MAX_CONNECTIONS).asInteger();
    final int bufferSize = context.getProperty(RECV_BUFFER_SIZE).asDataSize(DataUnit.B).intValue();
    final Charset charSet = Charset.forName(context.getProperty(CHARSET).getValue());

    // initialize the buffer pool based on max number of connections and the buffer size
    final BlockingQueue<ByteBuffer> bufferPool = createBufferPool(maxConnections, bufferSize);

    // if an SSLContextService was provided then create an SSLContext to pass down to the dispatcher
    SSLContext sslContext = null;
    final SSLContextService sslContextService = context.getProperty(SSL_CONTEXT_SERVICE).asControllerService(SSLContextService.class);
    if (sslContextService != null) {
        sslContext = sslContextService.createSSLContext(SslContextFactory.ClientAuth.REQUIRED);
    }

    // if we decide to support SSL then get the context and pass it in here
    return new SocketChannelDispatcher<>(eventFactory, handlerFactory, bufferPool, events,
        getLogger(), maxConnections, sslContext, charSet);
}
 
示例19
public SocketChannelDispatcher(final EventFactory<E> eventFactory,
                               final ChannelHandlerFactory<E, AsyncChannelDispatcher> handlerFactory,
                               final BlockingQueue<ByteBuffer> bufferPool,
                               final BlockingQueue<E> events,
                               final ComponentLog logger,
                               final int maxConnections,
                               final SSLContext sslContext,
                               final Charset charset) {
    this(eventFactory, handlerFactory, bufferPool, events, logger, maxConnections, sslContext, SslContextFactory.ClientAuth.REQUIRED, charset);
}
 
示例20
private void verifySslConfig(final ValidationContext validationContext) throws ProcessException {
    final String protocol = validationContext.getProperty(SSL_ALGORITHM).getValue();
    try {
        final PropertyValue keyPasswdProp = validationContext.getProperty(KEY_PASSWORD);
        final char[] keyPassword = keyPasswdProp.isSet() ? keyPasswdProp.getValue().toCharArray() : null;

        final String keystoreFile = validationContext.getProperty(KEYSTORE).getValue();
        if (keystoreFile == null) {
            SslContextFactory.createTrustSslContext(
                    validationContext.getProperty(TRUSTSTORE).getValue(),
                    validationContext.getProperty(TRUSTSTORE_PASSWORD).getValue().toCharArray(),
                    validationContext.getProperty(TRUSTSTORE_TYPE).getValue(),
                    protocol);
            return;
        }
        final String truststoreFile = validationContext.getProperty(TRUSTSTORE).getValue();
        if (truststoreFile == null) {
            SslContextFactory.createSslContext(
                    validationContext.getProperty(KEYSTORE).getValue(),
                    validationContext.getProperty(KEYSTORE_PASSWORD).getValue().toCharArray(),
                    keyPassword,
                    validationContext.getProperty(KEYSTORE_TYPE).getValue(),
                    protocol);
            return;
        }

        SslContextFactory.createSslContext(
                validationContext.getProperty(KEYSTORE).getValue(),
                validationContext.getProperty(KEYSTORE_PASSWORD).getValue().toCharArray(),
                keyPassword,
                validationContext.getProperty(KEYSTORE_TYPE).getValue(),
                validationContext.getProperty(TRUSTSTORE).getValue(),
                validationContext.getProperty(TRUSTSTORE_PASSWORD).getValue().toCharArray(),
                validationContext.getProperty(TRUSTSTORE_TYPE).getValue(),
                org.apache.nifi.security.util.SslContextFactory.ClientAuth.REQUIRED,
                protocol);
    } catch (final Exception e) {
        throw new ProcessException(e);
    }
}
 
示例21
@Test
public void testCustomValidate() throws InitializationException {
    runner.setProperty(ListenTCP.PORT, "1");
    runner.assertValid();

    configureProcessorSslContextService();
    runner.setProperty(ListenTCP.CLIENT_AUTH, "");
    runner.assertNotValid();

    runner.setProperty(ListenTCP.CLIENT_AUTH, SslContextFactory.ClientAuth.REQUIRED.name());
    runner.assertValid();
}
 
示例22
@Test
public void testTLSClienAuthRequiredAndClientCertProvided() throws InitializationException, IOException, InterruptedException,
        UnrecoverableKeyException, CertificateException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {

    runner.setProperty(ListenTCP.CLIENT_AUTH, SSLContextService.ClientAuth.REQUIRED.name());
    configureProcessorSslContextService();

    final List<String> messages = new ArrayList<>();
    messages.add("This is message 1\n");
    messages.add("This is message 2\n");
    messages.add("This is message 3\n");
    messages.add("This is message 4\n");
    messages.add("This is message 5\n");

    // Make an SSLContext with a key and trust store to send the test messages
    final SSLContext clientSslContext = SslContextFactory.createSslContext(
            "src/test/resources/localhost-ks.jks",
            "localtest".toCharArray(),
            "jks",
            "src/test/resources/localhost-ts.jks",
            "localtest".toCharArray(),
            "jks",
            org.apache.nifi.security.util.SslContextFactory.ClientAuth.valueOf("NONE"),
            "TLS");

    runTCP(messages, messages.size(), clientSslContext);

    List<MockFlowFile> mockFlowFiles = runner.getFlowFilesForRelationship(ListenTCP.REL_SUCCESS);
    for (int i=0; i < mockFlowFiles.size(); i++) {
        mockFlowFiles.get(i).assertContentEquals("This is message " + (i + 1));
    }
}
 
示例23
@Test
public void testTLSClienAuthRequiredAndClientCertNotProvided() throws InitializationException, IOException, InterruptedException,
        UnrecoverableKeyException, CertificateException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {

    runner.setProperty(ListenTCP.CLIENT_AUTH, SSLContextService.ClientAuth.REQUIRED.name());
    configureProcessorSslContextService();

    final List<String> messages = new ArrayList<>();
    messages.add("This is message 1\n");
    messages.add("This is message 2\n");
    messages.add("This is message 3\n");
    messages.add("This is message 4\n");
    messages.add("This is message 5\n");

    // Make an SSLContext that only has the trust store, this should not work since the processor has client auth REQUIRED
    final SSLContext clientSslContext = SslContextFactory.createTrustSslContext(
            "src/test/resources/localhost-ts.jks",
            "localtest".toCharArray(),
            "jks",
            "TLS");

    try {
        runTCP(messages, messages.size(), clientSslContext);
        Assert.fail("Should have thrown exception");
    } catch (Exception e) {

    }
}
 
示例24
@Test
public void testTLSClienAuthNoneAndClientCertNotProvided() throws InitializationException, IOException, InterruptedException,
        UnrecoverableKeyException, CertificateException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {

    runner.setProperty(ListenTCP.CLIENT_AUTH, SSLContextService.ClientAuth.NONE.name());
    configureProcessorSslContextService();

    final List<String> messages = new ArrayList<>();
    messages.add("This is message 1\n");
    messages.add("This is message 2\n");
    messages.add("This is message 3\n");
    messages.add("This is message 4\n");
    messages.add("This is message 5\n");

    // Make an SSLContext that only has the trust store, this should not work since the processor has client auth REQUIRED
    final SSLContext clientSslContext = SslContextFactory.createTrustSslContext(
            "src/test/resources/localhost-ts.jks",
            "localtest".toCharArray(),
            "jks",
            "TLS");

    runTCP(messages, messages.size(), clientSslContext);

    List<MockFlowFile> mockFlowFiles = runner.getFlowFilesForRelationship(ListenTCP.REL_SUCCESS);
    for (int i=0; i < mockFlowFiles.size(); i++) {
        mockFlowFiles.get(i).assertContentEquals("This is message " + (i + 1));
    }
}
 
示例25
/**
 * Generates certificates with the tls-toolkit and then starts up the docker compose file
 */
@BeforeClass
public static void initCertificates() throws Exception {
    resourceDirectory = Paths.get(HierarchicalC2IntegrationTest.class.getClassLoader()
            .getResource("docker-compose-c2-hierarchical.yml").getFile()).getParent();
    certificatesDirectory = resourceDirectory.toAbsolutePath().resolve("certificates-c2-hierarchical");
    authoritativeFiles = resourceDirectory.resolve("c2").resolve("hierarchical").resolve("c2-authoritative").resolve("files");
    minifiEdge1Version2 = authoritativeFiles.resolve("edge1").resolve("raspi3").resolve("config.text.yml.v2");
    minifiEdge2Version2 = authoritativeFiles.resolve("edge2").resolve("raspi2").resolve("config.text.yml.v2");
    minifiEdge3Version2 = authoritativeFiles.resolve("edge3").resolve("raspi3").resolve("config.text.yml.v2");

    if (Files.exists(minifiEdge1Version2)) {
        Files.delete(minifiEdge1Version2);
    }
    if (Files.exists(minifiEdge2Version2)) {
        Files.delete(minifiEdge2Version2);
    }
    if (Files.exists(minifiEdge3Version2)) {
        Files.delete(minifiEdge3Version2);
    }

    List<String> toolkitCommandLine = new ArrayList<>(Arrays.asList("-O", "-o", certificatesDirectory.toFile().getAbsolutePath(), "-S", "badKeystorePass", "-P", "badTrustPass"));
    for (String serverHostname : Arrays.asList("c2-authoritative", "minifi-edge1", "c2-edge2", "minifi-edge3")) {
        toolkitCommandLine.add("-n");
        toolkitCommandLine.add(serverHostname);
    }
    Files.createDirectories(certificatesDirectory);
    TlsToolkitStandaloneCommandLine tlsToolkitStandaloneCommandLine = new TlsToolkitStandaloneCommandLine();
    tlsToolkitStandaloneCommandLine.parse(toolkitCommandLine.toArray(new String[toolkitCommandLine.size()]));
    new TlsToolkitStandalone().createNifiKeystoresAndTrustStores(tlsToolkitStandaloneCommandLine.createConfig());

    trustSslContext = SslContextFactory.createTrustSslContext(certificatesDirectory.resolve("c2-authoritative")
            .resolve("truststore.jks").toFile().getAbsolutePath(), "badTrustPass".toCharArray(), "jks", "TLS");
    healthCheckSocketFactory = trustSslContext.getSocketFactory();

    docker.before();
}
 
示例26
protected SSLContext loadSslContext(String username, Path directory) throws GeneralSecurityException, IOException {
    char[] keystorePasswd;
    try (InputStream inputStream = Files.newInputStream(directory.resolve("CN=" + username + ".password"))) {
        keystorePasswd = IOUtils.toString(inputStream, StandardCharsets.UTF_8).toCharArray();
    }
    return SslContextFactory.createSslContext(
            directory.resolve("CN=" + username + ".p12").toFile().getAbsolutePath(),
            keystorePasswd,
            "PKCS12",
            certificatesDirectory.resolve("c2").resolve("truststore.jks").toFile().getAbsolutePath(),
            "badTrustPass".toCharArray(), "jks", SslContextFactory.ClientAuth.NONE, "TLS");
}
 
示例27
@Override
protected void init(final NotificationInitializationContext context) {
    final String url = context.getProperty(PROP_URL).evaluateAttributeExpressions().getValue();
    if (url == null || url.isEmpty()) {
        throw new IllegalArgumentException("Property, \"" + PROP_URL.getDisplayName() + "\", for the URL to POST notifications to must be set.");
    }

    urlReference.set(url);

    httpClientReference.set(null);

    final OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();

    Long connectTimeout = context.getProperty(PROP_CONNECTION_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS);
    Long writeTimeout = context.getProperty(PROP_WRITE_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS);

    // Set timeouts
    okHttpClientBuilder.connectTimeout(connectTimeout, TimeUnit.MILLISECONDS);
    okHttpClientBuilder.writeTimeout(writeTimeout, TimeUnit.MILLISECONDS);

    // check if the keystore is set and add the factory if so
    if (url.toLowerCase().startsWith("https")) {
        try {
            TlsConfiguration tlsConfiguration = createTlsConfigurationFromContext(context);
            final SSLSocketFactory sslSocketFactory = SslContextFactory.createSSLSocketFactory(tlsConfiguration);
            final X509TrustManager x509TrustManager = SslContextFactory.getX509TrustManager(tlsConfiguration);
            if (sslSocketFactory != null && x509TrustManager != null) {
                okHttpClientBuilder.sslSocketFactory(sslSocketFactory, x509TrustManager);
            } else {
                // If the TLS config couldn't be parsed, throw an exception
                throw new IllegalStateException("The HTTP notification service URL indicates HTTPS but the TLS properties are not valid");
            }
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }

    httpClientReference.set(okHttpClientBuilder.build());
}
 
示例28
public static SiteToSiteClient getClient(PropertyContext reportContext, ComponentLog logger, StateManager stateManager) {
    final SSLContextService sslContextService = reportContext.getProperty(SiteToSiteUtils.SSL_CONTEXT).asControllerService(SSLContextService.class);
    final SSLContext sslContext = sslContextService == null ? null : sslContextService.createSSLContext(SslContextFactory.ClientAuth.REQUIRED);
    final EventReporter eventReporter = (EventReporter) (severity, category, message) -> {
        switch (severity) {
            case WARNING:
                logger.warn(message);
                break;
            case ERROR:
                logger.error(message);
                break;
            default:
                break;
        }
    };
    final String destinationUrl = reportContext.getProperty(SiteToSiteUtils.DESTINATION_URL).evaluateAttributeExpressions().getValue();

    final SiteToSiteTransportProtocol mode = SiteToSiteTransportProtocol.valueOf(reportContext.getProperty(SiteToSiteUtils.TRANSPORT_PROTOCOL).getValue());
    final HttpProxy httpProxy = mode.equals(SiteToSiteTransportProtocol.RAW) || StringUtils.isEmpty(reportContext.getProperty(SiteToSiteUtils.HTTP_PROXY_HOSTNAME).getValue()) ? null
            : new HttpProxy(reportContext.getProperty(SiteToSiteUtils.HTTP_PROXY_HOSTNAME).getValue(), reportContext.getProperty(SiteToSiteUtils.HTTP_PROXY_PORT).asInteger(),
            reportContext.getProperty(SiteToSiteUtils.HTTP_PROXY_USERNAME).getValue(), reportContext.getProperty(SiteToSiteUtils.HTTP_PROXY_PASSWORD).getValue());

    // If no state manager was provided and this context supports retrieving it, do so
    if (stateManager == null && reportContext instanceof ReportingContext) {
        stateManager = ((ReportingContext) reportContext).getStateManager();
    }
    return new SiteToSiteClient.Builder()
            .urls(SiteToSiteRestApiClient.parseClusterUrls(destinationUrl))
            .portName(reportContext.getProperty(SiteToSiteUtils.PORT_NAME).getValue())
            .useCompression(reportContext.getProperty(SiteToSiteUtils.COMPRESS).asBoolean())
            .eventReporter(eventReporter)
            .sslContext(sslContext)
            .timeout(reportContext.getProperty(SiteToSiteUtils.TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS)
            .transportProtocol(mode)
            .httpProxy(httpProxy)
            .stateManager(stateManager)
            .build();
}
 
示例29
@OnEnabled
public void onEnabled(ConfigurationContext context) {
    resourceServerUrl = context.getProperty(ACCESS_TOKEN_URL).evaluateAttributeExpressions().getValue();

    sslContextService = context.getProperty(SSL_CONTEXT).asControllerService(SSLContextService.class);

    sslContext = sslContextService == null ? null : sslContextService.createSSLContext(SslContextFactory.ClientAuth.NONE);
}
 
示例30
@Override
public SSLContext createSSLContext(final SslContextFactory.ClientAuth clientAuth) throws ProcessException {
    try {
        return SslContextFactory.createSslContext(createTlsConfiguration(), clientAuth);
    } catch (TlsException e) {
        getLogger().error("Encountered an error creating the SSL context from the SSL context service: {}", new String[]{e.getLocalizedMessage()});
        throw new ProcessException("Error creating SSL context", e);
    }
}