GutoVeronezi commented on code in PR #6577:
URL: https://github.com/apache/cloudstack/pull/6577#discussion_r967026872
##########
server/src/main/java/com/cloud/server/ManagementServerImpl.java:
##########
@@ -2847,6 +2849,42 @@ public String getConsoleAccessUrlRoot(final long vmId) {
return null;
}
+ @Override
+ public Pair<Boolean, String> setConsoleAccessForVm(long vmId, String
sessionUuid) {
+ final VMInstanceVO vm = _vmInstanceDao.findById(vmId);
+ if (vm == null) {
+ return new Pair<>(false, "Cannot find a VM with id = " + vmId);
+ }
+ final ConsoleProxyInfo proxy =
getConsoleProxyForVm(vm.getDataCenterId(), vmId);
+ if (proxy == null) {
+ return new Pair<>(false, "Cannot find a console proxy for the VM "
+ vmId);
+ }
+ AllowConsoleAccessCommand cmd = new
AllowConsoleAccessCommand(sessionUuid);
+ HostVO hostVO = _hostDao.findByTypeNameAndZoneId(vm.getDataCenterId(),
proxy.getProxyName(), Type.ConsoleProxy);
+ if (hostVO == null) {
+ return new Pair<>(false, "Cannot find a console proxy agent for
CPVM with name " + proxy.getProxyName());
+ }
+ Answer answer;
+ try {
+ answer = _agentMgr.send(hostVO.getId(), cmd);
+ } catch (AgentUnavailableException | OperationTimedoutException e) {
+ String errorMsg = "Could not send allow session command to CPVM: "
+ e.getMessage();
+ s_logger.error(errorMsg, e);
+ return new Pair<>(false, errorMsg);
+ }
+ return new Pair<>(answer != null && answer.getResult(), answer != null
? answer.getDetails() : "null answer");
Review Comment:
```suggestion
boolean result = false;
String details = "null answer";
if (answer != null) {
result = answer.getResult();
details = answer.getDetails();
}
return new Pair<>(result, details);
```
##########
server/src/main/java/com/cloud/servlet/ConsoleProxyClientParam.java:
##########
@@ -36,6 +36,15 @@ public class ConsoleProxyClientParam {
private String sourceIP;
private String websocketUrl;
+ private String sessionUuid;
+
+ // The server-side generated value for extra console endpoint validation
+ private String extraSecurityToken;
+
+ // The extra parameter received in the console URL, must be compared
against the server-side generated value
+ // for extra validation (if has been enabled)
Review Comment:
It could be a JavaDoc instead of a comment.
##########
server/src/main/java/org/apache/cloudstack/consoleproxy/ConsoleAccessManagerImpl.java:
##########
@@ -0,0 +1,489 @@
+// 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 org.apache.cloudstack.consoleproxy;
+
+import com.cloud.agent.AgentManager;
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.GetVmVncTicketAnswer;
+import com.cloud.agent.api.GetVmVncTicketCommand;
+import com.cloud.consoleproxy.ConsoleProxyManager;
+import com.cloud.exception.AgentUnavailableException;
+import com.cloud.exception.OperationTimedoutException;
+import com.cloud.exception.PermissionDeniedException;
+import com.cloud.host.HostVO;
+import com.cloud.hypervisor.Hypervisor;
+import com.cloud.resource.ResourceState;
+import com.cloud.server.ManagementServer;
+import com.cloud.servlet.ConsoleProxyClientParam;
+import com.cloud.servlet.ConsoleProxyPasswordBasedEncryptor;
+import com.cloud.storage.GuestOSVO;
+import com.cloud.user.Account;
+import com.cloud.user.AccountManager;
+import com.cloud.utils.Pair;
+import com.cloud.utils.Ternary;
+import com.cloud.utils.component.ManagerBase;
+import com.cloud.utils.db.EntityManager;
+import com.cloud.utils.exception.CloudRuntimeException;
+import com.cloud.vm.UserVmDetailVO;
+import com.cloud.vm.VirtualMachine;
+import com.cloud.vm.VirtualMachineManager;
+import com.cloud.vm.VmDetailConstants;
+import com.cloud.vm.dao.UserVmDetailsDao;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import org.apache.cloudstack.api.command.user.consoleproxy.ConsoleEndpoint;
+import org.apache.cloudstack.context.CallContext;
+import org.apache.cloudstack.framework.config.ConfigKey;
+import org.apache.cloudstack.framework.security.keys.KeysManager;
+import org.apache.commons.codec.binary.Base64;
+import org.apache.commons.lang3.BooleanUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.log4j.Logger;
+
+import javax.crypto.Mac;
+import javax.crypto.spec.SecretKeySpec;
+import javax.inject.Inject;
+import javax.naming.ConfigurationException;
+
+import java.util.Date;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+
+public class ConsoleAccessManagerImpl extends ManagerBase implements
ConsoleAccessManager {
+
+ @Inject
+ private AccountManager accountManager;
+ @Inject
+ private VirtualMachineManager virtualMachineManager;
+ @Inject
+ private ManagementServer managementServer;
+ @Inject
+ private EntityManager entityManager;
+ @Inject
+ private UserVmDetailsDao userVmDetailsDao;
+ @Inject
+ private KeysManager keysManager;
+ @Inject
+ private AgentManager agentManager;
+ @Inject
+ private ConsoleProxyManager consoleProxyManager;
+
+ private static KeysManager secretKeysManager;
+ private final Gson gson = new GsonBuilder().create();
+
+ public static final Logger s_logger =
Logger.getLogger(ConsoleAccessManagerImpl.class.getName());
+
+ private static Set<String> allowedSessions;
+
+ @Override
+ public boolean configure(String name, Map<String, Object> params) throws
ConfigurationException {
+ ConsoleAccessManagerImpl.secretKeysManager = keysManager;
+ ConsoleAccessManagerImpl.allowedSessions = new HashSet<>();
+ return super.configure(name, params);
+ }
+
+ @Override
+ public ConsoleEndpoint generateConsoleEndpoint(Long vmId, String
extraSecurityToken, String clientAddress) {
+ try {
+ if (accountManager == null || virtualMachineManager == null ||
managementServer == null) {
Review Comment:
We could use `org.apache.commons.lang3.ObjectUtils#anyNull()` here:
```suggestion
if (ObjectUtils.anyNull(accountManager, virtualMachineManager,
managementServer)) {
```
##########
api/src/main/java/org/apache/cloudstack/consoleproxy/ConsoleAccessManager.java:
##########
@@ -0,0 +1,35 @@
+// 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 org.apache.cloudstack.consoleproxy;
+
+import com.cloud.utils.component.Manager;
+import org.apache.cloudstack.api.command.user.consoleproxy.ConsoleEndpoint;
+import org.apache.cloudstack.framework.config.ConfigKey;
+import org.apache.cloudstack.framework.config.Configurable;
+
+public interface ConsoleAccessManager extends Manager, Configurable {
+
+ ConfigKey<Boolean> ConsoleProxyExtraSecurityValidationEnabled = new
ConfigKey<>(ConfigKey.CATEGORY_ADVANCED, Boolean.class,
+ "consoleproxy.extra.security.validation.enabled", "false",
+ "Enable/disable extra security validation for console proxy using
an extra token", true);
Review Comment:
```suggestion
"Enable/disable extra security validation for console proxy
using an extra token.", true);
```
##########
server/src/main/java/com/cloud/servlet/ConsoleProxyClientParam.java:
##########
@@ -36,6 +36,15 @@ public class ConsoleProxyClientParam {
private String sourceIP;
private String websocketUrl;
+ private String sessionUuid;
+
+ // The server-side generated value for extra console endpoint validation
Review Comment:
It could be a JavaDoc instead of a comment.
##########
server/src/main/java/org/apache/cloudstack/consoleproxy/ConsoleAccessManagerImpl.java:
##########
@@ -0,0 +1,489 @@
+// 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 org.apache.cloudstack.consoleproxy;
+
+import com.cloud.agent.AgentManager;
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.GetVmVncTicketAnswer;
+import com.cloud.agent.api.GetVmVncTicketCommand;
+import com.cloud.consoleproxy.ConsoleProxyManager;
+import com.cloud.exception.AgentUnavailableException;
+import com.cloud.exception.OperationTimedoutException;
+import com.cloud.exception.PermissionDeniedException;
+import com.cloud.host.HostVO;
+import com.cloud.hypervisor.Hypervisor;
+import com.cloud.resource.ResourceState;
+import com.cloud.server.ManagementServer;
+import com.cloud.servlet.ConsoleProxyClientParam;
+import com.cloud.servlet.ConsoleProxyPasswordBasedEncryptor;
+import com.cloud.storage.GuestOSVO;
+import com.cloud.user.Account;
+import com.cloud.user.AccountManager;
+import com.cloud.utils.Pair;
+import com.cloud.utils.Ternary;
+import com.cloud.utils.component.ManagerBase;
+import com.cloud.utils.db.EntityManager;
+import com.cloud.utils.exception.CloudRuntimeException;
+import com.cloud.vm.UserVmDetailVO;
+import com.cloud.vm.VirtualMachine;
+import com.cloud.vm.VirtualMachineManager;
+import com.cloud.vm.VmDetailConstants;
+import com.cloud.vm.dao.UserVmDetailsDao;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import org.apache.cloudstack.api.command.user.consoleproxy.ConsoleEndpoint;
+import org.apache.cloudstack.context.CallContext;
+import org.apache.cloudstack.framework.config.ConfigKey;
+import org.apache.cloudstack.framework.security.keys.KeysManager;
+import org.apache.commons.codec.binary.Base64;
+import org.apache.commons.lang3.BooleanUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.log4j.Logger;
+
+import javax.crypto.Mac;
+import javax.crypto.spec.SecretKeySpec;
+import javax.inject.Inject;
+import javax.naming.ConfigurationException;
+
+import java.util.Date;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+
+public class ConsoleAccessManagerImpl extends ManagerBase implements
ConsoleAccessManager {
+
+ @Inject
+ private AccountManager accountManager;
+ @Inject
+ private VirtualMachineManager virtualMachineManager;
+ @Inject
+ private ManagementServer managementServer;
+ @Inject
+ private EntityManager entityManager;
+ @Inject
+ private UserVmDetailsDao userVmDetailsDao;
+ @Inject
+ private KeysManager keysManager;
+ @Inject
+ private AgentManager agentManager;
+ @Inject
+ private ConsoleProxyManager consoleProxyManager;
+
+ private static KeysManager secretKeysManager;
+ private final Gson gson = new GsonBuilder().create();
+
+ public static final Logger s_logger =
Logger.getLogger(ConsoleAccessManagerImpl.class.getName());
+
+ private static Set<String> allowedSessions;
+
+ @Override
+ public boolean configure(String name, Map<String, Object> params) throws
ConfigurationException {
+ ConsoleAccessManagerImpl.secretKeysManager = keysManager;
+ ConsoleAccessManagerImpl.allowedSessions = new HashSet<>();
+ return super.configure(name, params);
+ }
+
+ @Override
+ public ConsoleEndpoint generateConsoleEndpoint(Long vmId, String
extraSecurityToken, String clientAddress) {
+ try {
+ if (accountManager == null || virtualMachineManager == null ||
managementServer == null) {
+ return new ConsoleEndpoint(false, null,"Console service is not
ready");
+ }
+
+ if (keysManager.getHashKey() == null) {
+ String msg = "Console access denied. Ticket service is not
ready yet";
+ s_logger.debug(msg);
+ return new ConsoleEndpoint(false, null, msg);
+ }
+
+ Account account = CallContext.current().getCallingAccount();
+
+ // Do a sanity check here to make sure the user hasn't already
been deleted
+ if (account == null) {
+ s_logger.debug("Invalid user/account, reject console access");
+ return new ConsoleEndpoint(false, null,"Access denied. Invalid
or inconsistent account is found");
+ }
+
+ VirtualMachine vm = entityManager.findById(VirtualMachine.class,
vmId);
+ if (vm == null) {
+ s_logger.info("Invalid console servlet command parameter: " +
vmId);
+ return new ConsoleEndpoint(false, null, "Cannot find VM with
ID " + vmId);
+ }
+
+ if (!checkSessionPermission(vm, account)) {
+ return new ConsoleEndpoint(false, null, "Permission denied");
+ }
+
+ if
(BooleanUtils.isTrue(ConsoleAccessManager.ConsoleProxyExtraSecurityValidationEnabled.value())
&&
+ StringUtils.isBlank(extraSecurityToken)) {
+ String errorMsg = "Extra security validation is enabled but
the extra token is missing";
+ s_logger.error(errorMsg);
+ return new ConsoleEndpoint(false, errorMsg);
+ }
+
+ String sessionUuid = UUID.randomUUID().toString();
+ return generateAccessEndpoint(vmId, sessionUuid,
extraSecurityToken, clientAddress);
+ } catch (Exception e) {
+ s_logger.error("Unexepected exception in ConsoleAccessManager", e);
Review Comment:
We could print the some context info here, like the `vmId` or the
`clientAddress`.
##########
api/src/main/java/org/apache/cloudstack/api/command/user/consoleproxy/CreateConsoleEndpointCmd.java:
##########
@@ -0,0 +1,120 @@
+// 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 org.apache.cloudstack.api.command.user.consoleproxy;
+
+import com.cloud.exception.ConcurrentOperationException;
+import com.cloud.exception.InsufficientCapacityException;
+import com.cloud.exception.NetworkRuleConflictException;
+import com.cloud.exception.ResourceAllocationException;
+import com.cloud.exception.ResourceUnavailableException;
+import org.apache.cloudstack.acl.RoleType;
+import org.apache.cloudstack.api.APICommand;
+import org.apache.cloudstack.api.ApiConstants;
+import org.apache.cloudstack.api.ApiErrorCode;
+import org.apache.cloudstack.api.BaseCmd;
+import org.apache.cloudstack.api.Parameter;
+import org.apache.cloudstack.api.ServerApiException;
+import org.apache.cloudstack.api.response.ConsoleEndpointWebsocketResponse;
+import org.apache.cloudstack.api.response.CreateConsoleEndpointResponse;
+import org.apache.cloudstack.api.response.UserVmResponse;
+import org.apache.cloudstack.consoleproxy.ConsoleAccessManager;
+import org.apache.cloudstack.context.CallContext;
+import org.apache.cloudstack.utils.consoleproxy.ConsoleAccessUtils;
+import org.apache.commons.collections.MapUtils;
+import org.apache.log4j.Logger;
+
+import javax.inject.Inject;
+import java.util.Map;
+
+@APICommand(name = CreateConsoleEndpointCmd.APINAME, description = "Create a
console endpoint to connect to a VM console",
+ responseObject = CreateConsoleEndpointResponse.class, since = "4.18.0",
+ requestHasSensitiveInfo = false, responseHasSensitiveInfo = false,
+ authorized = {RoleType.Admin, RoleType.ResourceAdmin,
RoleType.DomainAdmin, RoleType.User})
+public class CreateConsoleEndpointCmd extends BaseCmd {
+
+ public static final String APINAME = "createConsoleEndpoint";
+ public static final Logger s_logger =
Logger.getLogger(CreateConsoleEndpointCmd.class.getName());
+
+ @Inject
+ private ConsoleAccessManager consoleManager;
+
+ @Parameter(name = ApiConstants.VIRTUAL_MACHINE_ID,
+ type = CommandType.UUID,
+ entityType = UserVmResponse.class,
+ required = true,
+ description = "ID of the VM")
+ private Long vmId;
+
+ @Parameter(name = ApiConstants.TOKEN,
+ type = CommandType.STRING,
+ required = false,
+ description = "(optional) extra security token, valid when the
extra validation is enabled")
+ private String extraSecurityToken;
+
+ @Override
+ public void execute() throws ResourceUnavailableException,
InsufficientCapacityException, ServerApiException,
ConcurrentOperationException, ResourceAllocationException,
NetworkRuleConflictException {
+ String clientAddress = getClientAddress();
+ ConsoleEndpoint endpoint =
consoleManager.generateConsoleEndpoint(vmId, extraSecurityToken, clientAddress);
+ if (endpoint != null) {
+ CreateConsoleEndpointResponse response = createResponse(endpoint);
+ setResponseObject(response);
+ } else {
+ throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Unable
to generate console endpoint for vm " + vmId);
+ }
+ }
+
+ private CreateConsoleEndpointResponse createResponse(ConsoleEndpoint
endpoint) {
+ CreateConsoleEndpointResponse response = new
CreateConsoleEndpointResponse();
+ response.setResult(endpoint.isResult());
+ response.setDetails(endpoint.getDetails());
+ response.setUrl(endpoint.getUrl());
+ response.setWebsocketResponse(createWebsocketResponse(endpoint));
+ response.setResponseName(getCommandName());
+ response.setObjectName("consoleendpoint");
+ return response;
+ }
+
+ private ConsoleEndpointWebsocketResponse
createWebsocketResponse(ConsoleEndpoint endpoint) {
+ ConsoleEndpointWebsocketResponse wsResponse = new
ConsoleEndpointWebsocketResponse();
+ wsResponse.setHost(endpoint.getWebsocketHost());
+ wsResponse.setPort(endpoint.getWebsocketPort());
+ wsResponse.setPath(endpoint.getWebsocketPath());
+ wsResponse.setToken(endpoint.getWebsocketToken());
+ wsResponse.setExtra(endpoint.getWebsocketExtra());
+ wsResponse.setObjectName("websocket");
+ return wsResponse;
+ }
+
+ private String getParameterBase(String paramKey) {
+ Map<String, String> params = getFullUrlParams();
+ return MapUtils.isNotEmpty(params) && params.containsKey(paramKey) ?
params.get(paramKey) : null;
Review Comment:
[Map#get] already returns `null` if there is no mapping for the key.
```suggestion
return MapUtils.isNotEmpty(params) ? params.get(paramKey) : null;
```
[Map#get]:
https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#get-java.lang.Object-
##########
server/src/main/java/org/apache/cloudstack/consoleproxy/ConsoleAccessManagerImpl.java:
##########
@@ -0,0 +1,489 @@
+// 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 org.apache.cloudstack.consoleproxy;
+
+import com.cloud.agent.AgentManager;
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.GetVmVncTicketAnswer;
+import com.cloud.agent.api.GetVmVncTicketCommand;
+import com.cloud.consoleproxy.ConsoleProxyManager;
+import com.cloud.exception.AgentUnavailableException;
+import com.cloud.exception.OperationTimedoutException;
+import com.cloud.exception.PermissionDeniedException;
+import com.cloud.host.HostVO;
+import com.cloud.hypervisor.Hypervisor;
+import com.cloud.resource.ResourceState;
+import com.cloud.server.ManagementServer;
+import com.cloud.servlet.ConsoleProxyClientParam;
+import com.cloud.servlet.ConsoleProxyPasswordBasedEncryptor;
+import com.cloud.storage.GuestOSVO;
+import com.cloud.user.Account;
+import com.cloud.user.AccountManager;
+import com.cloud.utils.Pair;
+import com.cloud.utils.Ternary;
+import com.cloud.utils.component.ManagerBase;
+import com.cloud.utils.db.EntityManager;
+import com.cloud.utils.exception.CloudRuntimeException;
+import com.cloud.vm.UserVmDetailVO;
+import com.cloud.vm.VirtualMachine;
+import com.cloud.vm.VirtualMachineManager;
+import com.cloud.vm.VmDetailConstants;
+import com.cloud.vm.dao.UserVmDetailsDao;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import org.apache.cloudstack.api.command.user.consoleproxy.ConsoleEndpoint;
+import org.apache.cloudstack.context.CallContext;
+import org.apache.cloudstack.framework.config.ConfigKey;
+import org.apache.cloudstack.framework.security.keys.KeysManager;
+import org.apache.commons.codec.binary.Base64;
+import org.apache.commons.lang3.BooleanUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.log4j.Logger;
+
+import javax.crypto.Mac;
+import javax.crypto.spec.SecretKeySpec;
+import javax.inject.Inject;
+import javax.naming.ConfigurationException;
+
+import java.util.Date;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+
+public class ConsoleAccessManagerImpl extends ManagerBase implements
ConsoleAccessManager {
+
+ @Inject
+ private AccountManager accountManager;
+ @Inject
+ private VirtualMachineManager virtualMachineManager;
+ @Inject
+ private ManagementServer managementServer;
+ @Inject
+ private EntityManager entityManager;
+ @Inject
+ private UserVmDetailsDao userVmDetailsDao;
+ @Inject
+ private KeysManager keysManager;
+ @Inject
+ private AgentManager agentManager;
+ @Inject
+ private ConsoleProxyManager consoleProxyManager;
+
+ private static KeysManager secretKeysManager;
+ private final Gson gson = new GsonBuilder().create();
+
+ public static final Logger s_logger =
Logger.getLogger(ConsoleAccessManagerImpl.class.getName());
+
+ private static Set<String> allowedSessions;
+
+ @Override
+ public boolean configure(String name, Map<String, Object> params) throws
ConfigurationException {
+ ConsoleAccessManagerImpl.secretKeysManager = keysManager;
+ ConsoleAccessManagerImpl.allowedSessions = new HashSet<>();
+ return super.configure(name, params);
+ }
+
+ @Override
+ public ConsoleEndpoint generateConsoleEndpoint(Long vmId, String
extraSecurityToken, String clientAddress) {
+ try {
+ if (accountManager == null || virtualMachineManager == null ||
managementServer == null) {
+ return new ConsoleEndpoint(false, null,"Console service is not
ready");
+ }
+
+ if (keysManager.getHashKey() == null) {
+ String msg = "Console access denied. Ticket service is not
ready yet";
+ s_logger.debug(msg);
+ return new ConsoleEndpoint(false, null, msg);
+ }
+
+ Account account = CallContext.current().getCallingAccount();
+
+ // Do a sanity check here to make sure the user hasn't already
been deleted
+ if (account == null) {
+ s_logger.debug("Invalid user/account, reject console access");
+ return new ConsoleEndpoint(false, null,"Access denied. Invalid
or inconsistent account is found");
+ }
+
+ VirtualMachine vm = entityManager.findById(VirtualMachine.class,
vmId);
+ if (vm == null) {
+ s_logger.info("Invalid console servlet command parameter: " +
vmId);
+ return new ConsoleEndpoint(false, null, "Cannot find VM with
ID " + vmId);
+ }
+
+ if (!checkSessionPermission(vm, account)) {
+ return new ConsoleEndpoint(false, null, "Permission denied");
+ }
+
+ if
(BooleanUtils.isTrue(ConsoleAccessManager.ConsoleProxyExtraSecurityValidationEnabled.value())
&&
+ StringUtils.isBlank(extraSecurityToken)) {
+ String errorMsg = "Extra security validation is enabled but
the extra token is missing";
+ s_logger.error(errorMsg);
+ return new ConsoleEndpoint(false, errorMsg);
+ }
+
+ String sessionUuid = UUID.randomUUID().toString();
+ return generateAccessEndpoint(vmId, sessionUuid,
extraSecurityToken, clientAddress);
+ } catch (Exception e) {
+ s_logger.error("Unexepected exception in ConsoleAccessManager", e);
+ return new ConsoleEndpoint(false, null, "Server Internal Error: "
+ e.getMessage());
+ }
+ }
+
+ @Override
+ public boolean isSessionAllowed(String sessionUuid) {
+ return allowedSessions.contains(sessionUuid);
+ }
+
+ @Override
+ public void removeSessions(String[] sessionUuids) {
+ for (String r : sessionUuids) {
+ allowedSessions.remove(r);
+ }
+ }
+
+ protected boolean checkSessionPermission(VirtualMachine vm, Account
account) {
+ if (accountManager.isRootAdmin(account.getId())) {
+ return true;
+ }
+
+ switch (vm.getType()) {
+ case User:
+ try {
+ accountManager.checkAccess(account, null, true, vm);
+ } catch (PermissionDeniedException ex) {
+ if (accountManager.isNormalUser(account.getId())) {
+ if (s_logger.isDebugEnabled()) {
+ s_logger.debug("VM access is denied. VM owner
account " + vm.getAccountId() + " does not match the account id in session " +
+ account.getId() + " and caller is a normal
user");
+ }
+ } else if ((accountManager.isDomainAdmin(account.getId())
+ || account.getType() ==
Account.Type.READ_ONLY_ADMIN) && s_logger.isDebugEnabled()) {
+ s_logger.debug("VM access is denied. VM owner account
" + vm.getAccountId()
Review Comment:
We could print the VM ID here too.
##########
server/src/main/java/org/apache/cloudstack/consoleproxy/ConsoleAccessManagerImpl.java:
##########
@@ -0,0 +1,489 @@
+// 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 org.apache.cloudstack.consoleproxy;
+
+import com.cloud.agent.AgentManager;
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.GetVmVncTicketAnswer;
+import com.cloud.agent.api.GetVmVncTicketCommand;
+import com.cloud.consoleproxy.ConsoleProxyManager;
+import com.cloud.exception.AgentUnavailableException;
+import com.cloud.exception.OperationTimedoutException;
+import com.cloud.exception.PermissionDeniedException;
+import com.cloud.host.HostVO;
+import com.cloud.hypervisor.Hypervisor;
+import com.cloud.resource.ResourceState;
+import com.cloud.server.ManagementServer;
+import com.cloud.servlet.ConsoleProxyClientParam;
+import com.cloud.servlet.ConsoleProxyPasswordBasedEncryptor;
+import com.cloud.storage.GuestOSVO;
+import com.cloud.user.Account;
+import com.cloud.user.AccountManager;
+import com.cloud.utils.Pair;
+import com.cloud.utils.Ternary;
+import com.cloud.utils.component.ManagerBase;
+import com.cloud.utils.db.EntityManager;
+import com.cloud.utils.exception.CloudRuntimeException;
+import com.cloud.vm.UserVmDetailVO;
+import com.cloud.vm.VirtualMachine;
+import com.cloud.vm.VirtualMachineManager;
+import com.cloud.vm.VmDetailConstants;
+import com.cloud.vm.dao.UserVmDetailsDao;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import org.apache.cloudstack.api.command.user.consoleproxy.ConsoleEndpoint;
+import org.apache.cloudstack.context.CallContext;
+import org.apache.cloudstack.framework.config.ConfigKey;
+import org.apache.cloudstack.framework.security.keys.KeysManager;
+import org.apache.commons.codec.binary.Base64;
+import org.apache.commons.lang3.BooleanUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.log4j.Logger;
+
+import javax.crypto.Mac;
+import javax.crypto.spec.SecretKeySpec;
+import javax.inject.Inject;
+import javax.naming.ConfigurationException;
+
+import java.util.Date;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+
+public class ConsoleAccessManagerImpl extends ManagerBase implements
ConsoleAccessManager {
+
+ @Inject
+ private AccountManager accountManager;
+ @Inject
+ private VirtualMachineManager virtualMachineManager;
+ @Inject
+ private ManagementServer managementServer;
+ @Inject
+ private EntityManager entityManager;
+ @Inject
+ private UserVmDetailsDao userVmDetailsDao;
+ @Inject
+ private KeysManager keysManager;
+ @Inject
+ private AgentManager agentManager;
+ @Inject
+ private ConsoleProxyManager consoleProxyManager;
+
+ private static KeysManager secretKeysManager;
+ private final Gson gson = new GsonBuilder().create();
+
+ public static final Logger s_logger =
Logger.getLogger(ConsoleAccessManagerImpl.class.getName());
+
+ private static Set<String> allowedSessions;
+
+ @Override
+ public boolean configure(String name, Map<String, Object> params) throws
ConfigurationException {
+ ConsoleAccessManagerImpl.secretKeysManager = keysManager;
+ ConsoleAccessManagerImpl.allowedSessions = new HashSet<>();
+ return super.configure(name, params);
+ }
+
+ @Override
+ public ConsoleEndpoint generateConsoleEndpoint(Long vmId, String
extraSecurityToken, String clientAddress) {
+ try {
+ if (accountManager == null || virtualMachineManager == null ||
managementServer == null) {
+ return new ConsoleEndpoint(false, null,"Console service is not
ready");
+ }
+
+ if (keysManager.getHashKey() == null) {
+ String msg = "Console access denied. Ticket service is not
ready yet";
+ s_logger.debug(msg);
+ return new ConsoleEndpoint(false, null, msg);
+ }
+
+ Account account = CallContext.current().getCallingAccount();
+
+ // Do a sanity check here to make sure the user hasn't already
been deleted
+ if (account == null) {
+ s_logger.debug("Invalid user/account, reject console access");
+ return new ConsoleEndpoint(false, null,"Access denied. Invalid
or inconsistent account is found");
+ }
+
+ VirtualMachine vm = entityManager.findById(VirtualMachine.class,
vmId);
+ if (vm == null) {
+ s_logger.info("Invalid console servlet command parameter: " +
vmId);
+ return new ConsoleEndpoint(false, null, "Cannot find VM with
ID " + vmId);
+ }
+
+ if (!checkSessionPermission(vm, account)) {
+ return new ConsoleEndpoint(false, null, "Permission denied");
+ }
+
+ if
(BooleanUtils.isTrue(ConsoleAccessManager.ConsoleProxyExtraSecurityValidationEnabled.value())
&&
+ StringUtils.isBlank(extraSecurityToken)) {
+ String errorMsg = "Extra security validation is enabled but
the extra token is missing";
+ s_logger.error(errorMsg);
+ return new ConsoleEndpoint(false, errorMsg);
+ }
+
+ String sessionUuid = UUID.randomUUID().toString();
+ return generateAccessEndpoint(vmId, sessionUuid,
extraSecurityToken, clientAddress);
+ } catch (Exception e) {
+ s_logger.error("Unexepected exception in ConsoleAccessManager", e);
+ return new ConsoleEndpoint(false, null, "Server Internal Error: "
+ e.getMessage());
+ }
+ }
+
+ @Override
+ public boolean isSessionAllowed(String sessionUuid) {
+ return allowedSessions.contains(sessionUuid);
+ }
+
+ @Override
+ public void removeSessions(String[] sessionUuids) {
+ for (String r : sessionUuids) {
+ allowedSessions.remove(r);
+ }
+ }
+
+ protected boolean checkSessionPermission(VirtualMachine vm, Account
account) {
+ if (accountManager.isRootAdmin(account.getId())) {
+ return true;
+ }
+
+ switch (vm.getType()) {
+ case User:
+ try {
+ accountManager.checkAccess(account, null, true, vm);
+ } catch (PermissionDeniedException ex) {
+ if (accountManager.isNormalUser(account.getId())) {
+ if (s_logger.isDebugEnabled()) {
+ s_logger.debug("VM access is denied. VM owner
account " + vm.getAccountId() + " does not match the account id in session " +
Review Comment:
We could print the VM ID here too.
##########
server/src/main/java/org/apache/cloudstack/consoleproxy/ConsoleAccessManagerImpl.java:
##########
@@ -0,0 +1,489 @@
+// 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 org.apache.cloudstack.consoleproxy;
+
+import com.cloud.agent.AgentManager;
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.GetVmVncTicketAnswer;
+import com.cloud.agent.api.GetVmVncTicketCommand;
+import com.cloud.consoleproxy.ConsoleProxyManager;
+import com.cloud.exception.AgentUnavailableException;
+import com.cloud.exception.OperationTimedoutException;
+import com.cloud.exception.PermissionDeniedException;
+import com.cloud.host.HostVO;
+import com.cloud.hypervisor.Hypervisor;
+import com.cloud.resource.ResourceState;
+import com.cloud.server.ManagementServer;
+import com.cloud.servlet.ConsoleProxyClientParam;
+import com.cloud.servlet.ConsoleProxyPasswordBasedEncryptor;
+import com.cloud.storage.GuestOSVO;
+import com.cloud.user.Account;
+import com.cloud.user.AccountManager;
+import com.cloud.utils.Pair;
+import com.cloud.utils.Ternary;
+import com.cloud.utils.component.ManagerBase;
+import com.cloud.utils.db.EntityManager;
+import com.cloud.utils.exception.CloudRuntimeException;
+import com.cloud.vm.UserVmDetailVO;
+import com.cloud.vm.VirtualMachine;
+import com.cloud.vm.VirtualMachineManager;
+import com.cloud.vm.VmDetailConstants;
+import com.cloud.vm.dao.UserVmDetailsDao;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import org.apache.cloudstack.api.command.user.consoleproxy.ConsoleEndpoint;
+import org.apache.cloudstack.context.CallContext;
+import org.apache.cloudstack.framework.config.ConfigKey;
+import org.apache.cloudstack.framework.security.keys.KeysManager;
+import org.apache.commons.codec.binary.Base64;
+import org.apache.commons.lang3.BooleanUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.log4j.Logger;
+
+import javax.crypto.Mac;
+import javax.crypto.spec.SecretKeySpec;
+import javax.inject.Inject;
+import javax.naming.ConfigurationException;
+
+import java.util.Date;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+
+public class ConsoleAccessManagerImpl extends ManagerBase implements
ConsoleAccessManager {
+
+ @Inject
+ private AccountManager accountManager;
+ @Inject
+ private VirtualMachineManager virtualMachineManager;
+ @Inject
+ private ManagementServer managementServer;
+ @Inject
+ private EntityManager entityManager;
+ @Inject
+ private UserVmDetailsDao userVmDetailsDao;
+ @Inject
+ private KeysManager keysManager;
+ @Inject
+ private AgentManager agentManager;
+ @Inject
+ private ConsoleProxyManager consoleProxyManager;
+
+ private static KeysManager secretKeysManager;
+ private final Gson gson = new GsonBuilder().create();
+
+ public static final Logger s_logger =
Logger.getLogger(ConsoleAccessManagerImpl.class.getName());
+
+ private static Set<String> allowedSessions;
+
+ @Override
+ public boolean configure(String name, Map<String, Object> params) throws
ConfigurationException {
+ ConsoleAccessManagerImpl.secretKeysManager = keysManager;
+ ConsoleAccessManagerImpl.allowedSessions = new HashSet<>();
+ return super.configure(name, params);
+ }
+
+ @Override
+ public ConsoleEndpoint generateConsoleEndpoint(Long vmId, String
extraSecurityToken, String clientAddress) {
+ try {
+ if (accountManager == null || virtualMachineManager == null ||
managementServer == null) {
+ return new ConsoleEndpoint(false, null,"Console service is not
ready");
Review Comment:
```suggestion
return new ConsoleEndpoint(false, null, "Console service is
not ready");
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]