Skip to content
Merged
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
28 changes: 0 additions & 28 deletions agent/src/com/cloud/agent/Agent.java
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@

import javax.naming.ConfigurationException;

import org.apache.cloudstack.agent.directdownload.SetupDirectDownloadCertificate;
import org.apache.cloudstack.agent.lb.SetupMSListAnswer;
import org.apache.cloudstack.agent.lb.SetupMSListCommand;
import org.apache.cloudstack.ca.PostCertificateRenewalCommand;
Expand Down Expand Up @@ -630,8 +629,6 @@ protected void processRequest(final Request request, final Link link) {
if (Host.Type.Routing.equals(_resource.getType())) {
scheduleServicesRestartTask();
}
} else if (cmd instanceof SetupDirectDownloadCertificate) {
answer = setupDirectDownloadCertificate((SetupDirectDownloadCertificate) cmd);
} else if (cmd instanceof SetupMSListCommand) {
answer = setupManagementServerList((SetupMSListCommand) cmd);
} else {
Expand Down Expand Up @@ -683,31 +680,6 @@ protected void processRequest(final Request request, final Link link) {
}
}

private Answer setupDirectDownloadCertificate(SetupDirectDownloadCertificate cmd) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So, this is not used anymore?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, but moved to specific KVM code. Let me update the description

String certificate = cmd.getCertificate();
String certificateName = cmd.getCertificateName();
s_logger.info("Importing certificate " + certificateName + " into keystore");

final File agentFile = PropertiesUtil.findConfigFile("agent.properties");
if (agentFile == null) {
return new Answer(cmd, false, "Failed to find agent.properties file");
}

final String keyStoreFile = agentFile.getParent() + "/" + KeyStoreUtils.KS_FILENAME;

String cerFile = agentFile.getParent() + "/" + certificateName + ".cer";
Script.runSimpleBashScript(String.format("echo '%s' > %s", certificate, cerFile));

String privatePasswordFormat = "sed -n '/keystore.passphrase/p' '%s' 2>/dev/null | sed 's/keystore.passphrase=//g' 2>/dev/null";
String privatePasswordCmd = String.format(privatePasswordFormat, agentFile.getAbsolutePath());
String privatePassword = Script.runSimpleBashScript(privatePasswordCmd);

String importCommandFormat = "keytool -importcert -file %s -keystore %s -alias '%s' -storepass '%s' -noprompt";
String importCmd = String.format(importCommandFormat, cerFile, keyStoreFile, certificateName, privatePassword);
Script.runSimpleBashScript(importCmd);
return new Answer(cmd, true, "Certificate " + certificateName + " imported");
}

public Answer setupAgentKeystore(final SetupKeyStoreCommand cmd) {
final String keyStorePassword = cmd.getKeystorePassword();
final long validityDays = cmd.getValidityDays();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,19 +35,19 @@

import javax.inject.Inject;

@APICommand(name = UploadTemplateDirectDownloadCertificate.APINAME,
@APICommand(name = UploadTemplateDirectDownloadCertificateCmd.APINAME,
description = "Upload a certificate for HTTPS direct template download on KVM hosts",
responseObject = SuccessResponse.class,
requestHasSensitiveInfo = true,
responseHasSensitiveInfo = true,
since = "4.11.0",
authorized = {RoleType.Admin})
public class UploadTemplateDirectDownloadCertificate extends BaseCmd {
public class UploadTemplateDirectDownloadCertificateCmd extends BaseCmd {

@Inject
DirectDownloadManager directDownloadManager;

private static final Logger LOG = Logger.getLogger(UploadTemplateDirectDownloadCertificate.class);
private static final Logger LOG = Logger.getLogger(UploadTemplateDirectDownloadCertificateCmd.class);
public static final String APINAME = "uploadTemplateDirectDownloadCertificate";

@Parameter(name = ApiConstants.CERTIFICATE, type = BaseCmd.CommandType.STRING, required = true, length = 65535,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,12 @@

import com.cloud.agent.api.Command;

public class SetupDirectDownloadCertificate extends Command {
public class SetupDirectDownloadCertificateCommand extends Command {

private String certificate;
private String certificateName;

public SetupDirectDownloadCertificate(String certificate, String name) {
public SetupDirectDownloadCertificateCommand(String certificate, String name) {
this.certificate = certificate;
this.certificateName = name;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
//
// 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.hypervisor.kvm.resource.wrapper;

import com.cloud.agent.api.Answer;
import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
import com.cloud.resource.CommandWrapper;
import com.cloud.resource.ResourceWrapper;
import com.cloud.utils.PropertiesUtil;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.script.Script;
import org.apache.cloudstack.agent.directdownload.SetupDirectDownloadCertificateCommand;
import org.apache.cloudstack.utils.security.KeyStoreUtils;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import static org.apache.commons.lang.StringUtils.isBlank;

@ResourceWrapper(handles = SetupDirectDownloadCertificateCommand.class)
public class LibvirtSetupDirectDownloadCertificateCommandWrapper extends CommandWrapper<SetupDirectDownloadCertificateCommand, Answer, LibvirtComputingResource> {

private static final String temporaryCertFilePrefix = "CSCERTIFICATE";

private static final Logger s_logger = Logger.getLogger(LibvirtSetupDirectDownloadCertificateCommandWrapper.class);

/**
* Retrieve agent.properties file
*/
private File getAgentPropertiesFile() throws FileNotFoundException {
final File agentFile = PropertiesUtil.findConfigFile("agent.properties");
if (agentFile == null) {
throw new FileNotFoundException("Failed to find agent.properties file");
}
return agentFile;
}

/**
* Get the property 'keystore.passphrase' value from agent.properties file
*/
private String getKeystorePassword(File agentFile) {
String pass = null;
if (agentFile != null) {
try {
pass = PropertiesUtil.loadFromFile(agentFile).getProperty(KeyStoreUtils.KS_PASSPHRASE_PROPERTY);
} catch (IOException e) {
s_logger.error("Could not get 'keystore.passphrase' property value due to: " + e.getMessage());
}
}
return pass;
}

/**
* Get keystore path
*/
private String getKeyStoreFilePath(File agentFile) {
return agentFile.getParent() + "/" + KeyStoreUtils.KS_FILENAME;
}

/**
* Import certificate from temporary file into keystore
*/
private void importCertificate(String tempCerFilePath, String keyStoreFile, String certificateName, String privatePassword) {
s_logger.debug("Importing certificate from temporary file to keystore");
String importCommandFormat = "keytool -importcert -file %s -keystore %s -alias '%s' -storepass '%s' -noprompt";
String importCmd = String.format(importCommandFormat, tempCerFilePath, keyStoreFile, certificateName, privatePassword);
int result = Script.runSimpleBashScriptForExitValue(importCmd);
if (result != 0) {
s_logger.debug("Certificate " + certificateName + " not imported as it already exist on keystore");
}
}

/**
* Create temporary file and return its path
*/
private String createTemporaryFile(File agentFile, String certificateName, String certificate) {
String tempCerFilePath = String.format("%s/%s-%s",
agentFile.getParent(), temporaryCertFilePrefix, certificateName);
s_logger.debug("Creating temporary certificate file into: " + tempCerFilePath);
int result = Script.runSimpleBashScriptForExitValue(String.format("echo '%s' > %s", certificate, tempCerFilePath));
if (result != 0) {
throw new CloudRuntimeException("Could not create the certificate file on path: " + tempCerFilePath);
}
return tempCerFilePath;
}

/**
* Remove temporary file
*/
private void cleanupTemporaryFile(String temporaryFile) {
s_logger.debug("Cleaning up temporary certificate file");
Script.runSimpleBashScript("rm -f " + temporaryFile);
}

@Override
public Answer execute(SetupDirectDownloadCertificateCommand cmd, LibvirtComputingResource serverResource) {
String certificate = cmd.getCertificate();
String certificateName = cmd.getCertificateName();

try {
File agentFile = getAgentPropertiesFile();
String privatePassword = getKeystorePassword(agentFile);
if (isBlank(privatePassword)) {
return new Answer(cmd, false, "No password found for keystore: " + KeyStoreUtils.KS_FILENAME);
}

final String keyStoreFile = getKeyStoreFilePath(agentFile);
String temporaryFile = createTemporaryFile(agentFile, certificateName, certificate);
importCertificate(temporaryFile, keyStoreFile, certificateName, privatePassword);
cleanupTemporaryFile(temporaryFile);
} catch (FileNotFoundException | CloudRuntimeException e) {
s_logger.error("Error while setting up certificate " + certificateName, e);
return new Answer(cmd, false, e.getMessage());
}

return new Answer(cmd, true, "Certificate " + certificateName + " imported");
}
}
4 changes: 2 additions & 2 deletions server/src/com/cloud/server/ManagementServerImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@
import org.apache.cloudstack.api.command.admin.config.ListHypervisorCapabilitiesCmd;
import org.apache.cloudstack.api.command.admin.config.UpdateCfgCmd;
import org.apache.cloudstack.api.command.admin.config.UpdateHypervisorCapabilitiesCmd;
import org.apache.cloudstack.api.command.admin.direct.download.UploadTemplateDirectDownloadCertificate;
import org.apache.cloudstack.api.command.admin.direct.download.UploadTemplateDirectDownloadCertificateCmd;
import org.apache.cloudstack.api.command.admin.domain.CreateDomainCmd;
import org.apache.cloudstack.api.command.admin.domain.DeleteDomainCmd;
import org.apache.cloudstack.api.command.admin.domain.ListDomainChildrenCmd;
Expand Down Expand Up @@ -3051,7 +3051,7 @@ public List<Class<?>> getCommands() {
cmdList.add(ReleasePodIpCmdByAdmin.class);
cmdList.add(CreateManagementNetworkIpRangeCmd.class);
cmdList.add(DeleteManagementNetworkIpRangeCmd.class);
cmdList.add(UploadTemplateDirectDownloadCertificate.class);
cmdList.add(UploadTemplateDirectDownloadCertificateCmd.class);

// Out-of-band management APIs for admins
cmdList.add(EnableOutOfBandManagementForHostCmd.class);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,10 @@

import java.net.URI;
import java.net.URISyntaxException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateExpiredException;
import java.security.cert.CertificateNotYetValidException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
Expand All @@ -50,14 +54,15 @@
import java.util.stream.Collectors;
import javax.inject.Inject;

import com.cloud.utils.security.CertificateHelper;
import org.apache.cloudstack.agent.directdownload.DirectDownloadCommand;
import org.apache.cloudstack.agent.directdownload.DirectDownloadAnswer;
import org.apache.cloudstack.agent.directdownload.DirectDownloadCommand.DownloadProtocol;
import org.apache.cloudstack.agent.directdownload.HttpDirectDownloadCommand;
import org.apache.cloudstack.agent.directdownload.MetalinkDirectDownloadCommand;
import org.apache.cloudstack.agent.directdownload.NfsDirectDownloadCommand;
import org.apache.cloudstack.agent.directdownload.HttpsDirectDownloadCommand;
import org.apache.cloudstack.agent.directdownload.SetupDirectDownloadCertificate;
import org.apache.cloudstack.agent.directdownload.SetupDirectDownloadCertificateCommand;
import org.apache.cloudstack.context.CallContext;
import org.apache.cloudstack.engine.subsystem.api.storage.DataStore;
import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager;
Expand All @@ -69,6 +74,7 @@
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.log4j.Logger;
import sun.security.x509.X509CertImpl;

public class DirectDownloadManagerImpl extends ManagerBase implements DirectDownloadManager {

Expand Down Expand Up @@ -313,14 +319,66 @@ private List<HostVO> getRunningHostsToUploadCertificate(HypervisorType hyperviso
.collect(Collectors.toList());
}

/**
* Return pretified PEM certificate
*/
protected String getPretifiedCertificate(String certificateCer) {
String cert = certificateCer.replaceAll("(.{64})", "$1\n");
if (!cert.startsWith(BEGIN_CERT) && !cert.endsWith(END_CERT)) {
cert = BEGIN_CERT + LINE_SEPARATOR + cert + LINE_SEPARATOR + END_CERT;
}
return cert;
}

/**
* Generate and return certificate from the string
* @throws CloudRuntimeException if the certificate is not well formed
*/
private Certificate getCertificateFromString(String certificatePem) {
try {
return CertificateHelper.buildCertificate(certificatePem);
} catch (CertificateException e) {
e.printStackTrace();
throw new CloudRuntimeException("Cannot parse the certificate provided, please provide a PEM certificate. Error: " + e.getMessage());
}
}

/**
* Perform sanity of string parsed certificate
*/
protected void certificateSanity(String certificatePem) {
Certificate certificate = getCertificateFromString(certificatePem);

if (certificate instanceof X509CertImpl) {
X509CertImpl x509Cert = (X509CertImpl) certificate;
try {
x509Cert.checkValidity();
} catch (CertificateExpiredException | CertificateNotYetValidException e) {
String msg = "Certificate is invalid. Please provide a valid certificate. Error: " + e.getMessage();
s_logger.error(msg);
throw new CloudRuntimeException(msg);
}
if (x509Cert.getSubjectDN() != null) {
s_logger.debug("Valid certificate for domain name: " + x509Cert.getSubjectDN().getName());
}
}
}

@Override
public boolean uploadCertificateToHosts(String certificateCer, String certificateName, String hypervisor) {
public boolean uploadCertificateToHosts(String certificateCer, String alias, String hypervisor) {
HypervisorType hypervisorType = HypervisorType.getType(hypervisor);
List<HostVO> hosts = getRunningHostsToUploadCertificate(hypervisorType);

String certificatePem = getPretifiedCertificate(certificateCer);
certificateSanity(certificatePem);

s_logger.info("Attempting to upload certificate: " + alias + " to " + hosts.size() + " hosts");
if (CollectionUtils.isNotEmpty(hosts)) {
for (HostVO host : hosts) {
if (!uploadCertificate(certificateCer, certificateName, host.getId())) {
throw new CloudRuntimeException("Uploading certificate " + certificateName + " failed on host: " + host.getId());
if (!uploadCertificate(certificatePem, alias, host.getId())) {
String msg = "Could not upload certificate " + alias + " on host: " + host.getName() + " (" + host.getUuid() + ")";
s_logger.error(msg);
throw new CloudRuntimeException(msg);
}
}
}
Expand All @@ -331,14 +389,18 @@ public boolean uploadCertificateToHosts(String certificateCer, String certificat
* Upload and import certificate to hostId on keystore
*/
protected boolean uploadCertificate(String certificate, String certificateName, long hostId) {
String cert = certificate.replaceAll("(.{64})", "$1\n");
final String prettified_cert = BEGIN_CERT + LINE_SEPARATOR + cert + LINE_SEPARATOR + END_CERT;
SetupDirectDownloadCertificate cmd = new SetupDirectDownloadCertificate(prettified_cert, certificateName);
SetupDirectDownloadCertificateCommand cmd = new SetupDirectDownloadCertificateCommand(certificate, certificateName);
Answer answer = agentManager.easySend(hostId, cmd);
if (answer == null || !answer.getResult()) {
String msg = "Certificate " + certificateName + " could not be added to host " + hostId;
if (answer != null) {
msg += " due to: " + answer.getDetails();
}
s_logger.error(msg);
return false;
}
s_logger.info("Certificate " + certificateName + " successfully uploaded to host: " + hostId);
return true;
}

}
Loading