forked from AnythingLinux/cloudstack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConsoleProxy.java
More file actions
508 lines (437 loc) · 20.9 KB
/
ConsoleProxy.java
File metadata and controls
508 lines (437 loc) · 20.9 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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
// 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.io.File;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.net.URISyntaxException;
import java.net.URL;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Hashtable;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;
import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.xml.DOMConfigurator;
import com.cloud.consoleproxy.util.Logger;
import com.google.gson.Gson;
import com.sun.net.httpserver.HttpServer;
/**
*
* ConsoleProxy, singleton class that manages overall activities in console proxy process. To make legacy code work, we still
*/
public class ConsoleProxy {
private static final Logger s_logger = Logger.getLogger(ConsoleProxy.class);
public static final int KEYBOARD_RAW = 0;
public static final int KEYBOARD_COOKED = 1;
public static int VIEWER_LINGER_SECONDS = 180;
public static Object context;
// this has become more ugly, to store keystore info passed from management server (we now use management server managed keystore to support
// dynamically changing to customer supplied certificate)
public static byte[] ksBits;
public static String ksPassword;
public static Method authMethod;
public static Method reportMethod;
public static Method ensureRouteMethod;
static Hashtable<String, ConsoleProxyClient> connectionMap = new Hashtable<String, ConsoleProxyClient>();
static int httpListenPort = 80;
static int httpCmdListenPort = 8001;
static int reconnectMaxRetry = 5;
static int readTimeoutSeconds = 90;
static int keyboardType = KEYBOARD_RAW;
static String factoryClzName;
static boolean standaloneStart = false;
static String encryptorPassword = genDefaultEncryptorPassword();
private static String genDefaultEncryptorPassword() {
try {
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
byte[] randomBytes = new byte[16];
random.nextBytes(randomBytes);
return Base64.encodeBase64String(randomBytes);
} catch (NoSuchAlgorithmException e) {
s_logger.error("Unexpected exception ", e);
assert(false);
}
return "Dummy";
}
private static void configLog4j() {
URL configUrl = System.class.getResource("/conf/log4j-cloud.xml");
if(configUrl == null)
configUrl = ClassLoader.getSystemResource("log4j-cloud.xml");
if(configUrl == null)
configUrl = ClassLoader.getSystemResource("conf/log4j-cloud.xml");
if(configUrl != null) {
try {
System.out.println("Configure log4j using " + configUrl.toURI().toString());
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
try {
File file = new File(configUrl.toURI());
System.out.println("Log4j configuration from : " + file.getAbsolutePath());
DOMConfigurator.configureAndWatch(file.getAbsolutePath(), 10000);
} catch (URISyntaxException e) {
System.out.println("Unable to convert log4j configuration Url to URI");
}
// DOMConfigurator.configure(configUrl);
} else {
System.out.println("Configure log4j with default properties");
}
}
private static void configProxy(Properties conf) {
s_logger.info("Configure console proxy...");
for(Object key : conf.keySet()) {
s_logger.info("Property " + (String)key + ": " + conf.getProperty((String)key));
}
String s = conf.getProperty("consoleproxy.httpListenPort");
if (s!=null) {
httpListenPort = Integer.parseInt(s);
s_logger.info("Setting httpListenPort=" + s);
}
s = conf.getProperty("premium");
if(s != null && s.equalsIgnoreCase("true")) {
s_logger.info("Premium setting will override settings from consoleproxy.properties, listen at port 443");
httpListenPort = 443;
factoryClzName = "com.cloud.consoleproxy.ConsoleProxySecureServerFactoryImpl";
} else {
factoryClzName = ConsoleProxyBaseServerFactoryImpl.class.getName();
}
s = conf.getProperty("consoleproxy.httpCmdListenPort");
if (s!=null) {
httpCmdListenPort = Integer.parseInt(s);
s_logger.info("Setting httpCmdListenPort=" + s);
}
s = conf.getProperty("consoleproxy.reconnectMaxRetry");
if (s!=null) {
reconnectMaxRetry = Integer.parseInt(s);
s_logger.info("Setting reconnectMaxRetry=" + reconnectMaxRetry);
}
s = conf.getProperty("consoleproxy.readTimeoutSeconds");
if (s!=null) {
readTimeoutSeconds = Integer.parseInt(s);
s_logger.info("Setting readTimeoutSeconds=" + readTimeoutSeconds);
}
}
public static ConsoleProxyServerFactory getHttpServerFactory() {
try {
Class<?> clz = Class.forName(factoryClzName);
try {
ConsoleProxyServerFactory factory = (ConsoleProxyServerFactory)clz.newInstance();
factory.init(ConsoleProxy.ksBits, ConsoleProxy.ksPassword);
return factory;
} catch (InstantiationException e) {
s_logger.error(e.getMessage(), e);
return null;
} catch (IllegalAccessException e) {
s_logger.error(e.getMessage(), e);
return null;
}
} catch (ClassNotFoundException e) {
s_logger.warn("Unable to find http server factory class: " + factoryClzName);
return new ConsoleProxyBaseServerFactoryImpl();
}
}
public static ConsoleProxyAuthenticationResult authenticateConsoleAccess(ConsoleProxyClientParam param, boolean reauthentication) {
ConsoleProxyAuthenticationResult authResult = new ConsoleProxyAuthenticationResult();
authResult.setSuccess(true);
authResult.setReauthentication(reauthentication);
authResult.setHost(param.getClientHostAddress());
authResult.setPort(param.getClientHostPort());
if(standaloneStart) {
return authResult;
}
if(authMethod != null) {
Object result;
try {
result = authMethod.invoke(ConsoleProxy.context,
param.getClientHostAddress(),
String.valueOf(param.getClientHostPort()),
param.getClientTag(),
param.getClientHostPassword(),
param.getTicket(),
new Boolean(reauthentication));
} catch (IllegalAccessException e) {
s_logger.error("Unable to invoke authenticateConsoleAccess due to IllegalAccessException" + " for vm: " + param.getClientTag(), e);
authResult.setSuccess(false);
return authResult;
} catch (InvocationTargetException e) {
s_logger.error("Unable to invoke authenticateConsoleAccess due to InvocationTargetException " + " for vm: " + param.getClientTag(), e);
authResult.setSuccess(false);
return authResult;
}
if(result != null && result instanceof String) {
authResult = new Gson().fromJson((String)result, ConsoleProxyAuthenticationResult.class);
} else {
s_logger.error("Invalid authentication return object " + result + " for vm: " + param.getClientTag() + ", decline the access");
authResult.setSuccess(false);
}
} else {
s_logger.warn("Private channel towards management server is not setup. Switch to offline mode and allow access to vm: " + param.getClientTag());
}
return authResult;
}
public static void reportLoadInfo(String gsonLoadInfo) {
if(reportMethod != null) {
try {
reportMethod.invoke(ConsoleProxy.context, gsonLoadInfo);
} catch (IllegalAccessException e) {
s_logger.error("Unable to invoke reportLoadInfo due to " + e.getMessage());
} catch (InvocationTargetException e) {
s_logger.error("Unable to invoke reportLoadInfo due to " + e.getMessage());
}
} else {
s_logger.warn("Private channel towards management server is not setup. Switch to offline mode and ignore load report");
}
}
public static void ensureRoute(String address) {
if(ensureRouteMethod != null) {
try {
ensureRouteMethod.invoke(ConsoleProxy.context, address);
} catch (IllegalAccessException e) {
s_logger.error("Unable to invoke ensureRoute due to " + e.getMessage());
} catch (InvocationTargetException e) {
s_logger.error("Unable to invoke ensureRoute due to " + e.getMessage());
}
} else {
s_logger.warn("Unable to find ensureRoute method, console proxy agent is not up to date");
}
}
public static void startWithContext(Properties conf, Object context, byte[] ksBits, String ksPassword) {
s_logger.info("Start console proxy with context");
if(conf != null) {
for(Object key : conf.keySet()) {
s_logger.info("Context property " + (String)key + ": " + conf.getProperty((String)key));
}
}
configLog4j();
Logger.setFactory(new ConsoleProxyLoggerFactory());
// Using reflection to setup private/secure communication channel towards management server
ConsoleProxy.context = context;
ConsoleProxy.ksBits = ksBits;
ConsoleProxy.ksPassword = ksPassword;
try {
Class<?> contextClazz = Class.forName("com.cloud.agent.resource.consoleproxy.ConsoleProxyResource");
authMethod = contextClazz.getDeclaredMethod("authenticateConsoleAccess", String.class, String.class, String.class, String.class, String.class, Boolean.class);
reportMethod = contextClazz.getDeclaredMethod("reportLoadInfo", String.class);
ensureRouteMethod = contextClazz.getDeclaredMethod("ensureRoute", String.class);
} catch (SecurityException e) {
s_logger.error("Unable to setup private channel due to SecurityException", e);
} catch (NoSuchMethodException e) {
s_logger.error("Unable to setup private channel due to NoSuchMethodException", e);
} catch (IllegalArgumentException e) {
s_logger.error("Unable to setup private channel due to IllegalArgumentException", e);
} catch(ClassNotFoundException e) {
s_logger.error("Unable to setup private channel due to ClassNotFoundException", e);
}
// merge properties from conf file
InputStream confs = ConsoleProxy.class.getResourceAsStream("/conf/consoleproxy.properties");
Properties props = new Properties();
if (confs == null) {
s_logger.info("Can't load consoleproxy.properties from classpath, will use default configuration");
} else {
try {
props.load(confs);
for(Object key : props.keySet()) {
// give properties passed via context high priority, treat properties from consoleproxy.properties
// as default values
if(conf.get(key) == null)
conf.put(key, props.get(key));
}
} catch (Exception e) {
s_logger.error(e.toString(), e);
}
}
start(conf);
}
public static void start(Properties conf) {
System.setProperty("java.awt.headless", "true");
configProxy(conf);
ConsoleProxyServerFactory factory = getHttpServerFactory();
if(factory == null) {
s_logger.error("Unable to load console proxy server factory");
System.exit(1);
}
if(httpListenPort != 0) {
startupHttpMain();
} else {
s_logger.error("A valid HTTP server port is required to be specified, please check your consoleproxy.httpListenPort settings");
System.exit(1);
}
if(httpCmdListenPort > 0) {
startupHttpCmdPort();
} else {
s_logger.info("HTTP command port is disabled");
}
ConsoleProxyGCThread cthread = new ConsoleProxyGCThread(connectionMap);
cthread.setName("Console Proxy GC Thread");
cthread.start();
}
private static void startupHttpMain() {
try {
ConsoleProxyServerFactory factory = getHttpServerFactory();
if(factory == null) {
s_logger.error("Unable to load HTTP server factory");
System.exit(1);
}
HttpServer server = factory.createHttpServerInstance(httpListenPort);
server.createContext("/getscreen", new ConsoleProxyThumbnailHandler());
server.createContext("/resource/", new ConsoleProxyResourceHandler());
server.createContext("/ajax", new ConsoleProxyAjaxHandler());
server.createContext("/ajaximg", new ConsoleProxyAjaxImageHandler());
server.setExecutor(new ThreadExecutor()); // creates a default executor
server.start();
} catch(Exception e) {
s_logger.error(e.getMessage(), e);
System.exit(1);
}
}
private static void startupHttpCmdPort() {
try {
s_logger.info("Listening for HTTP CMDs on port " + httpCmdListenPort);
HttpServer cmdServer = HttpServer.create(new InetSocketAddress(httpCmdListenPort), 2);
cmdServer.createContext("/cmd", new ConsoleProxyCmdHandler());
cmdServer.setExecutor(new ThreadExecutor()); // creates a default executor
cmdServer.start();
} catch(Exception e) {
s_logger.error(e.getMessage(), e);
System.exit(1);
}
}
public static void main(String[] argv) {
standaloneStart = true;
configLog4j();
Logger.setFactory(new ConsoleProxyLoggerFactory());
InputStream confs = ConsoleProxy.class.getResourceAsStream("/conf/consoleproxy.properties");
Properties conf = new Properties();
if (confs == null) {
s_logger.info("Can't load consoleproxy.properties from classpath, will use default configuration");
} else {
try {
conf.load(confs);
} catch (Exception e) {
s_logger.error(e.toString(), e);
}
}
start(conf);
}
public static ConsoleProxyClient getVncViewer(ConsoleProxyClientParam param) throws Exception {
ConsoleProxyClient viewer = null;
boolean reportLoadChange = false;
String clientKey = param.getClientMapKey();
synchronized (connectionMap) {
viewer = connectionMap.get(clientKey);
if (viewer == null) {
viewer = new ConsoleProxyVncClient();
viewer.initClient(param);
connectionMap.put(clientKey, viewer);
s_logger.info("Added viewer object " + viewer);
reportLoadChange = true;
} else if (!viewer.isFrontEndAlive()) {
s_logger.info("The rfb thread died, reinitializing the viewer " + viewer);
viewer.initClient(param);
} else if (!param.getClientHostPassword().equals(viewer.getClientHostPassword())) {
s_logger.warn("Bad sid detected(VNC port may be reused). sid in session: " + viewer.getClientHostPassword()
+ ", sid in request: " + param.getClientHostPassword());
viewer.initClient(param);
}
}
if(reportLoadChange) {
ConsoleProxyClientStatsCollector statsCollector = getStatsCollector();
String loadInfo = statsCollector.getStatsReport();
reportLoadInfo(loadInfo);
if(s_logger.isDebugEnabled())
s_logger.debug("Report load change : " + loadInfo);
}
return viewer;
}
public static ConsoleProxyClient getAjaxVncViewer(ConsoleProxyClientParam param, String ajaxSession) throws Exception {
boolean reportLoadChange = false;
String clientKey = param.getClientMapKey();
synchronized (connectionMap) {
ConsoleProxyClient viewer = connectionMap.get(clientKey);
if (viewer == null) {
authenticationExternally(param);
viewer = new ConsoleProxyVncClient();
viewer.initClient(param);
connectionMap.put(clientKey, viewer);
s_logger.info("Added viewer object " + viewer);
reportLoadChange = true;
} else {
// protected against malicous attack by modifying URL content
if(ajaxSession != null) {
long ajaxSessionIdFromUrl = Long.parseLong(ajaxSession);
if(ajaxSessionIdFromUrl != viewer.getAjaxSessionId())
throw new AuthenticationException ("Cannot use the existing viewer " +
viewer + ": modified AJAX session id");
}
if(param.getClientHostPassword() == null || param.getClientHostPassword().isEmpty() || !param.getClientHostPassword().equals(viewer.getClientHostPassword()))
throw new AuthenticationException ("Cannot use the existing viewer " +
viewer + ": bad sid");
if(!viewer.isFrontEndAlive()) {
authenticationExternally(param);
viewer.initClient(param);
reportLoadChange = true;
}
}
if(reportLoadChange) {
ConsoleProxyClientStatsCollector statsCollector = getStatsCollector();
String loadInfo = statsCollector.getStatsReport();
reportLoadInfo(loadInfo);
if(s_logger.isDebugEnabled())
s_logger.debug("Report load change : " + loadInfo);
}
return viewer;
}
}
public static void removeViewer(ConsoleProxyClient viewer) {
synchronized (connectionMap) {
for(Map.Entry<String, ConsoleProxyClient> entry : connectionMap.entrySet()) {
if(entry.getValue() == viewer) {
connectionMap.remove(entry.getKey());
return;
}
}
}
}
public static ConsoleProxyClientStatsCollector getStatsCollector() {
return new ConsoleProxyClientStatsCollector(connectionMap);
}
public static void authenticationExternally(ConsoleProxyClientParam param) throws AuthenticationException {
ConsoleProxyAuthenticationResult authResult = authenticateConsoleAccess(param, false);
if(authResult == null || !authResult.isSuccess()) {
s_logger.warn("External authenticator failed authencation request for vm " + param.getClientTag() + " with sid " + param.getClientHostPassword());
throw new AuthenticationException("External authenticator failed request for vm " + param.getClientTag() + " with sid " + param.getClientHostPassword());
}
}
public static ConsoleProxyAuthenticationResult reAuthenticationExternally(ConsoleProxyClientParam param) {
return authenticateConsoleAccess(param, true);
}
public static String getEncryptorPassword() {
return encryptorPassword;
}
public static void setEncryptorPassword(String password) {
encryptorPassword = password;
}
static class ThreadExecutor implements Executor {
public void execute(Runnable r) {
new Thread(r).start();
}
}
}