aboutsummaryrefslogtreecommitdiffstats
path: root/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/maintenance/identity/AthenzCredentialsMaintainer.java
blob: ade46182efcbfab0e4cb6843bbdf6ba9a7cdbf13 (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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
// 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.node.admin.maintenance.identity;

import com.yahoo.vespa.athenz.api.AthenzService;
import com.yahoo.vespa.athenz.client.zts.DefaultZtsClient;
import com.yahoo.vespa.athenz.client.zts.InstanceIdentity;
import com.yahoo.vespa.athenz.client.zts.ZtsClient;
import com.yahoo.vespa.athenz.client.zts.ZtsClientException;
import com.yahoo.vespa.athenz.identity.ServiceIdentityProvider;
import com.yahoo.vespa.athenz.identityprovider.api.EntityBindingsMapper;
import com.yahoo.vespa.athenz.identityprovider.api.IdentityDocumentClient;
import com.yahoo.vespa.athenz.identityprovider.api.SignedIdentityDocument;
import com.yahoo.vespa.athenz.identityprovider.client.DefaultIdentityDocumentClient;
import com.yahoo.vespa.athenz.identityprovider.client.InstanceCsrGenerator;
import com.yahoo.vespa.athenz.tls.AthenzIdentityVerifier;
import com.yahoo.vespa.athenz.utils.SiaUtils;
import com.yahoo.vespa.hosted.dockerapi.ContainerName;
import com.yahoo.vespa.hosted.node.admin.component.Environment;
import com.yahoo.vespa.hosted.node.admin.util.PrefixLogger;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;

import static java.util.Collections.singleton;

/**
 * A maintainer that is responsible for providing and refreshing Athenz credentials for a container.
 *
 * @author bjorncs
 */
@SuppressWarnings("deprecation")
public class AthenzCredentialsMaintainer {

    private static final Duration EXPIRY_MARGIN = Duration.ofDays(1);
    private static final Duration REFRESH_PERIOD = Duration.ofDays(1);
    private static final Duration REFRESH_BACKOFF = Duration.ofHours(1); // Backoff when refresh fails to ensure ZTS is not DDoS'ed.

    private static final Path CONTAINER_SIA_DIRECTORY = Paths.get("/var/lib/sia");

    private final boolean enabled;
    private final PrefixLogger log;
    private final String hostname;
    private final Path trustStorePath;
    private final Path privateKeyFile;
    private final Path certificateFile;
    private final Path identityDocumentFile;
    private final AthenzService containerIdentity;
    private final URI ztsEndpoint;
    private final Clock clock;
    private final ServiceIdentityProvider hostIdentityProvider;
    private final IdentityDocumentClient identityDocumentClient;
    private final InstanceCsrGenerator csrGenerator;
    private final AthenzService configserverIdentity;

    private Instant lastRefreshAttempt = Instant.EPOCH; // Used as an optimization to ensure ZTS is not DDoS'ed on continuously failing refresh attempts

    public AthenzCredentialsMaintainer(String hostname,
                                       Environment environment,
                                       ServiceIdentityProvider hostIdentityProvider) {
        ContainerName containerName = ContainerName.fromHostname(hostname);
        Path containerSiaDirectory = environment.pathInNodeAdminFromPathInNode(containerName, CONTAINER_SIA_DIRECTORY);
        this.enabled = environment.isNodeAgentCertEnabled();
        this.log = PrefixLogger.getNodeAgentLogger(AthenzCredentialsMaintainer.class, containerName);
        this.hostname = hostname;
        this.containerIdentity = environment.getNodeAthenzIdentity();
        this.ztsEndpoint = environment.getZtsUri();
        this.configserverIdentity = environment.getConfigserverAthenzIdentity();
        this.csrGenerator = new InstanceCsrGenerator(environment.getCertificateDnsSuffix());
        this.trustStorePath = environment.getTrustStorePath();
        this.privateKeyFile = SiaUtils.getPrivateKeyFile(containerSiaDirectory, containerIdentity);
        this.certificateFile = SiaUtils.getCertificateFile(containerSiaDirectory, containerIdentity);
        this.identityDocumentFile = containerSiaDirectory.resolve("vespa-node-identity-document.json");
        this.hostIdentityProvider = hostIdentityProvider;
        this.identityDocumentClient =
                new DefaultIdentityDocumentClient(
                        environment.getConfigserverLoadBalancerEndpoint(),
                        hostIdentityProvider,
                        new AthenzIdentityVerifier(singleton(configserverIdentity)));
        this.clock = Clock.systemUTC();
    }

    public void converge() {
        try {
            if (!enabled) {
                log.debug("Feature disabled on this host - not fetching certificate");
                return;
            }
            log.debug("Checking certificate");
            Instant now = clock.instant();
            if (!Files.exists(privateKeyFile) || !Files.exists(certificateFile) || !Files.exists(identityDocumentFile)) {
                log.info("Certificate/private key/identity document file does not exist");
                Files.createDirectories(privateKeyFile.getParent());
                Files.createDirectories(certificateFile.getParent());
                Files.createDirectories(identityDocumentFile.getParent());
                registerIdentity();
                return;
            }
            X509Certificate certificate = readCertificateFromFile();
            Instant expiry = certificate.getNotAfter().toInstant();
            if (isCertificateExpired(expiry, now)) {
                log.info(String.format("Certificate has expired (expiry=%s)", expiry.toString()));
                registerIdentity();
                return;
            }
            Duration age = Duration.between(certificate.getNotBefore().toInstant(), now);
            if (shouldRefreshCredentials(age)) {
                log.info(String.format("Certificate is ready to be refreshed (age=%s)", age.toString()));
                if (shouldThrottleRefreshAttempts(now)) {
                    log.warning(String.format("Skipping refresh attempt as last refresh was on %s (less than %s ago)",
                                              lastRefreshAttempt.toString(), REFRESH_BACKOFF.toString()));
                    return;
                } else {
                    lastRefreshAttempt = now;
                    refreshIdentity();
                    return;
                }
            }
            log.debug("Certificate is still valid");
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    public void clearCredentials() {
        if (!enabled) return;
        try {
            if (Files.deleteIfExists(privateKeyFile))
                log.info(String.format("Deleted private key file (path=%s)", privateKeyFile));
            if (Files.deleteIfExists(certificateFile))
                log.info(String.format("Deleted certificate file (path=%s)", certificateFile));
            if (Files.deleteIfExists(identityDocumentFile))
                log.info(String.format("Deleted identity document file (path=%s)", certificateFile));
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    private boolean shouldRefreshCredentials(Duration age) {
        return age.compareTo(REFRESH_PERIOD) >= 0;
    }

    private boolean shouldThrottleRefreshAttempts(Instant now) {
        return REFRESH_BACKOFF.compareTo(Duration.between(lastRefreshAttempt, now)) > 0;
    }

    private X509Certificate readCertificateFromFile() throws IOException {
        String pemEncodedCertificate = new String(Files.readAllBytes(certificateFile));
        return com.yahoo.vespa.athenz.tls.X509CertificateUtils.fromPem(pemEncodedCertificate);
    }

    private boolean isCertificateExpired(Instant expiry, Instant now) {
        return now.isAfter(expiry.minus(EXPIRY_MARGIN));
    }

    private void registerIdentity() {
        KeyPair keyPair = com.yahoo.vespa.athenz.tls.KeyUtils.generateKeypair(com.yahoo.vespa.athenz.tls.KeyAlgorithm.RSA);
        SignedIdentityDocument signedIdentityDocument = identityDocumentClient.getNodeIdentityDocument(hostname);
        com.yahoo.vespa.athenz.tls.Pkcs10Csr csr = csrGenerator.generateCsr(
                containerIdentity, signedIdentityDocument.providerUniqueId(), signedIdentityDocument.ipAddresses(), keyPair);
        try (ZtsClient ztsClient = new DefaultZtsClient(ztsEndpoint, hostIdentityProvider)) {
            InstanceIdentity instanceIdentity =
                    ztsClient.registerInstance(
                            configserverIdentity,
                            containerIdentity,
                            signedIdentityDocument.providerUniqueId().asDottedString(),
                            EntityBindingsMapper.toAttestationData(signedIdentityDocument),
                            false,
                            csr);
            EntityBindingsMapper.writeSignedIdentityDocumentToFile(identityDocumentFile, signedIdentityDocument);
            writePrivateKeyAndCertificate(keyPair.getPrivate(), instanceIdentity.certificate());
            log.info("Instance successfully registered and credentials written to file");
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    private void refreshIdentity() {
        SignedIdentityDocument identityDocument = EntityBindingsMapper.readSignedIdentityDocumentFromFile(identityDocumentFile);
        KeyPair keyPair = com.yahoo.vespa.athenz.tls.KeyUtils.generateKeypair(com.yahoo.vespa.athenz.tls.KeyAlgorithm.RSA);
        com.yahoo.vespa.athenz.tls.Pkcs10Csr csr = csrGenerator.generateCsr(containerIdentity, identityDocument.providerUniqueId(), identityDocument.ipAddresses(), keyPair);
        SSLContext containerIdentitySslContext =
                new com.yahoo.vespa.athenz.tls.SslContextBuilder()
                        .withKeyStore(privateKeyFile.toFile(), certificateFile.toFile())
                        .withTrustStore(trustStorePath.toFile(), com.yahoo.vespa.athenz.tls.KeyStoreType.JKS)
                        .build();
        try {
            try (ZtsClient ztsClient = new DefaultZtsClient(ztsEndpoint, containerIdentity, containerIdentitySslContext)) {
                InstanceIdentity instanceIdentity =
                        ztsClient.refreshInstance(
                                configserverIdentity,
                                containerIdentity,
                                identityDocument.providerUniqueId().asDottedString(),
                                false,
                                csr);
                writePrivateKeyAndCertificate(keyPair.getPrivate(), instanceIdentity.certificate());
                log.info("Instance successfully refreshed and credentials written to file");
            } catch (ZtsClientException e) {
                if (e.getErrorCode() == 403 && e.getDescription().startsWith("Certificate revoked")) {
                    log.error("Certificate cannot be refreshed as it is revoked by ZTS - re-registering the instance now", e);
                    registerIdentity();
                } else {
                    throw e;
                }
            }
        } catch (Exception e) {
            log.error("Certificate refresh failed: " + e.getMessage(), e);
        }
    }

    private void writePrivateKeyAndCertificate(PrivateKey privateKey, X509Certificate certificate) throws IOException {
        Path tempPrivateKeyFile = toTempPath(privateKeyFile);
        Files.write(tempPrivateKeyFile, com.yahoo.vespa.athenz.tls.KeyUtils.toPem(privateKey).getBytes());
        Path tempCertificateFile = toTempPath(certificateFile);
        Files.write(tempCertificateFile, com.yahoo.vespa.athenz.tls.X509CertificateUtils.toPem(certificate).getBytes());

        Files.move(tempPrivateKeyFile, privateKeyFile, StandardCopyOption.ATOMIC_MOVE);
        Files.move(tempCertificateFile, certificateFile, StandardCopyOption.ATOMIC_MOVE);
    }

    private static Path toTempPath(Path file) {
        return Paths.get(file.toAbsolutePath().toString() + ".tmp");
    }

}