aboutsummaryrefslogtreecommitdiffstats
path: root/athenz-identity-provider-service/src/main/java/com/yahoo/vespa/hosted/athenz/instanceproviderservice/ConfigserverSslContextFactoryProvider.java
blob: 1a7224fdc713bb56933e225098f6b8f8634fa945 (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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.athenz.instanceproviderservice;

import com.google.inject.Inject;
import com.yahoo.component.AbstractComponent;
import com.yahoo.config.provision.Zone;
import com.yahoo.jdisc.http.ssl.SslContextFactoryProvider;
import com.yahoo.log.LogLevel;
import com.yahoo.security.KeyStoreBuilder;
import com.yahoo.security.KeyStoreType;
import com.yahoo.security.KeyUtils;
import com.yahoo.vespa.athenz.api.AthenzService;
import com.yahoo.vespa.athenz.client.zts.DefaultZtsClient;
import com.yahoo.vespa.athenz.client.zts.Identity;
import com.yahoo.vespa.athenz.client.zts.ZtsClient;
import com.yahoo.vespa.athenz.identity.ServiceIdentityProvider;
import com.yahoo.vespa.athenz.utils.SiaUtils;
import com.yahoo.vespa.defaults.Defaults;
import com.yahoo.vespa.hosted.athenz.instanceproviderservice.config.AthenzProviderServiceConfig;
import org.eclipse.jetty.util.ssl.SslContextFactory;

import java.net.URI;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.X509Certificate;
import java.time.Duration;
import java.time.Instant;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;

import static com.yahoo.vespa.hosted.athenz.instanceproviderservice.impl.Utils.getZoneConfig;

/**
 * Configures the JDisc https connector with the configserver's Athenz provider certificate and private key.
 *
 * @author bjorncs
 */
public class ConfigserverSslContextFactoryProvider extends AbstractComponent implements SslContextFactoryProvider {
    private static final String CERTIFICATE_ALIAS = "athenz";
    private static final Duration EXPIRATION_MARGIN = Duration.ofHours(6);
    private static final Path VESPA_SIA_DIRECTORY = Paths.get(Defaults.getDefaults().underVespaHome("var/vespa/sia"));

    private static final Logger log = Logger.getLogger(ConfigserverSslContextFactoryProvider.class.getName());

    private final SslContextFactory sslContextFactory;
    private final ScheduledExecutorService scheduler =
            Executors.newSingleThreadScheduledExecutor(runnable -> new Thread(runnable, "configserver-ssl-context-factory-provider"));
    private final ZtsClient ztsClient;
    private final KeyProvider keyProvider;
    private final AthenzProviderServiceConfig.Zones zoneConfig;
    private final AthenzService configserverIdentity;

    @Inject
    public ConfigserverSslContextFactoryProvider(ServiceIdentityProvider bootstrapIdentity,
                                                 KeyProvider keyProvider,
                                                 AthenzProviderServiceConfig config,
                                                 Zone zone) {
        this.zoneConfig = getZoneConfig(config, zone);
        this.ztsClient = new DefaultZtsClient(URI.create(zoneConfig.ztsUrl()), bootstrapIdentity);
        this.keyProvider = keyProvider;
        this.configserverIdentity = new AthenzService(zoneConfig.domain(), zoneConfig.serviceName());

        Duration updatePeriod = Duration.ofDays(config.updatePeriodDays());
        Path trustStoreFile = Paths.get(config.athenzCaTrustStore());
        this.sslContextFactory = initializeSslContextFactory(keyProvider, trustStoreFile, updatePeriod, configserverIdentity, ztsClient, zoneConfig);
        scheduler.scheduleAtFixedRate(new KeystoreUpdater(sslContextFactory),
                                      updatePeriod.toDays()/*initial delay*/,
                                      updatePeriod.toDays(),
                                      TimeUnit.DAYS);
    }

    @Override
    public SslContextFactory getInstance(String containerId, int port) {
        return sslContextFactory;
    }

    Instant getCertificateNotAfter() {
        try {
            X509Certificate certificate = (X509Certificate) sslContextFactory.getKeyStore().getCertificate(CERTIFICATE_ALIAS);
            return certificate.getNotAfter().toInstant();
        } catch (GeneralSecurityException e) {
            throw new IllegalStateException("Unable to find configserver certificate from keystore: " + e.getMessage(), e);
        }
    }

    @Override
    public void deconstruct() {
        try {
            scheduler.shutdownNow();
            scheduler.awaitTermination(30, TimeUnit.SECONDS);
            ztsClient.close();
        } catch (InterruptedException e) {
            throw new RuntimeException("Failed to shutdown Athenz certificate updater on time", e);
        }
    }

    private static SslContextFactory initializeSslContextFactory(KeyProvider keyProvider,
                                                                 Path trustStoreFile,
                                                                 Duration updatePeriod,
                                                                 AthenzService configserverIdentity,
                                                                 ZtsClient ztsClient,
                                                                 AthenzProviderServiceConfig.Zones zoneConfig) {
        SslContextFactory factory = new SslContextFactory();

        factory.setWantClientAuth(true);

        KeyStore trustStore =
                KeyStoreBuilder.withType(KeyStoreType.JKS)
                        .fromFile(trustStoreFile)
                        .build();
        factory.setTrustStore(trustStore);

        KeyStore keyStore =
                tryReadKeystoreFile(configserverIdentity, updatePeriod)
                        .orElseGet(() -> updateKeystore(configserverIdentity, generateKeystorePassword(), keyProvider, ztsClient, zoneConfig));
        factory.setKeyStore(keyStore);
        factory.setKeyStorePassword("");
        return factory;
    }

    private static Optional<KeyStore> tryReadKeystoreFile(AthenzService configserverIdentity, Duration updatePeriod) {
        Optional<X509Certificate> certificate = SiaUtils.readCertificateFile(VESPA_SIA_DIRECTORY, configserverIdentity);
        if (!certificate.isPresent()) return Optional.empty();
        Optional<PrivateKey> privateKey = SiaUtils.readPrivateKeyFile(VESPA_SIA_DIRECTORY, configserverIdentity);
        if (!privateKey.isPresent()) return Optional.empty();
        Instant minimumExpiration = Instant.now().plus(updatePeriod).plus(EXPIRATION_MARGIN);
        boolean isExpired = certificate.get().getNotAfter().toInstant().isBefore(minimumExpiration);
        if (isExpired) return Optional.empty();
        KeyStore keyStore = KeyStoreBuilder.withType(KeyStoreType.JKS)
                .withKeyEntry(CERTIFICATE_ALIAS, privateKey.get(), certificate.get())
                .build();
        return Optional.of(keyStore);
    }

    private static KeyStore updateKeystore(AthenzService configserverIdentity,
                                           char[] keystorePwd,
                                           KeyProvider keyProvider,
                                           ZtsClient ztsClient,
                                           AthenzProviderServiceConfig.Zones zoneConfig) {
        PrivateKey privateKey = keyProvider.getPrivateKey(zoneConfig.secretVersion());
        PublicKey publicKey = KeyUtils.extractPublicKey(privateKey);
        Identity serviceIdentity = ztsClient.getServiceIdentity(configserverIdentity,
                                                                Integer.toString(zoneConfig.secretVersion()),
                                                                new KeyPair(publicKey, privateKey),
                                                                zoneConfig.certDnsSuffix());
        X509Certificate certificate = serviceIdentity.certificate();
        SiaUtils.writeCertificateFile(VESPA_SIA_DIRECTORY, configserverIdentity, certificate);
        SiaUtils.writePrivateKeyFile(VESPA_SIA_DIRECTORY, configserverIdentity, privateKey);
        Instant expirationTime = certificate.getNotAfter().toInstant();
        Duration expiry = Duration.between(certificate.getNotBefore().toInstant(), expirationTime);
        log.log(LogLevel.INFO, String.format("Got Athenz x509 certificate with expiry %s (expires %s)", expiry, expirationTime));
        return KeyStoreBuilder.withType(KeyStoreType.JKS)
                .withKeyEntry(CERTIFICATE_ALIAS, privateKey, keystorePwd, certificate)
                .build();
    }

    private static char[] generateKeystorePassword() {
        return UUID.randomUUID().toString().toCharArray();
    }

    private class KeystoreUpdater implements Runnable {
        final SslContextFactory sslContextFactory;

        KeystoreUpdater(SslContextFactory sslContextFactory) {
            this.sslContextFactory = sslContextFactory;
        }

        @Override
        public void run() {
            try {
                log.log(LogLevel.INFO, "Updating configserver provider certificate from ZTS");
                char[] keystorePwd = generateKeystorePassword();
                KeyStore keyStore = updateKeystore(configserverIdentity, keystorePwd, keyProvider, ztsClient, zoneConfig);
                sslContextFactory.reload(scf -> {
                    scf.setKeyStore(keyStore);
                    scf.setKeyStorePassword(new String(keystorePwd));
                });
                log.log(LogLevel.INFO, "Certificate successfully updated");
            } catch (Throwable t) {
                log.log(LogLevel.ERROR, "Failed to update certificate from ZTS: " + t.getMessage(), t);
            }
        }
    }
}