forked from apache/cloudstack
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathConsoleProxyServlet.java
More file actions
812 lines (693 loc) · 32.3 KB
/
ConsoleProxyServlet.java
File metadata and controls
812 lines (693 loc) · 32.3 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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
// 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.servlet;
import java.io.IOException;
import java.net.InetAddress;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.inject.Inject;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
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.exception.AgentUnavailableException;
import com.cloud.exception.OperationTimedoutException;
import com.cloud.utils.StringUtils;
import org.apache.cloudstack.framework.security.keys.KeysManager;
import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
import com.cloud.vm.VmDetailConstants;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.cloud.api.ApiServlet;
import com.cloud.consoleproxy.ConsoleProxyManager;
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.storage.GuestOSVO;
import com.cloud.user.Account;
import com.cloud.user.AccountManager;
import com.cloud.user.User;
import com.cloud.uservm.UserVm;
import com.cloud.utils.ConstantTimeComparator;
import com.cloud.utils.Pair;
import com.cloud.utils.Ternary;
import com.cloud.utils.db.EntityManager;
import com.cloud.utils.db.TransactionLegacy;
import com.cloud.vm.UserVmDetailVO;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachineManager;
import com.cloud.vm.dao.UserVmDetailsDao;
/**
* Thumbnail access : /console?cmd=thumbnail&vm=xxx&w=xxx&h=xxx
* Console access : /conosole?cmd=access&vm=xxx
* Authentication : /console?cmd=auth&vm=xxx&sid=xxx
*/
@Component("consoleServlet")
public class ConsoleProxyServlet extends HttpServlet {
private static final long serialVersionUID = -5515382620323808168L;
public static final Logger s_logger = Logger.getLogger(ConsoleProxyServlet.class.getName());
private static final int DEFAULT_THUMBNAIL_WIDTH = 144;
private static final int DEFAULT_THUMBNAIL_HEIGHT = 110;
@Inject
AccountManager _accountMgr;
@Inject
VirtualMachineManager _vmMgr;
@Inject
ManagementServer _ms;
@Inject
EntityManager _entityMgr;
@Inject
UserVmDetailsDao _userVmDetailsDao;
@Inject
KeysManager _keysMgr;
@Inject
AgentManager agentManager;
static KeysManager s_keysMgr;
private final Gson _gson = new GsonBuilder().create();
public ConsoleProxyServlet() {
}
@Override
public void init(ServletConfig config) throws ServletException {
SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext());
s_keysMgr = _keysMgr;
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
doGet(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
try {
if (_accountMgr == null || _vmMgr == null || _ms == null) {
sendResponse(resp, "Service is not ready");
return;
}
if (_keysMgr.getHashKey() == null) {
s_logger.debug("Console/thumbnail access denied. Ticket service is not ready yet");
sendResponse(resp, "Service is not ready");
return;
}
String userId = null;
String account = null;
Account accountObj = null;
Map<String, Object[]> params = new HashMap<String, Object[]>();
params.putAll(req.getParameterMap());
HttpSession session = req.getSession(false);
if (session == null) {
if (verifyRequest(params)) {
userId = (String)params.get("userid")[0];
account = (String)params.get("account")[0];
accountObj = (Account)params.get("accountobj")[0];
} else {
s_logger.debug("Invalid web session or API key in request, reject console/thumbnail access");
sendResponse(resp, "Access denied. Invalid web session or API key in request");
return;
}
} else {
// adjust to latest API refactoring changes
if (session.getAttribute("userid") != null) {
userId = ((Long)session.getAttribute("userid")).toString();
}
accountObj = (Account)session.getAttribute("accountobj");
if (accountObj != null) {
account = "" + accountObj.getId();
}
}
// Do a sanity check here to make sure the user hasn't already been deleted
if ((userId == null) || (account == null) || (accountObj == null) || !verifyUser(Long.valueOf(userId))) {
s_logger.debug("Invalid user/account, reject console/thumbnail access");
sendResponse(resp, "Access denied. Invalid or inconsistent account is found");
return;
}
String cmd = req.getParameter("cmd");
if (cmd == null || !isValidCmd(cmd)) {
s_logger.debug("invalid console servlet command: " + cmd);
sendResponse(resp, "");
return;
}
String vmIdString = req.getParameter("vm");
VirtualMachine vm = _entityMgr.findByUuid(VirtualMachine.class, vmIdString);
if (vm == null) {
s_logger.info("invalid console servlet command parameter: " + vmIdString);
sendResponse(resp, "");
return;
}
Long vmId = vm.getId();
if (!checkSessionPermision(req, vmId, accountObj)) {
sendResponse(resp, "Permission denied");
return;
}
if (cmd.equalsIgnoreCase("thumbnail")) {
handleThumbnailRequest(req, resp, vmId);
} else if (cmd.equalsIgnoreCase("access")) {
handleAccessRequest(req, resp, vmId);
} else {
handleAuthRequest(req, resp, vmId);
}
} catch (Throwable e) {
s_logger.error("Unexepected exception in ConsoleProxyServlet", e);
sendResponse(resp, "Server Internal Error");
}
}
private void handleThumbnailRequest(HttpServletRequest req, HttpServletResponse resp, long vmId) {
VirtualMachine vm = _vmMgr.findById(vmId);
if (vm == null) {
s_logger.warn("VM " + vmId + " does not exist, sending blank response for thumbnail request");
sendResponse(resp, "");
return;
}
if (vm.getHostId() == null) {
s_logger.warn("VM " + vmId + " lost host info, sending blank response for thumbnail request");
sendResponse(resp, "");
return;
}
HostVO host = _ms.getHostBy(vm.getHostId());
if (host == null) {
s_logger.warn("VM " + vmId + "'s host does not exist, sending blank response for thumbnail request");
sendResponse(resp, "");
return;
}
String rootUrl = _ms.getConsoleAccessUrlRoot(vmId);
if (rootUrl == null) {
sendResponse(resp, "");
return;
}
int w = DEFAULT_THUMBNAIL_WIDTH;
int h = DEFAULT_THUMBNAIL_HEIGHT;
String value = req.getParameter("w");
try {
w = Integer.parseInt(value);
} catch (NumberFormatException e) {
s_logger.info("[ignored] not a number: " + value);
}
value = req.getParameter("h");
try {
h = Integer.parseInt(value);
} catch (NumberFormatException e) {
s_logger.info("[ignored] not a number: " + value);
}
try {
resp.sendRedirect(composeThumbnailUrl(rootUrl, vm, host, w, h));
} catch (IOException e) {
s_logger.info("Client may already close the connection", e);
}
}
private void handleAccessRequest(HttpServletRequest req, HttpServletResponse resp, long vmId) {
VirtualMachine vm = _vmMgr.findById(vmId);
if (vm == null) {
s_logger.warn("VM " + vmId + " does not exist, sending blank response for console access request");
sendResponse(resp, "");
return;
}
if (vm.getHostId() == null) {
s_logger.warn("VM " + vmId + " lost host info, sending blank response for console access request");
sendResponse(resp, "");
return;
}
HostVO host = _ms.getHostBy(vm.getHostId());
if (host == null) {
s_logger.warn("VM " + vmId + "'s host does not exist, sending blank response for console access request");
sendResponse(resp, "");
return;
}
if (Hypervisor.HypervisorType.LXC.equals(vm.getHypervisorType())){
sendResponse(resp, "<html><body><p>Console access is not supported for LXC</p></body></html>");
return;
}
String rootUrl = _ms.getConsoleAccessUrlRoot(vmId);
if (rootUrl == null) {
sendResponse(resp, "<html><body><p>Console access will be ready in a few minutes. Please try it again later.</p></body></html>");
return;
}
String vmName = vm.getHostName();
if (vm.getType() == VirtualMachine.Type.User) {
UserVm userVm = _entityMgr.findById(UserVm.class, vmId);
String displayName = userVm.getDisplayName();
if (displayName != null && !displayName.isEmpty() && !displayName.equals(vmName)) {
vmName += "(" + displayName + ")";
}
}
InetAddress remoteAddress = null;
try {
remoteAddress = ApiServlet.getClientAddress(req);
} catch (UnknownHostException e) {
s_logger.warn("UnknownHostException when trying to lookup remote IP-Address. This should never happen. Blocking request.", e);
}
StringBuffer sb = new StringBuffer();
sb.append("<html><title>").append(escapeHTML(vmName)).append("</title><frameset><frame src=\"").append(composeConsoleAccessUrl(rootUrl, vm, host, remoteAddress));
sb.append("\"></frame></frameset></html>");
s_logger.debug("the console url is :: " + sb.toString());
sendResponse(resp, sb.toString());
}
private void handleAuthRequest(HttpServletRequest req, HttpServletResponse resp, long vmId) {
// TODO authentication channel between console proxy VM and management server needs to be secured,
// the data is now being sent through private network, but this is apparently not enough
VirtualMachine vm = _vmMgr.findById(vmId);
if (vm == null) {
s_logger.warn("VM " + vmId + " does not exist, sending failed response for authentication request from console proxy");
sendResponse(resp, "failed");
return;
}
if (vm.getHostId() == null) {
s_logger.warn("VM " + vmId + " lost host info, failed response for authentication request from console proxy");
sendResponse(resp, "failed");
return;
}
HostVO host = _ms.getHostBy(vm.getHostId());
if (host == null) {
s_logger.warn("VM " + vmId + "'s host does not exist, sending failed response for authentication request from console proxy");
sendResponse(resp, "failed");
return;
}
String sid = req.getParameter("sid");
if (sid == null || !sid.equals(vm.getVncPassword())) {
s_logger.warn("sid " + sid + " in url does not match stored sid.");
sendResponse(resp, "failed");
return;
}
sendResponse(resp, "success");
}
// put the ugly stuff here
static public Ternary<String, String, String> parseHostInfo(String hostInfo) {
String host = null;
String tunnelUrl = null;
String tunnelSession = null;
s_logger.info("Parse host info returned from executing GetVNCPortCommand. host info: " + hostInfo);
if (hostInfo != null) {
if (hostInfo.startsWith("consoleurl")) {
String tokens[] = hostInfo.split("&");
if (hostInfo.length() > 19 && hostInfo.indexOf('/', 19) > 19) {
host = hostInfo.substring(19, hostInfo.indexOf('/', 19)).trim();
tunnelUrl = tokens[0].substring("consoleurl=".length());
tunnelSession = tokens[1].split("=")[1];
} else {
host = "";
}
} else if (hostInfo.startsWith("instanceId")) {
host = hostInfo.substring(hostInfo.indexOf('=') + 1);
} else {
host = hostInfo;
}
} else {
host = hostInfo;
}
return new Ternary<String, String, String>(host, tunnelUrl, tunnelSession);
}
private String getEncryptorPassword() {
String key = _keysMgr.getEncryptionKey();
String iv = _keysMgr.getEncryptionIV();
ConsoleProxyPasswordBasedEncryptor.KeyIVPair keyIvPair = new ConsoleProxyPasswordBasedEncryptor.KeyIVPair(key, iv);
return _gson.toJson(keyIvPair);
}
private String composeThumbnailUrl(String rootUrl, VirtualMachine vm, HostVO hostVo, int w, int h) {
StringBuffer sb = new StringBuffer(rootUrl);
String host = hostVo.getPrivateIpAddress();
Pair<String, Integer> portInfo = _ms.getVncPort(vm);
Ternary<String, String, String> parsedHostInfo = parseHostInfo(portInfo.first());
String sid = vm.getVncPassword();
String tag = vm.getUuid();
int port = -1;
if (portInfo.second() == -9) {
//for hyperv
port = Integer.parseInt(_ms.findDetail(hostVo.getId(), "rdp.server.port").getValue());
} else {
port = portInfo.second();
}
String ticket = genAccessTicket(parsedHostInfo.first(), String.valueOf(port), sid, tag);
ConsoleProxyPasswordBasedEncryptor encryptor = new ConsoleProxyPasswordBasedEncryptor(getEncryptorPassword());
ConsoleProxyClientParam param = new ConsoleProxyClientParam();
param.setClientHostAddress(parsedHostInfo.first());
param.setClientHostPort(portInfo.second());
param.setClientHostPassword(sid);
param.setClientTag(tag);
param.setTicket(ticket);
if (portInfo.second() == -9) {
//For Hyperv Clinet Host Address will send Instance id
param.setHypervHost(host);
param.setUsername(_ms.findDetail(hostVo.getId(), "username").getValue());
param.setPassword(_ms.findDetail(hostVo.getId(), "password").getValue());
}
if (parsedHostInfo.second() != null && parsedHostInfo.third() != null) {
param.setClientTunnelUrl(parsedHostInfo.second());
param.setClientTunnelSession(parsedHostInfo.third());
}
sb.append("/ajaximg?token=" + encryptor.encryptObject(ConsoleProxyClientParam.class, param));
sb.append("&w=").append(w).append("&h=").append(h).append("&key=0");
if (s_logger.isDebugEnabled()) {
s_logger.debug("Compose thumbnail url: " + sb.toString());
}
return sb.toString();
}
/**
* Sets the URL to establish a VNC over websocket connection
*/
private void setWebsocketUrl(VirtualMachine vm, ConsoleProxyClientParam param) {
String ticket = acquireVncTicketForVmwareVm(vm);
if (StringUtils.isBlank(ticket)) {
s_logger.error("Could not obtain VNC ticket for VM " + vm.getInstanceName());
return;
}
String wsUrl = composeWebsocketUrlForVmwareVm(ticket, param);
param.setWebsocketUrl(wsUrl);
}
/**
* Format expected: wss://<ESXi_HOST_IP>:443/ticket/<TICKET_ID>
*/
private String composeWebsocketUrlForVmwareVm(String ticket, ConsoleProxyClientParam param) {
param.setClientHostPort(443);
return String.format("wss://%s:%s/ticket/%s", param.getClientHostAddress(), param.getClientHostPort(), ticket);
}
/**
* Acquires a ticket to be used for console proxy as described in 'Removal of VNC Server from ESXi' on:
* https://docs.vmware.com/en/VMware-vSphere/7.0/rn/vsphere-esxi-vcenter-server-70-release-notes.html
*/
private String acquireVncTicketForVmwareVm(VirtualMachine vm) {
try {
s_logger.info("Acquiring VNC ticket for VM = " + vm.getHostName());
GetVmVncTicketCommand cmd = new GetVmVncTicketCommand(vm.getInstanceName());
Answer answer = agentManager.send(vm.getHostId(), cmd);
GetVmVncTicketAnswer ans = (GetVmVncTicketAnswer) answer;
if (!ans.getResult()) {
s_logger.info("VNC ticket could not be acquired correctly: " + ans.getDetails());
}
return ans.getTicket();
} catch (AgentUnavailableException | OperationTimedoutException e) {
s_logger.error("Error acquiring ticket", e);
return null;
}
}
private String composeConsoleAccessUrl(String rootUrl, VirtualMachine vm, HostVO hostVo, InetAddress addr) {
StringBuffer sb = new StringBuffer(rootUrl);
String host = hostVo.getPrivateIpAddress();
Pair<String, Integer> portInfo = null;
if (hostVo.getHypervisorType() == Hypervisor.HypervisorType.KVM &&
(hostVo.getResourceState().equals(ResourceState.ErrorInMaintenance) ||
hostVo.getResourceState().equals(ResourceState.ErrorInPrepareForMaintenance))) {
UserVmDetailVO detailAddress = _userVmDetailsDao.findDetail(vm.getId(), VmDetailConstants.KVM_VNC_ADDRESS);
UserVmDetailVO detailPort = _userVmDetailsDao.findDetail(vm.getId(), VmDetailConstants.KVM_VNC_PORT);
if (detailAddress != null && detailPort != null) {
portInfo = new Pair<>(detailAddress.getValue(), Integer.valueOf(detailPort.getValue()));
} else {
s_logger.warn("KVM Host in ErrorInMaintenance/ErrorInPrepareForMaintenance but " +
"no VNC Address/Port was available. Falling back to default one from MS.");
}
}
if (portInfo == null) {
portInfo = _ms.getVncPort(vm);
}
if (s_logger.isDebugEnabled())
s_logger.debug("Port info " + portInfo.first());
Ternary<String, String, String> parsedHostInfo = parseHostInfo(portInfo.first());
int port = -1;
if (portInfo.second() == -9) {
//for hyperv
port = Integer.parseInt(_ms.findDetail(hostVo.getId(), "rdp.server.port").getValue());
} else {
port = portInfo.second();
}
String sid = vm.getVncPassword();
UserVmDetailVO details = _userVmDetailsDao.findDetail(vm.getId(), VmDetailConstants.KEYBOARD);
String tag = vm.getUuid();
String ticket = genAccessTicket(parsedHostInfo.first(), String.valueOf(port), sid, tag);
ConsoleProxyPasswordBasedEncryptor encryptor = new ConsoleProxyPasswordBasedEncryptor(getEncryptorPassword());
ConsoleProxyClientParam param = new ConsoleProxyClientParam();
param.setClientHostAddress(parsedHostInfo.first());
param.setClientHostPort(port);
param.setClientHostPassword(sid);
param.setClientTag(tag);
param.setTicket(ticket);
param.setSourceIP(addr != null ? addr.getHostAddress(): null);
if (requiresVncOverWebSocketConnection(vm, hostVo)) {
setWebsocketUrl(vm, param);
}
if (details != null) {
param.setLocale(details.getValue());
}
if (portInfo.second() == -9) {
//For Hyperv Clinet Host Address will send Instance id
param.setHypervHost(host);
param.setUsername(_ms.findDetail(hostVo.getId(), "username").getValue());
param.setPassword(_ms.findDetail(hostVo.getId(), "password").getValue());
}
if (parsedHostInfo.second() != null && parsedHostInfo.third() != null) {
param.setClientTunnelUrl(parsedHostInfo.second());
param.setClientTunnelSession(parsedHostInfo.third());
}
if (param.getHypervHost() != null || !ConsoleProxyManager.NoVncConsoleDefault.value()) {
sb.append("/ajax?token=" + encryptor.encryptObject(ConsoleProxyClientParam.class, param));
} else {
sb.append("/resource/noVNC/vnc.html")
.append("?autoconnect=true")
.append("&port=" + ConsoleProxyManager.DEFAULT_NOVNC_PORT)
.append("&token=" + encryptor.encryptObject(ConsoleProxyClientParam.class, param));
}
// for console access, we need guest OS type to help implement keyboard
long guestOs = vm.getGuestOSId();
GuestOSVO guestOsVo = _ms.getGuestOs(guestOs);
if (guestOsVo.getCategoryId() == 6)
sb.append("&guest=windows");
if (s_logger.isDebugEnabled()) {
s_logger.debug("Compose console url: " + sb.toString());
}
return sb.toString();
}
/**
* Since VMware 7.0 VNC servers are deprecated, it uses a ticket to create a VNC over websocket connection
* Check: https://docs.vmware.com/en/VMware-vSphere/7.0/rn/vsphere-esxi-vcenter-server-70-release-notes.html
*/
private boolean requiresVncOverWebSocketConnection(VirtualMachine vm, HostVO hostVo) {
return vm.getHypervisorType() == Hypervisor.HypervisorType.VMware && hostVo.getHypervisorVersion().compareTo("7.0") >= 0;
}
public static String genAccessTicket(String host, String port, String sid, String tag) {
return genAccessTicket(host, port, sid, tag, new Date());
}
public static String genAccessTicket(String host, String port, String sid, String tag, Date normalizedHashTime) {
String params = "host=" + host + "&port=" + port + "&sid=" + sid + "&tag=" + tag;
try {
Mac mac = Mac.getInstance("HmacSHA1");
long ts = normalizedHashTime.getTime();
ts = ts / 60000; // round up to 1 minute
String secretKey = s_keysMgr.getHashKey();
SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(), "HmacSHA1");
mac.init(keySpec);
mac.update(params.getBytes());
mac.update(String.valueOf(ts).getBytes());
byte[] encryptedBytes = mac.doFinal();
return Base64.encodeBase64String(encryptedBytes);
} catch (Exception e) {
s_logger.error("Unexpected exception ", e);
}
return "";
}
private void sendResponse(HttpServletResponse resp, String content) {
try {
resp.setContentType("text/html");
resp.getWriter().print(content);
} catch (IOException e) {
s_logger.info("Client may already close the connection", e);
}
}
private boolean checkSessionPermision(HttpServletRequest req, long vmId, Account accountObj) {
VirtualMachine vm = _vmMgr.findById(vmId);
if (vm == null) {
s_logger.debug("Console/thumbnail access denied. VM " + vmId + " does not exist in system any more");
return false;
}
// root admin can access anything
if (_accountMgr.isRootAdmin(accountObj.getId()))
return true;
switch (vm.getType()) {
case User:
try {
_accountMgr.checkAccess(accountObj, null, true, vm);
} catch (PermissionDeniedException ex) {
if (_accountMgr.isNormalUser(accountObj.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 " +
accountObj.getId() + " and caller is a normal user");
}
} else if (_accountMgr.isDomainAdmin(accountObj.getId())
|| accountObj.getType() == Account.ACCOUNT_TYPE_READ_ONLY_ADMIN) {
if(s_logger.isDebugEnabled()) {
s_logger.debug("VM access is denied. VM owner account " + vm.getAccountId()
+ " does not match the account id in session " + accountObj.getId() + " and the domain-admin caller does not manage the target domain");
}
}
return false;
}
break;
case DomainRouter:
case ConsoleProxy:
case SecondaryStorageVm:
return false;
default:
s_logger.warn("Unrecoginized virtual machine type, deny access by default. type: " + vm.getType());
return false;
}
return true;
}
private boolean isValidCmd(String cmd) {
if (cmd.equalsIgnoreCase("thumbnail") || cmd.equalsIgnoreCase("access") || cmd.equalsIgnoreCase("auth")) {
return true;
}
return false;
}
public boolean verifyUser(Long userId) {
// copy from ApiServer.java, a bit ugly here
User user = _accountMgr.getUserIncludingRemoved(userId);
Account account = null;
if (user != null) {
account = _accountMgr.getAccount(user.getAccountId());
}
if ((user == null) || (user.getRemoved() != null) || !user.getState().equals(Account.State.enabled) || (account == null) ||
!account.getState().equals(Account.State.enabled)) {
s_logger.warn("Deleted/Disabled/Locked user with id=" + userId + " attempting to access public API");
return false;
}
return true;
}
// copied and modified from ApiServer.java.
// TODO need to replace the whole servlet with a API command
private boolean verifyRequest(Map<String, Object[]> requestParameters) {
try {
String apiKey = null;
String secretKey = null;
String signature = null;
String unsignedRequest = null;
// - build a request string with sorted params, make sure it's all lowercase
// - sign the request, verify the signature is the same
List<String> parameterNames = new ArrayList<String>();
for (Object paramNameObj : requestParameters.keySet()) {
parameterNames.add((String)paramNameObj); // put the name in a list that we'll sort later
}
Collections.sort(parameterNames);
for (String paramName : parameterNames) {
// parameters come as name/value pairs in the form String/String[]
String paramValue = ((String[])requestParameters.get(paramName))[0];
if ("signature".equalsIgnoreCase(paramName)) {
signature = paramValue;
} else {
if ("apikey".equalsIgnoreCase(paramName)) {
apiKey = paramValue;
}
if (unsignedRequest == null) {
unsignedRequest = paramName + "=" + URLEncoder.encode(paramValue, "UTF-8").replaceAll("\\+", "%20");
} else {
unsignedRequest = unsignedRequest + "&" + paramName + "=" + URLEncoder.encode(paramValue, "UTF-8").replaceAll("\\+", "%20");
}
}
}
// if api/secret key are passed to the parameters
if ((signature == null) || (apiKey == null)) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("expired session, missing signature, or missing apiKey -- ignoring request...sig: " + signature + ", apiKey: " + apiKey);
}
return false; // no signature, bad request
}
TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.CLOUD_DB);
txn.close();
User user = null;
// verify there is a user with this api key
Pair<User, Account> userAcctPair = _accountMgr.findUserByApiKey(apiKey);
if (userAcctPair == null) {
s_logger.debug("apiKey does not map to a valid user -- ignoring request, apiKey: " + apiKey);
return false;
}
user = userAcctPair.first();
Account account = userAcctPair.second();
if (!user.getState().equals(Account.State.enabled) || !account.getState().equals(Account.State.enabled)) {
s_logger.debug("disabled or locked user accessing the api, userid = " + user.getId() + "; name = " + user.getUsername() + "; state: " + user.getState() +
"; accountState: " + account.getState());
return false;
}
// verify secret key exists
secretKey = user.getSecretKey();
if (secretKey == null) {
s_logger.debug("User does not have a secret key associated with the account -- ignoring request, username: " + user.getUsername());
return false;
}
unsignedRequest = unsignedRequest.toLowerCase();
Mac mac = Mac.getInstance("HmacSHA1");
SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(), "HmacSHA1");
mac.init(keySpec);
mac.update(unsignedRequest.getBytes());
byte[] encryptedBytes = mac.doFinal();
String computedSignature = Base64.encodeBase64String(encryptedBytes);
boolean equalSig = ConstantTimeComparator.compareStrings(signature, computedSignature);
if (!equalSig) {
s_logger.debug("User signature: " + signature + " is not equaled to computed signature: " + computedSignature);
}
if (equalSig) {
requestParameters.put("userid", new Object[] {String.valueOf(user.getId())});
requestParameters.put("account", new Object[] {account.getAccountName()});
requestParameters.put("accountobj", new Object[] {account});
}
return equalSig;
} catch (Exception ex) {
s_logger.error("unable to verifty request signature", ex);
}
return false;
}
public static final String escapeHTML(String content) {
if (content == null || content.isEmpty())
return content;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < content.length(); i++) {
char c = content.charAt(i);
switch (c) {
case '<':
sb.append("<");
break;
case '>':
sb.append(">");
break;
case '&':
sb.append("&");
break;
case '"':
sb.append(""");
break;
case ' ':
sb.append(" ");
break;
default:
sb.append(c);
break;
}
}
return sb.toString();
}
}