Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,7 @@
import com.cloud.kubernetes.cluster.actionworkers.KubernetesClusterStartWorker;
import com.cloud.kubernetes.cluster.actionworkers.KubernetesClusterStopWorker;
import com.cloud.kubernetes.cluster.actionworkers.KubernetesClusterUpgradeWorker;
import com.cloud.kubernetes.cluster.actionworkers.KubernetesClusterUserKubeConfigWorker;
import com.cloud.kubernetes.cluster.dao.KubernetesClusterAffinityGroupMapDao;
import com.cloud.kubernetes.cluster.dao.KubernetesClusterDao;
import com.cloud.kubernetes.cluster.dao.KubernetesClusterDetailsDao;
Expand Down Expand Up @@ -2269,11 +2270,47 @@ public KubernetesClusterConfigResponse getKubernetesClusterConfig(GetKubernetesC
String.format("Config not found for Kubernetes cluster : %s", kubernetesCluster.getName());
throw new CloudRuntimeException(exceptionMessage);
}
if (KubernetesClusterUserKubeConfigEnabled.valueIn(kubernetesCluster.getDomainId())) {
boolean canChangeCluster = canChangeKubernetesCluster(CallContext.current().getCallingUser(), cmd);
if (!canChangeCluster || !accountManager.isRootAdmin(caller.getId())) {
configData = issueUserKubeConfig(kubernetesCluster, configData, caller, canChangeCluster);
}
}
response.setConfigData(configData);
response.setObjectName("clusterconfig");
return response;
}

/**
* A caller whose role, project role and API key may scale the cluster already controls its nodes. Others, such as
* read-only roles that are allowed every get* API, only get read access in the cluster.
*/
protected boolean canChangeKubernetesCluster(User caller, GetKubernetesClusterConfigCmd cmd) {
String apiKey = cmd.getFullUrlParams().entrySet().stream()
.filter(e -> ApiConstants.API_KEY.equalsIgnoreCase(e.getKey()))
.map(Map.Entry::getValue).findFirst().orElse(null);
try {
accountManager.checkApiAccess(caller, BaseCmd.getCommandNameByClass(ScaleKubernetesClusterCmd.class), apiKey);
return true;
} catch (PermissionDeniedException e) {
return false;
}
}

protected String issueUserKubeConfig(KubernetesCluster kubernetesCluster, String clusterKubeConfig, Account caller, boolean clusterAdmin) {
int validityHours = KubernetesClusterUserKubeConfigValidity.valueIn(kubernetesCluster.getDomainId());
if (validityHours < 1 || validityHours > MAX_USER_KUBECONFIG_VALIDITY_HOURS) {
throw new CloudRuntimeException(String.format("%s must be between 1 and %d hours", KubernetesClusterUserKubeConfigValidity.key(), MAX_USER_KUBECONFIG_VALIDITY_HOURS));
}
KubernetesSupportedVersion version = kubernetesSupportedVersionDao.findById(kubernetesCluster.getKubernetesVersionId());
if (KubernetesVersionManagerImpl.compareSemanticVersions(version.getSemanticVersion(), MIN_KUBERNETES_VERSION_USER_KUBECONFIG) < 0) {
throw new CloudRuntimeException(String.format("Kubernetes cluster %s runs Kubernetes %s; a kubeconfig of your own needs %s or later. Upgrade the cluster or ask an administrator for its kubeconfig.",
kubernetesCluster.getName(), version.getSemanticVersion(), MIN_KUBERNETES_VERSION_USER_KUBECONFIG));
}
KubernetesClusterUserKubeConfigWorker worker = ComponentContext.inject(new KubernetesClusterUserKubeConfigWorker(kubernetesCluster, this));
return worker.issueKubeConfig(clusterKubeConfig, CallContext.current().getCallingUser(), caller, clusterAdmin, validityHours * 3600L);
}

@Override
@ActionEvent(eventType = KubernetesClusterEventTypes.EVENT_KUBERNETES_CLUSTER_SCALE,
eventDescription = "scaling Kubernetes cluster", async = true)
Expand Down Expand Up @@ -3089,7 +3126,9 @@ public ConfigKey<?>[] getConfigKeys() {
KubernetesControlNodeInstallReattempts,
KubernetesWorkerNodeInstallAttemptWait,
KubernetesWorkerNodeInstallReattempts,
KubernetesEtcdNodeStartPort
KubernetesEtcdNodeStartPort,
KubernetesClusterUserKubeConfigEnabled,
KubernetesClusterUserKubeConfigValidity
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@

public interface KubernetesClusterService extends PluggableService, Configurable {
static final String MIN_KUBERNETES_VERSION_HA_SUPPORT = "1.16.0";
static final String MIN_KUBERNETES_VERSION_USER_KUBECONFIG = "1.22.0";
static final int MAX_USER_KUBECONFIG_VALIDITY_HOURS = 8760;
static final int MIN_KUBERNETES_CLUSTER_NODE_CPU = 2;
static final int MIN_KUBERNETES_CLUSTER_NODE_RAM_SIZE = 2048;
static final String KUBEADMIN_ACCOUNT_NAME = "kubeadmin";
Expand Down Expand Up @@ -143,6 +145,25 @@ public interface KubernetesClusterService extends PluggableService, Configurable
"Start port for Port forwarding rules for etcd nodes",
true,
KubernetesServiceEnabled.key());
static final ConfigKey<Boolean> KubernetesClusterUserKubeConfigEnabled = new ConfigKey<Boolean>("Advanced", Boolean.class,
"cloud.kubernetes.cluster.user.kubeconfig.enabled",
"false",
"When true, getKubernetesClusterConfig gives each caller a kubeconfig of their own: a client certificate for " +
"the Kubernetes user cloudstack:user:<user uuid>, valid for cloud.kubernetes.cluster.user.kubeconfig.validity hours. " +
"Callers allowed to scale the cluster get cluster-admin, others the view role. Root admins allowed to scale " +
"the cluster still get the cluster's admin kubeconfig. Needs Kubernetes 1.22 or later. Kubeconfigs handed out " +
"before stay valid until they expire.",
true,
ConfigKey.Scope.Domain,
KubernetesServiceEnabled.key());
static final ConfigKey<Integer> KubernetesClusterUserKubeConfigValidity = new ConfigKey<Integer>("Advanced", Integer.class,
"cloud.kubernetes.cluster.user.kubeconfig.validity",
"24",
"Hours a kubeconfig given with cloud.kubernetes.cluster.user.kubeconfig.enabled stays valid (1 to 8760). " +
"The cluster may cap it at its own certificate signing duration.",
true,
ConfigKey.Scope.Domain,
KubernetesClusterUserKubeConfigEnabled.key());

KubernetesCluster findById(final Long id);

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.

package com.cloud.kubernetes.cluster.actionworkers;

import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.cloudstack.utils.security.CertUtils;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.asn1.x500.X500NameBuilder;
import org.bouncycastle.asn1.x500.style.BCStyle;
import org.bouncycastle.openssl.jcajce.JcaPEMWriter;
import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder;

import com.cloud.kubernetes.cluster.KubernetesCluster;
import com.cloud.kubernetes.cluster.KubernetesClusterManagerImpl;
import com.cloud.user.Account;
import com.cloud.user.User;
import com.cloud.utils.Pair;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.ssh.SshHelper;
import com.google.gson.Gson;

/**
* Issues a kubeconfig with a client certificate of the calling user's own. The private key is made here and only
* returned to the caller; the control node gets the certificate signing request and signs it with the cluster CA.
*/
public class KubernetesClusterUserKubeConfigWorker extends KubernetesClusterActionWorker {

public static final String USER_NAME_PREFIX = "cloudstack:user:";
public static final String ACCOUNT_GROUP_PREFIX = "cloudstack:account:";
public static final String CLUSTER_ADMINS_GROUP = "cloudstack:cluster-admins";
public static final String VIEWERS_GROUP = "cloudstack:viewers";
protected static final String KUBECTL = "sudo /opt/bin/kubectl";
protected static final String CERTIFICATE_PREFIX = "certificate: ";
private static final int KEY_SIZE = 2048;
private static final int SIGN_WAIT_SECONDS = 30;
private static final Pattern CERTIFICATE_AUTHORITY_DATA = Pattern.compile("(?m)^\\s*certificate-authority-data:[ \\t]*(\\S+)");
private static final Pattern SERVER = Pattern.compile("(?m)^\\s*server:[ \\t]*(\\S+)");
private static final Pattern CERTIFICATE = Pattern.compile(CERTIFICATE_PREFIX + "(\\S+)");

public KubernetesClusterUserKubeConfigWorker(final KubernetesCluster kubernetesCluster, final KubernetesClusterManagerImpl clusterManager) {
super(kubernetesCluster, clusterManager);
}

/**
* @param clusterKubeConfig the cluster's stored kubeconfig, for the API server address and the cluster CA
* @param clusterAdmin true for the cluster-admin group, false for the read-only group
*/
public String issueKubeConfig(String clusterKubeConfig, User user, Account account, boolean clusterAdmin, long validitySeconds) {
String userName = USER_NAME_PREFIX + user.getUuid();
List<String> groups = List.of(clusterAdmin ? CLUSTER_ADMINS_GROUP : VIEWERS_GROUP, ACCOUNT_GROUP_PREFIX + account.getUuid());
try {
KeyPair keyPair = CertUtils.generateRandomKeyPair(KEY_SIZE);
String csrName = "cloudstack-" + UUID.randomUUID();
String certificate = signCertificate(buildSignCommand(csrName, buildManifest(csrName, generateCsr(keyPair, userName, groups), validitySeconds)));
String kubeConfig = buildKubeConfig(clusterKubeConfig, kubernetesCluster.getUuid(), certificate, CertUtils.privateKeyToPem(keyPair.getPrivate()));
logger.info("Issued a kubeconfig for {} in groups {}, valid for {} seconds, on Kubernetes cluster {} (request {})",
userName, groups, validitySeconds, kubernetesCluster, csrName);
return kubeConfig;
} catch (IOException | OperatorCreationException | GeneralSecurityException e) {
throw new CloudRuntimeException(String.format("Unable to create a key for a kubeconfig of Kubernetes cluster %s", kubernetesCluster.getName()), e);
}
}

protected static String generateCsr(KeyPair keyPair, String userName, List<String> groups) throws IOException, OperatorCreationException {
X500NameBuilder subject = new X500NameBuilder(BCStyle.INSTANCE);
for (String group : groups) {
subject.addRDN(BCStyle.O, group);
}
subject.addRDN(BCStyle.CN, userName);
StringWriter pem = new StringWriter();
try (JcaPEMWriter writer = new JcaPEMWriter(pem)) {
writer.writeObject(new JcaPKCS10CertificationRequestBuilder(subject.build(), keyPair.getPublic())
.build(new JcaContentSignerBuilder("SHA256withRSA").build(keyPair.getPrivate())));
}
return pem.toString();
}

/**
* The RBAC bindings are applied with every request, so clusters created before this feature get them too.
*/
protected static String buildManifest(String csrName, String csrPem, long validitySeconds) {
Map<String, Object> csr = Map.of(
"apiVersion", "certificates.k8s.io/v1",
"kind", "CertificateSigningRequest",
"metadata", Map.of("name", csrName),
"spec", Map.of(
"request", Base64.encodeBase64String(csrPem.getBytes(StandardCharsets.UTF_8)),
"signerName", "kubernetes.io/kube-apiserver-client",
"expirationSeconds", validitySeconds,
"usages", List.of("client auth")));
return new Gson().toJson(Map.of("apiVersion", "v1", "kind", "List", "items",
List.of(clusterRoleBinding(CLUSTER_ADMINS_GROUP, "cluster-admin"), clusterRoleBinding(VIEWERS_GROUP, "view"), csr)));
}

private static Map<String, Object> clusterRoleBinding(String group, String clusterRole) {
String rbacApiGroup = "rbac.authorization.k8s.io";
return Map.of(
"apiVersion", rbacApiGroup + "/v1",
"kind", "ClusterRoleBinding",
"metadata", Map.of("name", group),
"roleRef", Map.of("apiGroup", rbacApiGroup, "kind", "ClusterRole", "name", clusterRole),
"subjects", List.of(Map.of("apiGroup", rbacApiGroup, "kind", "Group", "name", group)));
}

/**
* Prints the signed certificate, base64-encoded, after CERTIFICATE_PREFIX. The request is deleted either way.
* Server-side apply, so concurrent first requests do not race to create the bindings.
*/
protected static String buildSignCommand(String csrName, String manifest) {
return String.format("c=; echo %s | base64 -d | %s apply --server-side --force-conflicts --field-manager=cloudstack -f - > /dev/null && " +
"%s certificate approve %s > /dev/null && " +
"for i in $(seq %d); do c=$(%s get csr %s -o jsonpath='{.status.certificate}' 2> /dev/null); [ -n \"$c\" ] && break; sleep 1; done; " +
"%s delete csr %s --ignore-not-found > /dev/null 2>&1; [ -n \"$c\" ] && echo \"%s$c\"",
Base64.encodeBase64String(manifest.getBytes(StandardCharsets.UTF_8)), KUBECTL, KUBECTL, csrName,
SIGN_WAIT_SECONDS, KUBECTL, csrName, KUBECTL, csrName, CERTIFICATE_PREFIX);
}

protected String signCertificate(String command) {
sshKeyFile = getManagementServerSshPublicKeyFile();
Pair<String, Integer> ipSshPort = getKubernetesClusterServerIpSshPort(null);
Pair<Boolean, String> result;
try {
result = SshHelper.sshExecute(ipSshPort.first(), ipSshPort.second(), getControlNodeLoginUser(), sshKeyFile, null,
command, 10000, 10000, (SIGN_WAIT_SECONDS + 30) * 1000);
} catch (Exception e) {
throw new CloudRuntimeException(String.format("Unable to reach the control node of Kubernetes cluster %s to sign a kubeconfig certificate", kubernetesCluster.getName()), e);
}
if (!result.first()) {
throw new CloudRuntimeException(String.format("Kubernetes cluster %s did not sign the kubeconfig certificate; see the management server log", kubernetesCluster.getName()));
}
Matcher matcher = CERTIFICATE.matcher(result.second());
while (matcher.find()) {
String certificate = new String(Base64.decodeBase64(matcher.group(1)), StandardCharsets.UTF_8);
if (certificate.startsWith("-----BEGIN CERTIFICATE-----")) {
return certificate;
}
}
logger.warn("Kubernetes cluster {} returned no kubeconfig certificate: {}", kubernetesCluster, result.second());
throw new CloudRuntimeException(String.format("Kubernetes cluster %s returned no kubeconfig certificate; see the management server log", kubernetesCluster.getName()));
}

/**
* Entries are named after the cluster UUID, so kubeconfigs of several clusters can be merged.
*/
protected static String buildKubeConfig(String clusterKubeConfig, String clusterUuid, String certificatePem, String privateKeyPem) {
Matcher certificateAuthority = CERTIFICATE_AUTHORITY_DATA.matcher(clusterKubeConfig);
Matcher server = SERVER.matcher(clusterKubeConfig);
if (!certificateAuthority.find() || !server.find()) {
throw new CloudRuntimeException("The stored kubeconfig of the Kubernetes cluster has no API server address or CA certificate");
}
String entry = "cloudstack-" + clusterUuid;
return "apiVersion: v1\n" +
"kind: Config\n" +
"clusters:\n" +
"- name: " + entry + "\n" +
" cluster:\n" +
" certificate-authority-data: " + certificateAuthority.group(1) + "\n" +
" server: " + server.group(1) + "\n" +
"users:\n" +
"- name: " + entry + "\n" +
" user:\n" +
" client-certificate-data: " + Base64.encodeBase64String(certificatePem.getBytes(StandardCharsets.UTF_8)) + "\n" +
" client-key-data: " + Base64.encodeBase64String(privateKeyPem.getBytes(StandardCharsets.UTF_8)) + "\n" +
"contexts:\n" +
"- name: " + entry + "\n" +
" context:\n" +
" cluster: " + entry + "\n" +
" user: " + entry + "\n" +
"current-context: " + entry + "\n";
}
}
Loading
Loading