Skip to content
Closed
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
2 changes: 2 additions & 0 deletions engine/schema/src/com/cloud/user/dao/SSHKeyPairDao.java
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,6 @@ public interface SSHKeyPairDao extends GenericDao<SSHKeyPairVO, Long> {

public boolean deleteByName(long accountId, long domainId, String name);

public SSHKeyPairVO findByPublicKey(long accountId, long domainId, String publicKey);

}
9 changes: 9 additions & 0 deletions engine/schema/src/com/cloud/user/dao/SSHKeyPairDaoImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,15 @@ public SSHKeyPairVO findByPublicKey(String publicKey) {
return findOneBy(sc);
}

@Override
public SSHKeyPairVO findByPublicKey(long accountId, long domainId, String publicKey) {
SearchCriteria<SSHKeyPairVO> sc = createSearchCriteria();
sc.addAnd("accountId", SearchCriteria.Op.EQ, accountId);
sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId);
sc.addAnd("publicKey", SearchCriteria.Op.EQ, publicKey);
return findOneBy(sc);
}

@Override
public boolean deleteByName(long accountId, long domainId, String name) {
SSHKeyPairVO pair = findByName(accountId, domainId, name);
Expand Down
121 changes: 88 additions & 33 deletions server/src/com/cloud/server/ManagementServerImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,9 @@
import javax.inject.Inject;
import javax.naming.ConfigurationException;

import org.apache.cloudstack.api.command.admin.usage.RemoveRawUsageRecordsCmd;
import org.apache.cloudstack.api.command.user.snapshot.UpdateSnapshotPolicyCmd;
import org.apache.cloudstack.api.command.user.template.GetUploadParamsForTemplateCmd;
import org.apache.cloudstack.api.command.user.volume.GetUploadParamsForVolumeCmd;
import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;

import org.apache.cloudstack.acl.ControlledEntity;
import org.apache.cloudstack.affinity.AffinityGroupProcessor;
import org.apache.cloudstack.affinity.dao.AffinityGroupVMMapDao;
Expand Down Expand Up @@ -182,8 +179,8 @@
import org.apache.cloudstack.api.command.admin.storage.ListS3sCmd;
import org.apache.cloudstack.api.command.admin.storage.ListSecondaryStagingStoresCmd;
import org.apache.cloudstack.api.command.admin.storage.ListStoragePoolsCmd;
import org.apache.cloudstack.api.command.admin.storage.ListStorageTagsCmd;
import org.apache.cloudstack.api.command.admin.storage.ListStorageProvidersCmd;
import org.apache.cloudstack.api.command.admin.storage.ListStorageTagsCmd;
import org.apache.cloudstack.api.command.admin.storage.PreparePrimaryStorageForMaintenanceCmd;
import org.apache.cloudstack.api.command.admin.storage.UpdateCloudToUseObjectStoreCmd;
import org.apache.cloudstack.api.command.admin.storage.UpdateStoragePoolCmd;
Expand Down Expand Up @@ -213,6 +210,7 @@
import org.apache.cloudstack.api.command.admin.usage.ListTrafficTypeImplementorsCmd;
import org.apache.cloudstack.api.command.admin.usage.ListTrafficTypesCmd;
import org.apache.cloudstack.api.command.admin.usage.ListUsageTypesCmd;
import org.apache.cloudstack.api.command.admin.usage.RemoveRawUsageRecordsCmd;
import org.apache.cloudstack.api.command.admin.usage.UpdateTrafficTypeCmd;
import org.apache.cloudstack.api.command.admin.user.CreateUserCmd;
import org.apache.cloudstack.api.command.admin.user.DeleteUserCmd;
Expand Down Expand Up @@ -414,6 +412,7 @@
import org.apache.cloudstack.api.command.user.snapshot.ListSnapshotPoliciesCmd;
import org.apache.cloudstack.api.command.user.snapshot.ListSnapshotsCmd;
import org.apache.cloudstack.api.command.user.snapshot.RevertSnapshotCmd;
import org.apache.cloudstack.api.command.user.snapshot.UpdateSnapshotPolicyCmd;
import org.apache.cloudstack.api.command.user.ssh.CreateSSHKeyPairCmd;
import org.apache.cloudstack.api.command.user.ssh.DeleteSSHKeyPairCmd;
import org.apache.cloudstack.api.command.user.ssh.ListSSHKeyPairsCmd;
Expand All @@ -425,6 +424,7 @@
import org.apache.cloudstack.api.command.user.template.CreateTemplateCmd;
import org.apache.cloudstack.api.command.user.template.DeleteTemplateCmd;
import org.apache.cloudstack.api.command.user.template.ExtractTemplateCmd;
import org.apache.cloudstack.api.command.user.template.GetUploadParamsForTemplateCmd;
import org.apache.cloudstack.api.command.user.template.ListTemplatePermissionsCmd;
import org.apache.cloudstack.api.command.user.template.ListTemplatesCmd;
import org.apache.cloudstack.api.command.user.template.RegisterTemplateCmd;
Expand Down Expand Up @@ -463,6 +463,7 @@
import org.apache.cloudstack.api.command.user.volume.DeleteVolumeCmd;
import org.apache.cloudstack.api.command.user.volume.DetachVolumeCmd;
import org.apache.cloudstack.api.command.user.volume.ExtractVolumeCmd;
import org.apache.cloudstack.api.command.user.volume.GetUploadParamsForVolumeCmd;
import org.apache.cloudstack.api.command.user.volume.ListResourceDetailsCmd;
import org.apache.cloudstack.api.command.user.volume.ListVolumesCmd;
import org.apache.cloudstack.api.command.user.volume.MigrateVolumeCmd;
Expand Down Expand Up @@ -749,7 +750,7 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe
@Inject
private InstanceGroupDao _vmGroupDao;
@Inject
private SSHKeyPairDao _sshKeyPairDao;
protected SSHKeyPairDao _sshKeyPairDao;
@Inject
private LoadBalancerDao _loadbalancerDao;
@Inject
Expand Down Expand Up @@ -946,7 +947,7 @@ protected void checkPortParameters(String publicPort, String privatePort, String

@Override
public boolean archiveEvents(ArchiveEventsCmd cmd) {
Account caller = CallContext.current().getCallingAccount();
Account caller = getCaller();
List<Long> ids = cmd.getIds();
boolean result = true;
List<Long> permittedAccountIds = new ArrayList<Long>();
Expand All @@ -973,7 +974,7 @@ public boolean archiveEvents(ArchiveEventsCmd cmd) {

@Override
public boolean deleteEvents(DeleteEventsCmd cmd) {
Account caller = CallContext.current().getCallingAccount();
Account caller = getCaller();
List<Long> ids = cmd.getIds();
boolean result = true;
List<Long> permittedAccountIds = new ArrayList<Long>();
Expand Down Expand Up @@ -1097,8 +1098,7 @@ public Pair<List<? extends Host>, Integer> searchForServers(ListHostsCmd cmd) {

@Override
public Ternary<Pair<List<? extends Host>, Integer>, List<? extends Host>, Map<Host, Boolean>> listHostsForMigrationOfVM(Long vmId, Long startIndex, Long pageSize) {
// access check - only root admin can migrate VM
Account caller = CallContext.current().getCallingAccount();
Account caller = getCaller();
if (!_accountMgr.isRootAdmin(caller.getId())) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Caller is not a root admin, permission denied to migrate the VM");
Expand Down Expand Up @@ -1275,8 +1275,7 @@ private boolean hasSuitablePoolsForVolume(VolumeVO volume, Host host, VirtualMac

@Override
public Pair<List<? extends StoragePool>, List<? extends StoragePool>> listStoragePoolsForMigrationOfVolume(Long volumeId) {
// Access check - only root administrator can migrate volumes.
Account caller = CallContext.current().getCallingAccount();
Account caller = getCaller();
if (!_accountMgr.isRootAdmin(caller.getId())) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Caller is not a root admin, permission denied to migrate the volume");
Expand Down Expand Up @@ -1765,7 +1764,7 @@ public Pair<List<? extends IpAddress>, Integer> searchForIPAddresses(ListPublicI
List<Long> permittedAccounts = new ArrayList<Long>();
ListProjectResourcesCriteria listProjectResourcesCriteria = null;
if (isAllocated) {
Account caller = CallContext.current().getCallingAccount();
Account caller = getCaller();

Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(
cmd.getDomainId(), cmd.isRecursive(), null);
Expand Down Expand Up @@ -2258,8 +2257,7 @@ public DomainVO updateDomain(UpdateDomainCmd cmd) {
throw new InvalidParameterValueException("ROOT domain can not be edited with a new name");
}

// check permissions
Account caller = CallContext.current().getCallingAccount();
Account caller = getCaller();
_accountMgr.checkAccess(caller, domain);

// domain name is unique under the parent domain
Expand Down Expand Up @@ -3310,7 +3308,7 @@ private String signRequest(String request, String key) {

@Override
public ArrayList<String> getCloudIdentifierResponse(long userId) {
Account caller = CallContext.current().getCallingAccount();
Account caller = getCaller();

// verify that user exists
User user = _accountMgr.getUserIncludingRemoved(userId);
Expand Down Expand Up @@ -3350,7 +3348,7 @@ public ArrayList<String> getCloudIdentifierResponse(long userId) {
public Map<String, Object> listCapabilities(ListCapabilitiesCmd cmd) {
Map<String, Object> capabilities = new HashMap<String, Object>();

Account caller = CallContext.current().getCallingAccount();
Account caller = getCaller();
boolean securityGroupsEnabled = false;
boolean elasticLoadBalancerEnabled = false;
boolean KVMSnapshotEnabled = false;
Expand Down Expand Up @@ -3416,7 +3414,7 @@ public GuestOSHypervisorVO getGuestOsHypervisor(Long guestOsHypervisorId) {

@Override
public InstanceGroupVO updateVmGroup(UpdateVMGroupCmd cmd) {
Account caller = CallContext.current().getCallingAccount();
Account caller = getCaller();
Long groupId = cmd.getId();
String groupName = cmd.getGroupName();

Expand Down Expand Up @@ -3534,7 +3532,7 @@ public List<String> getHypervisors(Long zoneId) {

@Override
public SSHKeyPair createSSHKeyPair(CreateSSHKeyPairCmd cmd) {
Account caller = CallContext.current().getCallingAccount();
Account caller = getCaller();
String accountName = cmd.getAccountName();
Long domainId = cmd.getDomainId();
Long projectId = cmd.getProjectId();
Expand All @@ -3558,7 +3556,7 @@ public SSHKeyPair createSSHKeyPair(CreateSSHKeyPairCmd cmd) {

@Override
public boolean deleteSSHKeyPair(DeleteSSHKeyPairCmd cmd) {
Account caller = CallContext.current().getCallingAccount();
Account caller = getCaller();
String accountName = cmd.getAccountName();
Long domainId = cmd.getDomainId();
Long projectId = cmd.getProjectId();
Expand Down Expand Up @@ -3586,7 +3584,7 @@ public Pair<List<? extends SSHKeyPair>, Integer> listSSHKeyPairs(ListSSHKeyPairs
String name = cmd.getName();
String fingerPrint = cmd.getFingerprint();

Account caller = CallContext.current().getCallingAccount();
Account caller = getCaller();
List<Long> permittedAccounts = new ArrayList<Long>();

Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(
Expand Down Expand Up @@ -3618,30 +3616,87 @@ public Pair<List<? extends SSHKeyPair>, Integer> listSSHKeyPairs(ListSSHKeyPairs
@Override
@ActionEvent(eventType = EventTypes.EVENT_REGISTER_SSH_KEYPAIR, eventDescription = "registering ssh keypair", async = true)
public SSHKeyPair registerSSHKeyPair(RegisterSSHKeyPairCmd cmd) {
Account caller = CallContext.current().getCallingAccount();

Account owner = _accountMgr.finalizeOwner(caller, cmd.getAccountName(), cmd.getDomainId(), cmd.getProjectId());

SSHKeyPairVO s = _sshKeyPairDao.findByName(owner.getAccountId(), owner.getDomainId(), cmd.getName());
if (s != null) {
throw new InvalidParameterValueException("A key pair with name '" + cmd.getName() + "' already exists.");
}
Account owner = getOwner(cmd);
checkForKeyByName(cmd, owner);
checkForKeyByPublicKey(cmd, owner);

String name = cmd.getName();
String key = cmd.getPublicKey();
try {
key = URLDecoder.decode(key, "UTF-8");
} catch (UnsupportedEncodingException e) {
s_logger.warn("key decoding tried invain: " + e.getLocalizedMessage());
}
String publicKey = getPublicKeyFromKeyKeyMaterial(key);
String fingerprint = getFingerprint(publicKey);

return createAndSaveSSHKeyPair(name, fingerprint, publicKey, null, owner);
}

/**
* @param cmd
* @param owner
* @throws InvalidParameterValueException
*/
private void checkForKeyByPublicKey(RegisterSSHKeyPairCmd cmd, Account owner) throws InvalidParameterValueException {
SSHKeyPairVO existingPair = _sshKeyPairDao.findByPublicKey(owner.getAccountId(), owner.getDomainId(), cmd.getPublicKey());
if (existingPair != null) {
throw new InvalidParameterValueException("A key pair with name '" + cmd.getPublicKey() + "' already exists for this account.");
}
}

/**
* @param cmd
* @param owner
* @throws InvalidParameterValueException
*/
protected void checkForKeyByName(RegisterSSHKeyPairCmd cmd, Account owner) throws InvalidParameterValueException {
SSHKeyPairVO existingPair = _sshKeyPairDao.findByName(owner.getAccountId(), owner.getDomainId(), cmd.getName());
if (existingPair != null) {
throw new InvalidParameterValueException("A key pair with name '" + cmd.getName() + "' already exists for this account.");
}
}

/**
* @param publicKey
* @return
*/
private String getFingerprint(String publicKey) {
String fingerprint = SSHKeysHelper.getPublicKeyFingerprint(publicKey);
return fingerprint;
}

/**
* @param key
* @return
* @throws InvalidParameterValueException
*/
private String getPublicKeyFromKeyKeyMaterial(String key) throws InvalidParameterValueException {
String publicKey = SSHKeysHelper.getPublicKeyFromKeyMaterial(key);

if (publicKey == null) {
throw new InvalidParameterValueException("Public key is invalid");
}
return publicKey;
}

String fingerprint = SSHKeysHelper.getPublicKeyFingerprint(publicKey);
/**
* @param cmd
* @return
*/
protected Account getOwner(RegisterSSHKeyPairCmd cmd) {
Account caller = getCaller();

return createAndSaveSSHKeyPair(name, fingerprint, publicKey, null, owner);
Account owner = _accountMgr.finalizeOwner(caller, cmd.getAccountName(), cmd.getDomainId(), cmd.getProjectId());
return owner;
}

/**
* @return
*/
protected Account getCaller() {
Account caller = CallContext.current().getCallingAccount();
return caller;
}

private SSHKeyPair createAndSaveSSHKeyPair(String name, String fingerprint, String publicKey, String privateKey, Account owner) {
Expand All @@ -3661,7 +3716,7 @@ private SSHKeyPair createAndSaveSSHKeyPair(String name, String fingerprint, Stri

@Override
public String getVMPassword(GetVMPasswordCmd cmd) {
Account caller = CallContext.current().getCallingAccount();
Account caller = getCaller();

UserVmVO vm = _userVmDao.findById(cmd.getId());
if (vm == null) {
Expand Down Expand Up @@ -3837,7 +3892,7 @@ public VirtualMachine upgradeSystemVM(UpgradeSystemVMCmd cmd) {
}

private VirtualMachine upgradeStoppedSystemVm(Long systemVmId, Long serviceOfferingId, Map<String, String> customparameters) {
Account caller = CallContext.current().getCallingAccount();
Account caller = getCaller();

VMInstanceVO systemVm = _vmInstanceDao.findByIdTypes(systemVmId, VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm);
if (systemVm == null) {
Expand Down
67 changes: 67 additions & 0 deletions server/test/com/cloud/server/ManagementServerImplTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
// 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.server;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner;

import org.apache.cloudstack.api.command.user.ssh.RegisterSSHKeyPairCmd;

import com.cloud.exception.InvalidParameterValueException;
import com.cloud.user.Account;
import com.cloud.user.SSHKeyPairVO;
import com.cloud.user.dao.SSHKeyPairDao;

@RunWith(MockitoJUnitRunner.class)
public class ManagementServerImplTest {

@Mock
RegisterSSHKeyPairCmd regCmd;
@Mock
SSHKeyPairVO existingPair;
@Mock
Account account;
@Mock
SSHKeyPairDao sshKeyPairDao;
ManagementServerImpl ms = new ManagementServerImpl();
@Spy
ManagementServerImpl spy;

@Test(expected = InvalidParameterValueException.class)
public void testExistingPairRegistration() {
String accountName = "account";
String publicKeyString = "very public";
// setup owner with domainid
Mockito.doReturn(account).when(spy).getCaller();
Mockito.doReturn(account).when(spy).getOwner(regCmd);
// mock _sshKeyPairDao.findByName to return null
Mockito.doNothing().when(spy).checkForKeyByName(regCmd, account);
// mock _sshKeyPairDao.findByPublicKey to return a known object
Mockito.doReturn(accountName).when(regCmd).getAccountName();
Mockito.doReturn(publicKeyString).when(regCmd).getPublicKey();
Mockito.doReturn("name").when(regCmd).getName();
spy._sshKeyPairDao = sshKeyPairDao;
Mockito.doReturn(1L).when(account).getAccountId();
Mockito.doReturn(1L).when(account).getDomainId();
Mockito.doReturn(existingPair).when(sshKeyPairDao).findByPublicKey(1L, 1L, publicKeyString);
spy.registerSSHKeyPair(regCmd);
}
}