aboutsummaryrefslogtreecommitdiffstats
path: root/security-utils/src/main/java/com/yahoo/security/SslContextBuilder.java
blob: 9b26b79a960fb4c27e0439bef30d7fde68f054da (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.security;

import com.yahoo.security.tls.TlsContext;

import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509ExtendedKeyManager;
import javax.net.ssl.X509ExtendedTrustManager;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.List;

import static java.util.Collections.singletonList;

/**
 * A builder for {@link SSLContext}.
 *
 * @author bjorncs
 */
public class SslContextBuilder {

    private KeyStoreSupplier trustStoreSupplier = () -> null;
    private KeyStoreSupplier keyStoreSupplier = () -> null;
    private char[] keyStorePassword;
    private TrustManagerFactory trustManagerFactory = TrustManagerUtils::createDefaultX509TrustManager;
    private KeyManagerFactory keyManagerFactory = KeyManagerUtils::createDefaultX509KeyManager;
    private X509ExtendedKeyManager keyManager;
    private X509ExtendedTrustManager trustManager;

    public SslContextBuilder() {}

    public SslContextBuilder withTrustStore(Path file, KeyStoreType trustStoreType) {
        this.trustStoreSupplier = () -> KeyStoreBuilder.withType(trustStoreType).fromFile(file).build();
        return this;
    }

    public SslContextBuilder withTrustStore(KeyStore trustStore) {
        this.trustStoreSupplier = () -> trustStore;
        return this;
    }

    public SslContextBuilder withTrustStore(X509Certificate caCertificate) {
        return withTrustStore(singletonList(caCertificate));
    }

    public SslContextBuilder withTrustStore(List<X509Certificate> caCertificates) {
        this.trustStoreSupplier = () -> createTrustStore(caCertificates);
        return this;
    }

    public SslContextBuilder withTrustStore(Path pemEncodedCaCertificates) {
        this.trustStoreSupplier = () -> {
            List<X509Certificate> caCertificates =
                    X509CertificateUtils.certificateListFromPem(new String(Files.readAllBytes(pemEncodedCaCertificates)));
            return createTrustStore(caCertificates);
        };
        return this;
    }

    public SslContextBuilder withKeyStore(PrivateKey privateKey, X509Certificate certificate) {
        return withKeyStore(privateKey, singletonList(certificate));
    }

    public SslContextBuilder withKeyStore(PrivateKey privateKey, List<X509Certificate> certificates) {
        char[] pwd = new char[0];
        this.keyStoreSupplier = () -> KeyStoreBuilder.withType(KeyStoreType.JKS).withKeyEntry("default", privateKey, certificates).build();
        this.keyStorePassword = pwd;
        return this;
    }

    public SslContextBuilder withKeyStore(KeyStore keyStore, char[] password) {
        this.keyStoreSupplier = () -> keyStore;
        this.keyStorePassword = password;
        return this;
    }

    public SslContextBuilder withKeyStore(Path file, char[] password, KeyStoreType keyStoreType) {
        this.keyStoreSupplier = () -> KeyStoreBuilder.withType(keyStoreType).fromFile(file, password).build();
        this.keyStorePassword = password;
        return this;
    }

    public SslContextBuilder withKeyStore(Path privateKeyPemFile, Path certificatesPemFile) {
        this.keyStoreSupplier =
                () ->  {
                    PrivateKey privateKey = KeyUtils.fromPemEncodedPrivateKey(new String(Files.readAllBytes(privateKeyPemFile)));
                    List<X509Certificate> certificates = X509CertificateUtils.certificateListFromPem(new String(Files.readAllBytes(certificatesPemFile)));
                    return KeyStoreBuilder.withType(KeyStoreType.JKS)
                            .withKeyEntry("default", privateKey, certificates)
                            .build();
                };
        this.keyStorePassword = new char[0];
        return this;
    }

    public SslContextBuilder withTrustManagerFactory(TrustManagerFactory trustManagersFactory) {
        this.trustManagerFactory = trustManagersFactory;
        return this;
    }

    public SslContextBuilder withKeyManagerFactory(KeyManagerFactory keyManagerFactory) {
        this.keyManagerFactory = keyManagerFactory;
        return this;
    }

    /**
     * Note: Callee is responsible for configuring the key manager.
     *       Any keystore configured by {@link #withKeyStore(KeyStore, char[])} or the other overloads will be ignored.
     */
    public SslContextBuilder withKeyManager(X509ExtendedKeyManager keyManager) {
        this.keyManager = keyManager;
        return this;
    }

    /**
     * Note: Callee is responsible for configuring the trust manager.
     *       Any truststore configured by {@link #withTrustStore(KeyStore)} or the other overloads will be ignored.
     */
    public SslContextBuilder withTrustManager(X509ExtendedTrustManager trustManager) {
        this.trustManager = trustManager;
        return this;
    }

    public SSLContext build() {
        try {
            SSLContext sslContext = SSLContext.getInstance(TlsContext.SSL_CONTEXT_VERSION);
            X509ExtendedTrustManager trustManager = this.trustManager != null
                    ? this.trustManager
                    : trustManagerFactory.createTrustManager(trustStoreSupplier.get());
            X509ExtendedKeyManager keyManager = this.keyManager != null
                    ? this.keyManager
                    : keyManagerFactory.createKeyManager(keyStoreSupplier.get(), keyStorePassword);
            sslContext.init(new KeyManager[] {keyManager}, new TrustManager[] {trustManager}, null);
            return sslContext;
        } catch (GeneralSecurityException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
        finally {
            keyStorePassword = null;
        }
    }

    private static KeyStore createTrustStore(List<X509Certificate> caCertificates) {
        return KeyStoreBuilder.withType(KeyStoreType.JKS)
                .withCertificateEntries("cert", caCertificates)
                .build();
    }

    private interface KeyStoreSupplier {
        KeyStore get() throws IOException, GeneralSecurityException;
    }

    /**
     * A factory interface for creating {@link X509ExtendedTrustManager}.
     */
    @FunctionalInterface
    public interface TrustManagerFactory {
        X509ExtendedTrustManager createTrustManager(KeyStore truststore) throws GeneralSecurityException;
    }

    /**
     * A factory interface for creating {@link X509ExtendedKeyManager}.
     */
    @FunctionalInterface
    public interface KeyManagerFactory {
        X509ExtendedKeyManager createKeyManager(KeyStore truststore, char[] password) throws GeneralSecurityException;
    }

}