forked from apache/cloudstack
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathAgentHookBase.java
More file actions
296 lines (246 loc) · 13.4 KB
/
AgentHookBase.java
File metadata and controls
296 lines (246 loc) · 13.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
// 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.consoleproxy;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Date;
import org.apache.cloudstack.consoleproxy.ConsoleAccessManager;
import org.apache.cloudstack.consoleproxy.ConsoleAccessManagerImpl;
import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
import org.apache.cloudstack.framework.security.keys.KeysManager;
import org.apache.cloudstack.framework.security.keystore.KeystoreManager;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import com.cloud.agent.AgentManager;
import com.cloud.agent.api.AgentControlAnswer;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.ConsoleAccessAuthenticationAnswer;
import com.cloud.agent.api.ConsoleAccessAuthenticationCommand;
import com.cloud.agent.api.ConsoleProxyLoadReportCommand;
import com.cloud.agent.api.GetVncPortAnswer;
import com.cloud.agent.api.GetVncPortCommand;
import com.cloud.agent.api.StartupCommand;
import com.cloud.agent.api.StartupProxyCommand;
import com.cloud.agent.api.proxy.StartConsoleProxyAgentHttpHandlerCommand;
import com.cloud.configuration.Config;
import com.cloud.exception.AgentUnavailableException;
import com.cloud.exception.OperationTimedoutException;
import com.cloud.host.Host;
import com.cloud.host.HostVO;
import com.cloud.host.Status;
import com.cloud.host.dao.HostDao;
import com.cloud.servlet.ConsoleProxyPasswordBasedEncryptor;
import com.cloud.servlet.ConsoleProxyServlet;
import com.cloud.utils.Ternary;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.dao.VMInstanceDao;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
/**
* Utility class to manage interactions with agent-based console access
* Extracted from ConsoleProxyManagerImpl so that other console proxy managers
* can reuse
*/
public abstract class AgentHookBase implements AgentHook {
private static final Logger s_logger = Logger.getLogger(AgentHookBase.class);
VMInstanceDao _instanceDao;
HostDao _hostDao;
ConfigurationDao _configDao;
AgentManager _agentMgr;
KeystoreManager _ksMgr;
KeysManager _keysMgr;
ConsoleAccessManager consoleAccessManager;
protected AgentHookBase(VMInstanceDao instanceDao, HostDao hostDao, ConfigurationDao cfgDao, KeystoreManager ksMgr,
AgentManager agentMgr, KeysManager keysMgr, ConsoleAccessManager consoleAccessMgr) {
_instanceDao = instanceDao;
_hostDao = hostDao;
_agentMgr = agentMgr;
_configDao = cfgDao;
_ksMgr = ksMgr;
_keysMgr = keysMgr;
consoleAccessManager = consoleAccessMgr;
}
@Override
public AgentControlAnswer onConsoleAccessAuthentication(ConsoleAccessAuthenticationCommand cmd) {
Long vmId = null;
String ticketInUrl = cmd.getTicket();
String sessionUuid = cmd.getSessionUuid();
if (ticketInUrl == null) {
s_logger.error("Access ticket could not be found, you could be running an old version of console proxy. vmId: " + cmd.getVmId());
return new ConsoleAccessAuthenticationAnswer(cmd, false);
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Console authentication. Ticket in url for " + cmd.getHost() + ":" + cmd.getPort() + "-" + cmd.getVmId() + " is " + ticketInUrl);
}
if (!cmd.isReauthenticating()) {
String ticket = ConsoleAccessManagerImpl.genAccessTicket(cmd.getHost(), cmd.getPort(), cmd.getSid(), cmd.getVmId(), sessionUuid);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Console authentication. Ticket in 1 minute boundary for " + cmd.getHost() + ":" + cmd.getPort() + "-" + cmd.getVmId() + " is " + ticket);
}
if (!consoleAccessManager.isSessionAllowed(sessionUuid)) {
s_logger.error("Invalid session, only one session allowed per token");
return new ConsoleAccessAuthenticationAnswer(cmd, false);
}
s_logger.debug(String.format("Removing session [%s] from database because it is for an one time usage and we just validated it.", sessionUuid));
consoleAccessManager.removeSession(sessionUuid);
if (!ticket.equals(ticketInUrl)) {
Date now = new Date();
// considering of minute round-up
String minuteEarlyTicket = ConsoleAccessManagerImpl.genAccessTicket(cmd.getHost(), cmd.getPort(), cmd.getSid(), cmd.getVmId(), new Date(now.getTime() - 60 * 1000), sessionUuid);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Console authentication. Ticket in 2-minute boundary for " + cmd.getHost() + ":" + cmd.getPort() + "-" + cmd.getVmId() + " is " +
minuteEarlyTicket);
}
if (!minuteEarlyTicket.equals(ticketInUrl)) {
s_logger.error("Access ticket expired or has been modified. vmId: " + cmd.getVmId() + "ticket in URL: " + ticketInUrl +
", tickets to check against: " + ticket + "," + minuteEarlyTicket);
return new ConsoleAccessAuthenticationAnswer(cmd, false);
}
}
}
if (cmd.getVmId() != null && cmd.getVmId().isEmpty()) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Invalid vm id sent from proxy(happens when proxy session has terminated)");
}
return new ConsoleAccessAuthenticationAnswer(cmd, false);
}
VirtualMachine vm = _instanceDao.findByUuid(cmd.getVmId());
if (vm == null) {
vm = _instanceDao.findById(Long.parseLong(cmd.getVmId()));
}
if (vm == null) {
s_logger.error("Invalid vm id " + cmd.getVmId() + " sent from console access authentication");
return new ConsoleAccessAuthenticationAnswer(cmd, false);
}
if (vm.getHostId() == null) {
s_logger.warn("VM " + vmId + " lost host info, failed authentication request");
return new ConsoleAccessAuthenticationAnswer(cmd, false);
}
HostVO host = _hostDao.findById(vm.getHostId());
if (host == null) {
s_logger.warn("VM " + vmId + "'s host does not exist, fail authentication request");
return new ConsoleAccessAuthenticationAnswer(cmd, false);
}
String sid = cmd.getSid();
if (sid == null || !sid.equals(vm.getVncPassword())) {
s_logger.warn("sid " + sid + " in url does not match stored sid.");
return new ConsoleAccessAuthenticationAnswer(cmd, false);
}
if (cmd.isReauthenticating()) {
ConsoleAccessAuthenticationAnswer authenticationAnswer = new ConsoleAccessAuthenticationAnswer(cmd, true);
authenticationAnswer.setReauthenticating(true);
s_logger.info("Re-authentication request, ask host " + vm.getHostId() + " for new console info");
GetVncPortAnswer answer = (GetVncPortAnswer)_agentMgr.easySend(vm.getHostId(), new GetVncPortCommand(vm.getId(), vm.getInstanceName()));
if (answer != null && answer.getResult()) {
Ternary<String, String, String> parsedHostInfo = ConsoleProxyServlet.parseHostInfo(answer.getAddress());
if (parsedHostInfo.second() != null && parsedHostInfo.third() != null) {
s_logger.info("Re-authentication result. vm: " + vm.getId() + ", tunnel url: " + parsedHostInfo.second() + ", tunnel session: " +
parsedHostInfo.third());
authenticationAnswer.setTunnelUrl(parsedHostInfo.second());
authenticationAnswer.setTunnelSession(parsedHostInfo.third());
} else {
s_logger.info("Re-authentication result. vm: " + vm.getId() + ", host address: " + parsedHostInfo.first() + ", port: " + answer.getPort());
authenticationAnswer.setHost(parsedHostInfo.first());
authenticationAnswer.setPort(answer.getPort());
}
} else {
s_logger.warn("Re-authentication request failed");
authenticationAnswer.setSuccess(false);
}
return authenticationAnswer;
}
return new ConsoleAccessAuthenticationAnswer(cmd, true);
}
@Override
public void startAgentHttpHandlerInVM(StartupProxyCommand startupCmd) {
StartConsoleProxyAgentHttpHandlerCommand cmd = null;
try {
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
byte[] randomBytes = new byte[16];
random.nextBytes(randomBytes);
String storePassword = Base64.encodeBase64String(randomBytes);
byte[] ksBits = null;
String consoleProxyUrlDomain = _configDao.getValue(Config.ConsoleProxyUrlDomain.key());
String consoleProxySslEnabled = _configDao.getValue("consoleproxy.sslEnabled");
if (!StringUtils.isEmpty(consoleProxyUrlDomain) && !StringUtils.isEmpty(consoleProxySslEnabled)
&& consoleProxySslEnabled.equalsIgnoreCase("true")) {
ksBits = _ksMgr.getKeystoreBits(ConsoleProxyManager.CERTIFICATE_NAME, ConsoleProxyManager.CERTIFICATE_NAME, storePassword);
//ks manager raises exception if ksBits are null, hence no need to explicltly handle the condition
} else {
s_logger.debug("SSL is disabled for console proxy. To enable SSL, please configure consoleproxy.sslEnabled and consoleproxy.url.domain global settings.");
}
cmd = new StartConsoleProxyAgentHttpHandlerCommand(ksBits, storePassword);
cmd.setEncryptorPassword(getEncryptorPassword());
cmd.setIsSourceIpCheckEnabled(Boolean.parseBoolean(_configDao.getValue(ConsoleProxyManager.NoVncConsoleSourceIpCheckEnabled.key())));
HostVO consoleProxyHost = findConsoleProxyHost(startupCmd);
assert (consoleProxyHost != null);
if (consoleProxyHost != null) {
Answer answer = _agentMgr.send(consoleProxyHost.getId(), cmd);
if (answer == null || !answer.getResult()) {
s_logger.error("Console proxy agent reported that it failed to execute http handling startup command");
} else {
s_logger.info("Successfully sent out command to start HTTP handling in console proxy agent");
}
}
}catch (NoSuchAlgorithmException e) {
s_logger.error("Unexpected exception in SecureRandom Algorithm selection ", e);
} catch (AgentUnavailableException e) {
s_logger.error("Unable to send http handling startup command to the console proxy resource for proxy:" + startupCmd.getProxyVmId(), e);
} catch (OperationTimedoutException e) {
s_logger.error("Unable to send http handling startup command(time out) to the console proxy resource for proxy:" + startupCmd.getProxyVmId(), e);
} catch (OutOfMemoryError e) {
s_logger.error("Unrecoverable OutOfMemory Error, exit and let it be re-launched");
System.exit(1);
} catch (Exception e) {
s_logger.error(
"Unexpected exception when sending http handling startup command(time out) to the console proxy resource for proxy:" + startupCmd.getProxyVmId(), e);
}
}
private String getEncryptorPassword() {
String key;
String iv;
ConsoleProxyPasswordBasedEncryptor.KeyIVPair keyIvPair = null;
// if we failed after reset, something is definitely wrong
for (int i = 0; i < 2; i++) {
key = _keysMgr.getEncryptionKey();
iv = _keysMgr.getEncryptionIV();
keyIvPair = new ConsoleProxyPasswordBasedEncryptor.KeyIVPair(key, iv);
if (keyIvPair.getIvBytes() == null || keyIvPair.getIvBytes().length != 16 || keyIvPair.getKeyBytes() == null || keyIvPair.getKeyBytes().length != 16) {
s_logger.warn("Console access AES KeyIV sanity check failed, reset and regenerate");
_keysMgr.resetEncryptionKeyIV();
} else {
break;
}
}
Gson gson = new GsonBuilder().create();
return gson.toJson(keyIvPair);
}
protected abstract HostVO findConsoleProxyHost(StartupProxyCommand cmd);
@Override
public void onLoadReport(ConsoleProxyLoadReportCommand cmd) {
// no-op since we do not auto-scale
}
@Override
public void onAgentConnect(Host host, StartupCommand cmd) {
// no-op
}
@Override
public void onAgentDisconnect(long agentId, Status state) {
// no-op since we do not autoscale
}
}