Search in sources :

Example 6 with Certificate

use of org.apache.cloudstack.framework.ca.Certificate in project cloudstack by apache.

the class CAManagerImplTest method testProvisionCertificate.

@Test
public void testProvisionCertificate() throws Exception {
    final Host host = Mockito.mock(Host.class);
    Mockito.when(host.getPrivateIpAddress()).thenReturn("1.2.3.4");
    final KeyPair keyPair = CertUtils.generateRandomKeyPair(1024);
    final X509Certificate certificate = CertUtils.generateV3Certificate(null, keyPair, keyPair.getPublic(), "CN=ca", "SHA256withRSA", 365, null, null);
    Mockito.when(caProvider.issueCertificate(anyString(), anyList(), anyList(), anyInt())).thenReturn(new Certificate(certificate, null, Collections.singletonList(certificate)));
    Mockito.when(agentManager.send(anyLong(), any(SetupCertificateCommand.class))).thenReturn(new SetupCertificateAnswer(true));
    Mockito.when(agentManager.send(anyLong(), any(SetupKeyStoreCommand.class))).thenReturn(new SetupKeystoreAnswer("someCsr"));
    Mockito.doNothing().when(agentManager).reconnect(Mockito.anyLong());
    Assert.assertTrue(caManager.provisionCertificate(host, true, null));
    Mockito.verify(agentManager, Mockito.times(1)).send(Mockito.anyLong(), any(SetupKeyStoreCommand.class));
    Mockito.verify(agentManager, Mockito.times(1)).send(Mockito.anyLong(), any(SetupCertificateCommand.class));
    Mockito.verify(agentManager, Mockito.times(1)).reconnect(Mockito.anyLong());
}
Also used : KeyPair(java.security.KeyPair) Host(com.cloud.host.Host) X509Certificate(java.security.cert.X509Certificate) X509Certificate(java.security.cert.X509Certificate) Certificate(org.apache.cloudstack.framework.ca.Certificate) Test(org.junit.Test)

Example 7 with Certificate

use of org.apache.cloudstack.framework.ca.Certificate in project cloudstack by apache.

the class LibvirtServerDiscoverer method setupAgentSecurity.

private void setupAgentSecurity(final Connection sshConnection, final String agentIp, final String agentHostname) {
    if (sshConnection == null) {
        throw new CloudRuntimeException("Cannot secure agent communication because ssh connection is invalid for host ip=" + agentIp);
    }
    Integer validityPeriod = CAManager.CertValidityPeriod.value();
    if (validityPeriod < 1) {
        validityPeriod = 1;
    }
    final SSHCmdHelper.SSHCmdResult keystoreSetupResult = SSHCmdHelper.sshExecuteCmdWithResult(sshConnection, String.format("sudo /usr/share/cloudstack-common/scripts/util/%s " + "/etc/cloudstack/agent/agent.properties " + "/etc/cloudstack/agent/%s " + "%s %d " + "/etc/cloudstack/agent/%s", KeyStoreUtils.KS_SETUP_SCRIPT, KeyStoreUtils.KS_FILENAME, PasswordGenerator.generateRandomPassword(16), validityPeriod, KeyStoreUtils.CSR_FILENAME));
    if (!keystoreSetupResult.isSuccess()) {
        throw new CloudRuntimeException("Failed to setup keystore on the KVM host: " + agentIp);
    }
    final Certificate certificate = caManager.issueCertificate(keystoreSetupResult.getStdOut(), Arrays.asList(agentHostname, agentIp), Collections.singletonList(agentIp), null, null);
    if (certificate == null || certificate.getClientCertificate() == null) {
        throw new CloudRuntimeException("Failed to issue certificates for KVM host agent: " + agentIp);
    }
    final SetupCertificateCommand certificateCommand = new SetupCertificateCommand(certificate);
    final SSHCmdHelper.SSHCmdResult setupCertResult = SSHCmdHelper.sshExecuteCmdWithResult(sshConnection, String.format("sudo /usr/share/cloudstack-common/scripts/util/%s " + "/etc/cloudstack/agent/agent.properties " + "/etc/cloudstack/agent/%s %s " + "/etc/cloudstack/agent/%s \"%s\" " + "/etc/cloudstack/agent/%s \"%s\" " + "/etc/cloudstack/agent/%s \"%s\"", KeyStoreUtils.KS_IMPORT_SCRIPT, KeyStoreUtils.KS_FILENAME, KeyStoreUtils.SSH_MODE, KeyStoreUtils.CERT_FILENAME, certificateCommand.getEncodedCertificate(), KeyStoreUtils.CACERT_FILENAME, certificateCommand.getEncodedCaCertificates(), KeyStoreUtils.PKEY_FILENAME, certificateCommand.getEncodedPrivateKey()));
    if (setupCertResult != null && !setupCertResult.isSuccess()) {
        throw new CloudRuntimeException("Failed to setup certificate in the KVM agent's keystore file, please see logs and configure manually!");
    }
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Succeeded to import certificate in the keystore for agent on the KVM host: " + agentIp + ". Agent secured and trusted.");
    }
}
Also used : SetupCertificateCommand(org.apache.cloudstack.ca.SetupCertificateCommand) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) SSHCmdHelper(com.cloud.utils.ssh.SSHCmdHelper) Certificate(org.apache.cloudstack.framework.ca.Certificate)

Example 8 with Certificate

use of org.apache.cloudstack.framework.ca.Certificate in project cloudstack by apache.

the class KubernetesClusterStartWorker method getKubernetesControlNodeConfig.

private String getKubernetesControlNodeConfig(final String controlNodeIp, final String serverIp, final String hostName, final boolean haSupported, final boolean ejectIso) throws IOException {
    String k8sControlNodeConfig = readResourceFile("/conf/k8s-control-node.yml");
    final String apiServerCert = "{{ k8s_control_node.apiserver.crt }}";
    final String apiServerKey = "{{ k8s_control_node.apiserver.key }}";
    final String caCert = "{{ k8s_control_node.ca.crt }}";
    final String sshPubKey = "{{ k8s.ssh.pub.key }}";
    final String clusterToken = "{{ k8s_control_node.cluster.token }}";
    final String clusterInitArgsKey = "{{ k8s_control_node.cluster.initargs }}";
    final String ejectIsoKey = "{{ k8s.eject.iso }}";
    final List<String> addresses = new ArrayList<>();
    addresses.add(controlNodeIp);
    if (!serverIp.equals(controlNodeIp)) {
        addresses.add(serverIp);
    }
    final Certificate certificate = caManager.issueCertificate(null, Arrays.asList(hostName, "kubernetes", "kubernetes.default", "kubernetes.default.svc", "kubernetes.default.svc.cluster", "kubernetes.default.svc.cluster.local"), addresses, 3650, null);
    final String tlsClientCert = CertUtils.x509CertificateToPem(certificate.getClientCertificate());
    final String tlsPrivateKey = CertUtils.privateKeyToPem(certificate.getPrivateKey());
    final String tlsCaCert = CertUtils.x509CertificatesToPem(certificate.getCaCertificates());
    k8sControlNodeConfig = k8sControlNodeConfig.replace(apiServerCert, tlsClientCert.replace("\n", "\n      "));
    k8sControlNodeConfig = k8sControlNodeConfig.replace(apiServerKey, tlsPrivateKey.replace("\n", "\n      "));
    k8sControlNodeConfig = k8sControlNodeConfig.replace(caCert, tlsCaCert.replace("\n", "\n      "));
    String pubKey = "- \"" + configurationDao.getValue("ssh.publickey") + "\"";
    String sshKeyPair = kubernetesCluster.getKeyPair();
    if (StringUtils.isNotEmpty(sshKeyPair)) {
        SSHKeyPairVO sshkp = sshKeyPairDao.findByName(owner.getAccountId(), owner.getDomainId(), sshKeyPair);
        if (sshkp != null) {
            pubKey += "\n      - \"" + sshkp.getPublicKey() + "\"";
        }
    }
    k8sControlNodeConfig = k8sControlNodeConfig.replace(sshPubKey, pubKey);
    k8sControlNodeConfig = k8sControlNodeConfig.replace(clusterToken, KubernetesClusterUtil.generateClusterToken(kubernetesCluster));
    String initArgs = "";
    if (haSupported) {
        initArgs = String.format("--control-plane-endpoint %s:%d --upload-certs --certificate-key %s ", serverIp, CLUSTER_API_PORT, KubernetesClusterUtil.generateClusterHACertificateKey(kubernetesCluster));
    }
    initArgs += String.format("--apiserver-cert-extra-sans=%s", serverIp);
    initArgs += String.format(" --kubernetes-version=%s", getKubernetesClusterVersion().getSemanticVersion());
    k8sControlNodeConfig = k8sControlNodeConfig.replace(clusterInitArgsKey, initArgs);
    k8sControlNodeConfig = k8sControlNodeConfig.replace(ejectIsoKey, String.valueOf(ejectIso));
    k8sControlNodeConfig = updateKubeConfigWithRegistryDetails(k8sControlNodeConfig);
    return k8sControlNodeConfig;
}
Also used : ArrayList(java.util.ArrayList) SSHKeyPairVO(com.cloud.user.SSHKeyPairVO) Certificate(org.apache.cloudstack.framework.ca.Certificate)

Example 9 with Certificate

use of org.apache.cloudstack.framework.ca.Certificate in project cloudstack by apache.

the class RootCAProvider method generateCertificateUsingCsr.

private Certificate generateCertificateUsingCsr(final String csr, final List<String> names, final List<String> ips, final int validityDays) throws NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, CertificateException, SignatureException, IOException, OperatorCreationException {
    final List<String> dnsNames = new ArrayList<>();
    final List<String> ipAddresses = new ArrayList<>();
    if (names != null) {
        dnsNames.addAll(names);
    }
    if (ips != null) {
        ipAddresses.addAll(ips);
    }
    PemObject pemObject = null;
    try {
        final PemReader pemReader = new PemReader(new StringReader(csr));
        pemObject = pemReader.readPemObject();
    } catch (IOException e) {
        LOG.error("Failed to read provided CSR string as a PEM object", e);
    }
    if (pemObject == null) {
        throw new CloudRuntimeException("Unable to read/process CSR: " + csr);
    }
    final JcaPKCS10CertificationRequest request = new JcaPKCS10CertificationRequest(pemObject.getContent());
    final String subject = request.getSubject().toString();
    for (final Attribute attribute : request.getAttributes()) {
        if (attribute == null) {
            continue;
        }
        if (attribute.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
            final Extensions extensions = Extensions.getInstance(attribute.getAttrValues().getObjectAt(0));
            final GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName);
            if (gns != null && gns.getNames() != null && gns.getNames().length > 0) {
                for (final GeneralName name : gns.getNames()) {
                    if (name.getTagNo() == GeneralName.dNSName) {
                        dnsNames.add(name.getName().toString());
                    }
                    if (name.getTagNo() == GeneralName.iPAddress) {
                        final InetAddress address = InetAddress.getByAddress(DatatypeConverter.parseHexBinary(name.getName().toString().substring(1)));
                        ipAddresses.add(address.toString().replace("/", ""));
                    }
                }
            }
        }
    }
    final X509Certificate clientCertificate = CertUtils.generateV3Certificate(caCertificate, caKeyPair, request.getPublicKey(), subject, CAManager.CertSignatureAlgorithm.value(), validityDays, dnsNames, ipAddresses);
    return new Certificate(clientCertificate, null, Collections.singletonList(caCertificate));
}
Also used : JcaPKCS10CertificationRequest(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequest) Attribute(org.bouncycastle.asn1.pkcs.Attribute) ArrayList(java.util.ArrayList) IOException(java.io.IOException) Extensions(org.bouncycastle.asn1.x509.Extensions) X509Certificate(java.security.cert.X509Certificate) PemObject(org.bouncycastle.util.io.pem.PemObject) PemReader(org.bouncycastle.util.io.pem.PemReader) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) StringReader(java.io.StringReader) GeneralName(org.bouncycastle.asn1.x509.GeneralName) InetAddress(java.net.InetAddress) X509Certificate(java.security.cert.X509Certificate) Certificate(org.apache.cloudstack.framework.ca.Certificate)

Example 10 with Certificate

use of org.apache.cloudstack.framework.ca.Certificate in project cloudstack by apache.

the class RootCAProviderTest method testIssueCertificateWithCsr.

@Test
public void testIssueCertificateWithCsr() throws NoSuchProviderException, CertificateException, NoSuchAlgorithmException, InvalidKeyException, SignatureException {
    final String csr = "-----BEGIN NEW CERTIFICATE REQUEST-----\n" + "MIICxTCCAa0CAQAwUDETMBEGA1UEBhMKY2xvdWRzdGFjazETMBEGA1UEChMKY2xvdWRzdGFjazET\n" + "MBEGA1UECxMKY2xvdWRzdGFjazEPMA0GA1UEAxMGdi0xLVZNMIIBIjANBgkqhkiG9w0BAQEFAAOC\n" + "AQ8AMIIBCgKCAQEAhi3hOrt/p0hUmoW2A+2gFAMxSINItRrHfQ6VUnHhYKZGcTN9honVFuu30tz7\n" + "oSLUUx1laWEWLlIozpUcPSjOuPa5a0JS8kjplMd8DLfLNeQ6gcuEWznMRJqCaKM72qn/FAK3r11l\n" + "2NofEfWbHU5QVQ5CsYF0JndspLcnmf0tnmreAzz6vlSEPQd4g2hTSsPb72eAqYd0eJnl2oXe7cF3\n" + "iemg6/lWoxlh8njVFDKJ5ibNQA/RSc5syzzaQ8fn/AkZlChR5pml47elfC3GuqetfZPAEP4rebXV\n" + "zEw+UVbMo5bWx4AYm1S2HxhmsWC/1J5oxluZDtC6tjMqnkKQze8HbQIDAQABoDAwLgYJKoZIhvcN\n" + "AQkOMSEwHzAdBgNVHQ4EFgQUdgA1C/7vW3lUcb/dnolGjZB55/AwDQYJKoZIhvcNAQELBQADggEB\n" + "AH6ynWbyW5o4h2yEvmcr+upmu/LZYkpfwIWIo+dfrHX9OHu0rhHDIgMgqEStWzrOfhAkcEocQo21\n" + "E4Q39nECO+cgTCQ1nfH5BVqaMEg++n6tqXBwLmAQJkftEmB+YUPFB9OGn5TQY9Pcnof95Y8xnvtR\n" + "0DvVQa9RM9IsqxgvU4wQCcaNHuEC46Wzo7lyYJ6p//GLw8UQnHxsWktt8U+vyaqXjOvz0+nJobUz\n" + "Jv7r7DFkOwgS6ObBczaZsv1yx2YklcKfbsI7xVsvZAXFey2RsvSJi1QPEJC5XbwDenWnCSrPfjJg\n" + "SLJ0p9tV70D6v07r1OOmBtvU5AH4N+vioAZA0BE=\n" + "-----END NEW CERTIFICATE REQUEST-----\n";
    final Certificate certificate = provider.issueCertificate(csr, Arrays.asList("v-1-VM", "domain1.com", "domain2.com"), null, 1);
    Assert.assertTrue(certificate != null);
    Assert.assertTrue(certificate.getPrivateKey() == null);
    Assert.assertEquals(certificate.getCaCertificates().get(0), caCertificate);
    Assert.assertTrue(certificate.getClientCertificate().getSubjectDN().toString().startsWith("CN=v-1-VM,"));
    certificate.getClientCertificate().verify(caCertificate.getPublicKey());
}
Also used : X509Certificate(java.security.cert.X509Certificate) Certificate(org.apache.cloudstack.framework.ca.Certificate) Test(org.junit.Test)

Aggregations

Certificate (org.apache.cloudstack.framework.ca.Certificate)11 X509Certificate (java.security.cert.X509Certificate)7 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)5 IOException (java.io.IOException)3 Test (org.junit.Test)3 KeyPair (java.security.KeyPair)2 ArrayList (java.util.ArrayList)2 ActionEvent (com.cloud.event.ActionEvent)1 AgentUnavailableException (com.cloud.exception.AgentUnavailableException)1 OperationTimedoutException (com.cloud.exception.OperationTimedoutException)1 Host (com.cloud.host.Host)1 SSHKeyPairVO (com.cloud.user.SSHKeyPairVO)1 SSHCmdHelper (com.cloud.utils.ssh.SSHCmdHelper)1 StringReader (java.io.StringReader)1 InetAddress (java.net.InetAddress)1 KeyStoreException (java.security.KeyStoreException)1 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1 CertificateException (java.security.cert.CertificateException)1 HashMap (java.util.HashMap)1 LinkedHashMap (java.util.LinkedHashMap)1