-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathAccountManagerImpl.java
More file actions
3810 lines (3311 loc) · 174 KB
/
AccountManagerImpl.java
File metadata and controls
3810 lines (3311 loc) · 174 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
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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.user;
import java.net.InetAddress;
import java.net.URLEncoder;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.inject.Inject;
import javax.naming.ConfigurationException;
import org.apache.cloudstack.acl.APIChecker;
import org.apache.cloudstack.acl.ControlledEntity;
import org.apache.cloudstack.acl.InfrastructureEntity;
import org.apache.cloudstack.acl.QuerySelector;
import org.apache.cloudstack.acl.Role;
import org.apache.cloudstack.acl.RoleService;
import org.apache.cloudstack.acl.RoleType;
import org.apache.cloudstack.acl.SecurityChecker;
import org.apache.cloudstack.acl.SecurityChecker.AccessType;
import org.apache.cloudstack.affinity.AffinityGroup;
import org.apache.cloudstack.affinity.dao.AffinityGroupDao;
import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.ApiCommandResourceType;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.command.admin.account.CreateAccountCmd;
import org.apache.cloudstack.api.command.admin.account.UpdateAccountCmd;
import org.apache.cloudstack.api.command.admin.user.DeleteUserCmd;
import org.apache.cloudstack.api.command.admin.user.GetUserKeysCmd;
import org.apache.cloudstack.api.command.admin.user.MoveUserCmd;
import org.apache.cloudstack.api.command.admin.user.RegisterCmd;
import org.apache.cloudstack.api.command.admin.user.UpdateUserCmd;
import org.apache.cloudstack.api.response.UserTwoFactorAuthenticationSetupResponse;
import org.apache.cloudstack.auth.UserAuthenticator;
import org.apache.cloudstack.auth.UserAuthenticator.ActionOnFailedAuthentication;
import org.apache.cloudstack.auth.UserTwoFactorAuthenticator;
import org.apache.cloudstack.config.ApiServiceConfiguration;
import org.apache.cloudstack.context.CallContext;
import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService;
import org.apache.cloudstack.framework.config.ConfigKey;
import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
import org.apache.cloudstack.framework.messagebus.MessageBus;
import org.apache.cloudstack.framework.messagebus.PublishScope;
import org.apache.cloudstack.managed.context.ManagedContextRunnable;
import org.apache.cloudstack.network.RoutedIpv4Manager;
import org.apache.cloudstack.network.dao.NetworkPermissionDao;
import org.apache.cloudstack.region.gslb.GlobalLoadBalancerRuleDao;
import org.apache.cloudstack.resourcedetail.UserDetailVO;
import org.apache.cloudstack.resourcedetail.dao.UserDetailsDao;
import org.apache.cloudstack.utils.baremetal.BaremetalUtils;
import org.apache.cloudstack.webhook.WebhookHelper;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import com.cloud.api.ApiDBUtils;
import com.cloud.api.auth.SetupUserTwoFactorAuthenticationCmd;
import com.cloud.api.query.vo.ControlledViewEntity;
import com.cloud.configuration.Config;
import com.cloud.configuration.ConfigurationManager;
import com.cloud.configuration.Resource.ResourceOwnerType;
import com.cloud.configuration.ResourceCountVO;
import com.cloud.configuration.ResourceLimit;
import com.cloud.configuration.dao.ResourceCountDao;
import com.cloud.configuration.dao.ResourceLimitDao;
import com.cloud.dc.DataCenter;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.DedicatedResourceVO;
import com.cloud.dc.dao.DataCenterDao;
import com.cloud.dc.dao.DataCenterVnetDao;
import com.cloud.dc.dao.DedicatedResourceDao;
import com.cloud.domain.Domain;
import com.cloud.domain.DomainVO;
import com.cloud.domain.dao.DomainDao;
import com.cloud.event.ActionEvent;
import com.cloud.event.ActionEventUtils;
import com.cloud.event.ActionEvents;
import com.cloud.event.EventTypes;
import com.cloud.exception.AgentUnavailableException;
import com.cloud.exception.CloudAuthenticationException;
import com.cloud.exception.CloudTwoFactorAuthenticationException;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.OperationTimedoutException;
import com.cloud.exception.PermissionDeniedException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.host.dao.HostDao;
import com.cloud.kubernetes.cluster.KubernetesServiceHelper;
import com.cloud.network.IpAddress;
import com.cloud.network.IpAddressManager;
import com.cloud.network.Network;
import com.cloud.network.NetworkModel;
import com.cloud.network.VpnUserVO;
import com.cloud.network.as.AutoScaleManager;
import com.cloud.network.dao.AccountGuestVlanMapDao;
import com.cloud.network.dao.AccountGuestVlanMapVO;
import com.cloud.network.dao.IPAddressDao;
import com.cloud.network.dao.IPAddressVO;
import com.cloud.network.dao.NetworkDao;
import com.cloud.network.dao.NetworkVO;
import com.cloud.network.dao.RemoteAccessVpnDao;
import com.cloud.network.dao.RemoteAccessVpnVO;
import com.cloud.network.dao.VpnUserDao;
import com.cloud.network.router.VirtualRouter;
import com.cloud.network.security.SecurityGroupManager;
import com.cloud.network.security.SecurityGroupService;
import com.cloud.network.security.SecurityGroupVO;
import com.cloud.network.security.dao.SecurityGroupDao;
import com.cloud.network.vpc.Vpc;
import com.cloud.network.vpc.VpcManager;
import com.cloud.network.vpc.VpcOffering;
import com.cloud.network.vpn.RemoteAccessVpnService;
import com.cloud.network.vpn.Site2SiteVpnManager;
import com.cloud.offering.DiskOffering;
import com.cloud.offering.NetworkOffering;
import com.cloud.offering.ServiceOffering;
import com.cloud.projects.Project;
import com.cloud.projects.Project.ListProjectResourcesCriteria;
import com.cloud.projects.ProjectInvitationVO;
import com.cloud.projects.ProjectManager;
import com.cloud.projects.ProjectVO;
import com.cloud.projects.dao.ProjectAccountDao;
import com.cloud.projects.dao.ProjectDao;
import com.cloud.region.ha.GlobalLoadBalancingRulesService;
import com.cloud.storage.VMTemplateVO;
import com.cloud.storage.VolumeApiService;
import com.cloud.storage.VolumeVO;
import com.cloud.storage.dao.VMTemplateDao;
import com.cloud.storage.dao.VolumeDao;
import com.cloud.storage.snapshot.SnapshotManager;
import com.cloud.template.TemplateManager;
import com.cloud.template.VirtualMachineTemplate;
import com.cloud.user.Account.State;
import com.cloud.user.dao.AccountDao;
import com.cloud.user.dao.SSHKeyPairDao;
import com.cloud.user.dao.UserAccountDao;
import com.cloud.user.dao.UserDao;
import com.cloud.user.dao.UserDataDao;
import com.cloud.utils.ConstantTimeComparator;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.Pair;
import com.cloud.utils.Ternary;
import com.cloud.utils.component.ComponentContext;
import com.cloud.utils.component.Manager;
import com.cloud.utils.component.ManagerBase;
import com.cloud.utils.component.PluggableService;
import com.cloud.utils.concurrency.NamedThreadFactory;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.GlobalLock;
import com.cloud.utils.db.JoinBuilder;
import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.db.TransactionCallback;
import com.cloud.utils.db.TransactionCallbackNoReturn;
import com.cloud.utils.db.TransactionStatus;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.net.NetUtils;
import com.cloud.vm.InstanceGroupVO;
import com.cloud.vm.ReservationContext;
import com.cloud.vm.ReservationContextImpl;
import com.cloud.vm.UserVmManager;
import com.cloud.vm.UserVmVO;
import com.cloud.vm.VMInstanceVO;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachineManager;
import com.cloud.vm.dao.InstanceGroupDao;
import com.cloud.vm.dao.UserVmDao;
import com.cloud.vm.dao.VMInstanceDao;
import com.cloud.vm.snapshot.VMSnapshot;
import com.cloud.vm.snapshot.VMSnapshotManager;
import com.cloud.vm.snapshot.VMSnapshotVO;
import com.cloud.vm.snapshot.dao.VMSnapshotDao;
public class AccountManagerImpl extends ManagerBase implements AccountManager, Manager {
@Inject
private AccountDao _accountDao;
@Inject
private ConfigurationDao _configDao;
@Inject
private ResourceCountDao _resourceCountDao;
@Inject
private UserDao _userDao;
@Inject
private UserDetailsDao _userDetailsDao;
@Inject
private InstanceGroupDao _vmGroupDao;
@Inject
private UserAccountDao _userAccountDao;
@Inject
private VolumeDao _volumeDao;
@Inject
private UserVmDao _userVmDao;
@Inject
private VMTemplateDao _templateDao;
@Inject
private NetworkDao _networkDao;
@Inject
private SecurityGroupDao _securityGroupDao;
@Inject
private VMInstanceDao _vmDao;
@Inject
private SecurityGroupManager _networkGroupMgr;
@Inject
private NetworkOrchestrationService _networkMgr;
@Inject
private SnapshotManager _snapMgr;
@Inject
private VMSnapshotManager _vmSnapshotMgr;
@Inject
private VMSnapshotDao _vmSnapshotDao;
@Inject
private UserVmManager _vmMgr;
@Inject
private TemplateManager _tmpltMgr;
@Inject
private ConfigurationManager _configMgr;
@Inject
private VirtualMachineManager _itMgr;
@Inject
private RemoteAccessVpnDao _remoteAccessVpnDao;
@Inject
private RemoteAccessVpnService _remoteAccessVpnMgr;
@Inject
private VpnUserDao _vpnUser;
@Inject
private DataCenterDao _dcDao;
@Inject
private DomainManager _domainMgr;
@Inject
private ProjectManager _projectMgr;
@Inject
private ProjectDao _projectDao;
@Inject
private AccountDetailsDao _accountDetailsDao;
@Inject
private DomainDao _domainDao;
@Inject
private ProjectAccountDao _projectAccountDao;
@Inject
private IPAddressDao _ipAddressDao;
@Inject
private HostDao hostDao;
@Inject
private VpcManager _vpcMgr;
@Inject
private NetworkModel _networkModel;
@Inject
private Site2SiteVpnManager _vpnMgr;
@Inject
private AutoScaleManager _autoscaleMgr;
@Inject
private VolumeApiService volumeService;
@Inject
private AffinityGroupDao _affinityGroupDao;
@Inject
private AccountGuestVlanMapDao _accountGuestVlanMapDao;
@Inject
private DataCenterVnetDao _dataCenterVnetDao;
@Inject
private ResourceLimitService _resourceLimitMgr;
@Inject
private ResourceLimitDao _resourceLimitDao;
@Inject
private DedicatedResourceDao _dedicatedDao;
@Inject
private GlobalLoadBalancerRuleDao _gslbRuleDao;
@Inject
private SSHKeyPairDao _sshKeyPairDao;
@Inject
private UserDataDao userDataDao;
@Inject
private NetworkPermissionDao networkPermissionDao;
private List<QuerySelector> _querySelectors;
@Inject
private MessageBus _messageBus;
@Inject
private GlobalLoadBalancingRulesService _gslbService;
@Inject
public AccountService _accountService;
private List<UserAuthenticator> _userAuthenticators;
private List<UserTwoFactorAuthenticator> _userTwoFactorAuthenticators;
protected List<UserAuthenticator> _userPasswordEncoders;
protected List<PluggableService> services;
private List<APIChecker> apiAccessCheckers;
@Inject
private IpAddressManager _ipAddrMgr;
@Inject
private RoleService roleService;
@Inject
private RoutedIpv4Manager routedIpv4Manager;
@Inject
private PasswordPolicy passwordPolicy;
private final ScheduledExecutorService _executor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("AccountChecker"));
private int _allowedLoginAttempts;
private UserVO _systemUser;
private AccountVO _systemAccount;
private List<SecurityChecker> _securityCheckers;
private int _cleanupInterval;
private static final String OAUTH2_PROVIDER_NAME = "oauth2";
private List<String> apiNameList;
protected static Map<String, UserTwoFactorAuthenticator> userTwoFactorAuthenticationProvidersMap = new HashMap<>();
private List<UserTwoFactorAuthenticator> userTwoFactorAuthenticationProviders;
private long validUserLastAuthTimeDurationInMs = 0L;
private static final long DEFAULT_USER_AUTH_TIME_DURATION_MS = 350L;
public static ConfigKey<Boolean> enableUserTwoFactorAuthentication = new ConfigKey<>("Advanced",
Boolean.class,
"enable.user.2fa",
"false",
"Determines whether two factor authentication is enabled or not. This can also be configured at domain level.",
true,
ConfigKey.Scope.Domain);
public static ConfigKey<Boolean> mandateUserTwoFactorAuthentication = new ConfigKey<>("Advanced",
Boolean.class,
"mandate.user.2fa",
"false",
"Determines whether to make the two factor authentication mandatory or not. This setting is applicable only when enable.user.2fa is true. This can also be configured at domain level.",
true,
ConfigKey.Scope.Domain);
public static final ConfigKey<String> userTwoFactorAuthenticationIssuer = new ConfigKey<>("Advanced",
String.class,
"user.2fa.issuer",
"CloudStack",
"Name of the issuer of two factor authentication",
true,
ConfigKey.Scope.Domain);
static final ConfigKey<String> userTwoFactorAuthenticationDefaultProvider = new ConfigKey<>("Advanced", String.class,
"user.2fa.default.provider",
"totp",
"The default user two factor authentication provider. Eg. totp, staticpin", true, ConfigKey.Scope.Domain);
public static final ConfigKey<Boolean> apiKeyAccess = new ConfigKey<>(ConfigKey.CATEGORY_SYSTEM, Boolean.class,
"api.key.access",
"true",
"Determines whether API (api-key/secret-key) access is allowed or not. Editable only by Root Admin.",
true,
ConfigKey.Scope.Domain);
static ConfigKey<Boolean> userAllowMultipleAccounts = new ConfigKey<>("Advanced",
Boolean.class,
"user.allow.multiple.accounts",
"false",
"Determines if the same username can be added to more than one account in the same domain (SAML-only).",
true,
ConfigKey.Scope.Domain);
public static ConfigKey<String> listOfRoleTypesAllowedForOperationsOfSameRoleType = new ConfigKey<>("Hidden",
String.class,
"role.types.allowed.for.operations.on.accounts.of.same.role.type",
"Admin, ResourceAdmin, DomainAdmin",
"Comma separated list of role types that are allowed to do operations on accounts or users of the same role type within a domain.",
true,
ConfigKey.Scope.Domain);
public static ConfigKey<Boolean> allowOperationsOnUsersInSameAccount = new ConfigKey<>("Hidden",
Boolean.class,
"allow.operations.on.users.in.same.account",
"true",
"Allow operations on users among them in the same account",
true,
ConfigKey.Scope.Domain);
protected AccountManagerImpl() {
super();
}
public List<UserAuthenticator> getUserAuthenticators() {
return _userAuthenticators;
}
public void setUserAuthenticators(List<UserAuthenticator> authenticators) {
_userAuthenticators = authenticators;
}
public List<UserTwoFactorAuthenticator> getUserTwoFactorAuthenticators() {
return _userTwoFactorAuthenticators;
}
public void setUserTwoFactorAuthenticators(List<UserTwoFactorAuthenticator> twoFactorAuthenticators) {
_userTwoFactorAuthenticators = twoFactorAuthenticators;
}
public List<UserAuthenticator> getUserPasswordEncoders() {
return _userPasswordEncoders;
}
public void setUserPasswordEncoders(List<UserAuthenticator> encoders) {
_userPasswordEncoders = encoders;
}
public List<SecurityChecker> getSecurityCheckers() {
return _securityCheckers;
}
public void setSecurityCheckers(List<SecurityChecker> securityCheckers) {
_securityCheckers = securityCheckers;
}
public List<PluggableService> getServices() {
return services;
}
public void setServices(List<PluggableService> services) {
this.services = services;
}
public List<APIChecker> getApiAccessCheckers() {
return apiAccessCheckers;
}
public void setApiAccessCheckers(List<APIChecker> apiAccessCheckers) {
this.apiAccessCheckers = apiAccessCheckers;
}
public List<QuerySelector> getQuerySelectors() {
return _querySelectors;
}
public void setQuerySelectors(List<QuerySelector> querySelectors) {
_querySelectors = querySelectors;
}
protected void deleteWebhooksForAccount(long accountId) {
try {
WebhookHelper webhookService = ComponentContext.getDelegateComponentOfType(WebhookHelper.class);
webhookService.deleteWebhooksForAccount(accountId);
} catch (NoSuchBeanDefinitionException ignored) {
logger.debug("No WebhookHelper bean found");
}
}
@Override
public List<String> getApiNameList() {
return apiNameList;
}
@Override
public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException {
_systemAccount = _accountDao.findById(Account.ACCOUNT_ID_SYSTEM);
if (_systemAccount == null) {
throw new ConfigurationException("Unable to find the system account using " + Account.ACCOUNT_ID_SYSTEM);
}
_systemUser = _userDao.findById(User.UID_SYSTEM);
if (_systemUser == null) {
throw new ConfigurationException("Unable to find the system user using " + User.UID_SYSTEM);
}
Map<String, String> configs = _configDao.getConfiguration(params);
String loginAttempts = configs.get(Config.IncorrectLoginAttemptsAllowed.key());
_allowedLoginAttempts = NumbersUtil.parseInt(loginAttempts, 5);
String value = configs.get(Config.AccountCleanupInterval.key());
_cleanupInterval = NumbersUtil.parseInt(value, 60 * 60 * 24); // 1 day.
return true;
}
@Override
public UserVO getSystemUser() {
if (_systemUser == null) {
_systemUser = _userDao.findById(User.UID_SYSTEM);
}
return _systemUser;
}
@Override
public boolean start() {
initializeUserTwoFactorAuthenticationProvidersMap();
if (apiNameList == null) {
long startTime = System.nanoTime();
apiNameList = new ArrayList<>();
Set<Class<?>> cmdClasses = new LinkedHashSet<>();
for (PluggableService service : services) {
logger.debug(String.format("getting api commands of service: %s", service.getClass().getName()));
cmdClasses.addAll(service.getCommands());
}
apiNameList = createApiNameList(cmdClasses);
long endTime = System.nanoTime();
logger.info("Api Discovery Service: Annotation, docstrings, api relation graph processed in " + (endTime - startTime) / 1000000.0 + " ms");
}
_executor.scheduleAtFixedRate(new AccountCleanupTask(), _cleanupInterval, _cleanupInterval, TimeUnit.SECONDS);
return true;
}
protected List<String> createApiNameList(Set<Class<?>> cmdClasses) {
List<String> apiNameList = new ArrayList<>();
for (Class<?> cmdClass : cmdClasses) {
APICommand apiCmdAnnotation = cmdClass.getAnnotation(APICommand.class);
if (apiCmdAnnotation == null) {
apiCmdAnnotation = cmdClass.getSuperclass().getAnnotation(APICommand.class);
}
if (apiCmdAnnotation == null || !apiCmdAnnotation.includeInApiDoc() || apiCmdAnnotation.name().isEmpty()) {
continue;
}
String apiName = apiCmdAnnotation.name();
if (logger.isTraceEnabled()) {
logger.trace("Found api: " + apiName);
}
apiNameList.add(apiName);
}
return apiNameList;
}
@Override
public boolean stop() {
return true;
}
@Override
public AccountVO getSystemAccount() {
if (_systemAccount == null) {
_systemAccount = _accountDao.findById(Account.ACCOUNT_ID_SYSTEM);
}
return _systemAccount;
}
@Override
public boolean isAdmin(Long accountId) {
if (accountId != null) {
AccountVO acct = _accountDao.findById(accountId);
if (acct == null) {
return false; //account is deleted or does not exist
}
if ((isRootAdmin(accountId)) || (isDomainAdmin(accountId)) || (isResourceDomainAdmin(accountId))) {
return true;
} else if (acct.getType() == Account.Type.READ_ONLY_ADMIN) {
return true;
}
}
return false;
}
@Override
public boolean isRootAdmin(Long accountId) {
if (accountId != null) {
AccountVO acct = _accountDao.findById(accountId);
if (acct == null) {
return false; //account is deleted or does not exist
}
for (SecurityChecker checker : _securityCheckers) {
try {
if (checker.checkAccess(acct, null, null, "SystemCapability")) {
if (logger.isTraceEnabled()) {
logger.trace("Root Access granted to " + acct + " by " + checker.getName());
}
return true;
}
} catch (PermissionDeniedException ex) {
return false;
}
}
}
return false;
}
@Override
public boolean isDomainAdmin(Long accountId) {
if (accountId != null) {
AccountVO acct = _accountDao.findById(accountId);
if (acct == null) {
return false; //account is deleted or does not exist
}
for (SecurityChecker checker : _securityCheckers) {
try {
if (checker.checkAccess(acct, null, null, "DomainCapability")) {
if (logger.isTraceEnabled()) {
logger.trace("DomainAdmin Access granted to " + acct + " by " + checker.getName());
}
return true;
}
} catch (PermissionDeniedException ex) {
return false;
}
}
}
return false;
}
@Override
public boolean isNormalUser(long accountId) {
AccountVO acct = _accountDao.findById(accountId);
if (acct != null && acct.getType() == Account.Type.NORMAL) {
return true;
}
return false;
}
@Override
public boolean isResourceDomainAdmin(Long accountId) {
if (accountId != null) {
AccountVO acct = _accountDao.findById(accountId);
if (acct == null) {
return false; //account is deleted or does not exist
}
for (SecurityChecker checker : _securityCheckers) {
try {
if (checker.checkAccess(acct, null, null, "DomainResourceCapability")) {
if (logger.isTraceEnabled()) {
logger.trace("ResourceDomainAdmin Access granted to " + acct + " by " + checker.getName());
}
return true;
}
} catch (PermissionDeniedException ex) {
return false;
}
}
}
return false;
}
public boolean isInternalAccount(long accountId) {
Account account = _accountDao.findById(accountId);
if (account == null) {
return false; //account is deleted or does not exist
}
if (isRootAdmin(accountId) || (account.getType() == Account.Type.ADMIN)) {
return true;
}
return false;
}
@Override
public void checkAccess(Account caller, Domain domain) throws PermissionDeniedException {
for (SecurityChecker checker : _securityCheckers) {
if (checker.checkAccess(caller, domain)) {
if (logger.isDebugEnabled()) {
logger.debug("Access granted to " + caller + " to " + domain + " by " + checker.getName());
}
return;
}
}
throw new PermissionDeniedException("There's no way to confirm " + caller + " has access to " + domain);
}
@Override
public void checkAccess(Account caller, AccessType accessType, boolean sameOwner, ControlledEntity... entities) {
checkAccess(caller, accessType, sameOwner, null, entities);
}
@Override
public void checkAccess(Account caller, AccessType accessType, boolean sameOwner, String apiName, ControlledEntity... entities) {
//check for the same owner
Long ownerId = null;
ControlledEntity prevEntity = null;
if (sameOwner) {
for (ControlledEntity entity : entities) {
if (ownerId == null) {
ownerId = entity.getAccountId();
} else if (ownerId.longValue() != entity.getAccountId()) {
throw new PermissionDeniedException("Entity " + entity + " and entity " + prevEntity + " belong to different accounts");
}
prevEntity = entity;
}
}
if (caller.getId() == Account.ACCOUNT_ID_SYSTEM || isRootAdmin(caller.getId())) {
// no need to make permission checks if the system/root admin makes the call
if (logger.isTraceEnabled()) {
logger.trace("No need to make permission check for System/RootAdmin account, returning true");
}
return;
}
HashMap<Long, List<ControlledEntity>> domains = new HashMap<>();
for (ControlledEntity entity : entities) {
long domainId = entity.getDomainId();
if (entity.getAccountId() != -1 && domainId == -1) { // If account exists domainId should too so calculate
// it. This condition might be hit for templates or entities which miss domainId in their tables
Account account = ApiDBUtils.findAccountById(entity.getAccountId());
domainId = account != null ? account.getDomainId() : -1;
}
if (entity.getAccountId() != -1 && domainId != -1 && !(entity instanceof VirtualMachineTemplate)
&& !(entity instanceof Network && accessType != null && (accessType == AccessType.UseEntry || accessType == AccessType.OperateEntry))
&& !(entity instanceof AffinityGroup) && !(entity instanceof VirtualRouter)) {
List<ControlledEntity> toBeChecked = domains.get(entity.getDomainId());
// for templates, we don't have to do cross domains check
if (toBeChecked == null) {
toBeChecked = new ArrayList<>();
domains.put(domainId, toBeChecked);
}
toBeChecked.add(entity);
}
boolean granted = false;
for (SecurityChecker checker : _securityCheckers) {
if (checker.checkAccess(caller, entity, accessType, apiName)) {
if (logger.isDebugEnabled()) {
User user = CallContext.current().getCallingUser();
String userName = "";
if (user != null)
userName = user.getUsername();
logger.debug("Access to {} granted to {} by {} on behalf of user {}", entity, caller, checker.getName(), userName);
}
granted = true;
break;
}
}
if (!granted) {
assert false : "How can all of the security checkers pass on checking this check: " + entity;
throw new PermissionDeniedException("There's no way to confirm " + caller + " has access to " + entity);
}
}
for (Map.Entry<Long, List<ControlledEntity>> domain : domains.entrySet()) {
for (SecurityChecker checker : _securityCheckers) {
Domain d = _domainMgr.getDomain(domain.getKey());
if (d == null || d.getRemoved() != null) {
throw new PermissionDeniedException("Domain is not found.", caller, domain.getValue());
}
try {
checker.checkAccess(caller, d);
} catch (PermissionDeniedException e) {
e.addDetails(caller, domain.getValue());
throw e;
}
}
}
// check that resources belong to the same account
}
@Override
public void validateAccountHasAccessToResource(Account account, AccessType accessType, Object resource) {
Class<?> resourceClass = resource.getClass();
if (ControlledEntity.class.isAssignableFrom(resourceClass)) {
checkAccess(account, accessType, true, (ControlledEntity) resource);
} else if (Domain.class.isAssignableFrom(resourceClass)) {
checkAccess(account, (Domain) resource);
} else if (InfrastructureEntity.class.isAssignableFrom(resourceClass)) {
logger.trace("Validation of access to infrastructure entity has been disabled in CloudStack version 4.4.");
}
logger.debug("Account [{}] has access to resource.", account);
}
@Override
public Long checkAccessAndSpecifyAuthority(Account caller, Long zoneId) {
// We just care for resource domain admins for now, and they should be permitted to see only their zone.
if (isResourceDomainAdmin(caller.getAccountId())) {
if (zoneId == null) {
return getZoneIdForAccount(caller);
} else if (zoneId.compareTo(getZoneIdForAccount(caller)) != 0) {
throw new PermissionDeniedException("Caller " + caller + "is not allowed to access the zone " + zoneId);
} else {
return zoneId;
}
} else {
return zoneId;
}
}
private Long getZoneIdForAccount(Account account) {
// Currently just for resource domain admin
List<DataCenterVO> dcList = _dcDao.findZonesByDomainId(account.getDomainId());
if (dcList != null && dcList.size() != 0) {
return dcList.get(0).getId();
} else {
throw new CloudRuntimeException("Failed to find any private zone for Resource domain admin.");
}
}
@DB
public void updateLoginAttempts(final Long id, final int attempts, final boolean toDisable) {
try {
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
UserAccountVO user = null;
user = _userAccountDao.lockRow(id, true);
user.setLoginAttempts(attempts);
if (toDisable) {
user.setState(State.DISABLED.toString());
}
_userAccountDao.update(id, user);
}
});
} catch (Exception e) {
logger.error("Failed to update login attempts for user {}", () -> _userAccountDao.findById(id));
}
}
private boolean doSetUserStatus(long userId, State state) {
UserVO userForUpdate = _userDao.createForUpdate();
userForUpdate.setState(state);
return _userDao.update(Long.valueOf(userId), userForUpdate);
}
@Override
public boolean enableAccount(long accountId) {
boolean success = false;
AccountVO acctForUpdate = _accountDao.createForUpdate();
acctForUpdate.setState(State.ENABLED);
acctForUpdate.setNeedsCleanup(false);
success = _accountDao.update(Long.valueOf(accountId), acctForUpdate);
return success;
}
protected boolean lockAccount(long accountId) {
boolean success = false;
Account account = _accountDao.findById(accountId);
if (account != null) {
if (account.getState().equals(State.LOCKED)) {
return true; // already locked, no-op
} else if (account.getState().equals(State.ENABLED)) {
AccountVO acctForUpdate = _accountDao.createForUpdate();
acctForUpdate.setState(State.LOCKED);
success = _accountDao.update(Long.valueOf(accountId), acctForUpdate);
} else {
if (logger.isInfoEnabled()) {
logger.info("Attempting to lock a non-enabled account {}, current state is {}, locking failed.", account, account.getState());
}
}
} else {
logger.warn("Failed to lock account " + accountId + ", account not found.");
}
return success;
}
@Override
public boolean deleteAccount(AccountVO account, long callerUserId, Account caller) {
long accountId = account.getId();
// delete the account record
if (!_accountDao.remove(accountId)) {
logger.error("Unable to delete account {}", account);
return false;
}
account.setState(State.REMOVED);
_accountDao.update(accountId, account);
if (logger.isDebugEnabled()) {
logger.debug("Removed account {}", account);
}
return cleanupAccount(account, callerUserId, caller);
}
protected void cleanupPluginsResourcesIfNeeded(Account account) {
try {
KubernetesServiceHelper kubernetesServiceHelper =
ComponentContext.getDelegateComponentOfType(KubernetesServiceHelper.class);
kubernetesServiceHelper.cleanupForAccount(account);
} catch (NoSuchBeanDefinitionException ignored) {
logger.debug("No KubernetesServiceHelper bean found");
}
}
protected boolean cleanupAccount(AccountVO account, long callerUserId, Account caller) {
long accountId = account.getId();
boolean accountCleanupNeeded = false;
try {
// cleanup the users from the account
List<UserVO> users = _userDao.listByAccount(accountId);
for (UserVO user : users) {
if (!_userDao.remove(user.getId())) {
logger.error("Unable to delete user: " + user + " as a part of account " + account + " cleanup");
accountCleanupNeeded = true;
}
}
// delete autoscaling VM groups
if (!_autoscaleMgr.deleteAutoScaleVmGroupsByAccount(account)) {
accountCleanupNeeded = true;
}
// delete global load balancer rules for the account.
List<org.apache.cloudstack.region.gslb.GlobalLoadBalancerRuleVO> gslbRules = _gslbRuleDao.listByAccount(accountId);
if (gslbRules != null && !gslbRules.isEmpty()) {
_gslbService.revokeAllGslbRulesForAccount(caller, account);
}
// delete the account from project accounts
_projectAccountDao.removeAccountFromProjects(accountId);
// Delete account's network permissions
networkPermissionDao.removeAccountPermissions(accountId);
if (account.getType() != Account.Type.PROJECT) {
// delete the account from group
_messageBus.publish(_name, MESSAGE_REMOVE_ACCOUNT_EVENT, PublishScope.LOCAL, accountId);
}
// delete all vm groups belonging to account
List<InstanceGroupVO> groups = _vmGroupDao.listByAccountId(accountId);
for (InstanceGroupVO group : groups) {
if (!_vmMgr.deleteVmGroup(group.getId())) {
logger.error("Unable to delete group: {}", group);
accountCleanupNeeded = true;
}
}
// Delete the snapshots dir for the account. Have to do this before destroying the VMs.
boolean success = _snapMgr.deleteSnapshotDirsForAccount(account);
if (success) {
logger.debug("Successfully deleted snapshots directories for all volumes under account {} across all zones", account);
}
// clean up templates
List<VMTemplateVO> userTemplates = _templateDao.listByAccountId(accountId);
boolean allTemplatesDeleted = true;
for (VMTemplateVO template : userTemplates) {
if (template.getRemoved() == null) {
try {
allTemplatesDeleted = _tmpltMgr.delete(callerUserId, template.getId(), null);
} catch (Exception e) {
logger.warn("Failed to delete template {} while removing account {} due to: ", template, account, e);
allTemplatesDeleted = false;
}
}
}
if (!allTemplatesDeleted) {
logger.warn("Failed to delete Templates while removing Account {}", account);
accountCleanupNeeded = true;
}
// Destroy VM Snapshots
List<VMSnapshotVO> vmSnapshots = _vmSnapshotDao.listByAccountId(Long.valueOf(accountId));
for (VMSnapshot vmSnapshot : vmSnapshots) {
try {
_vmSnapshotMgr.deleteVMSnapshot(vmSnapshot.getId());
} catch (Exception e) {
logger.debug("Failed to cleanup Instance Snapshot {} due to {}", vmSnapshot, e.toString());
}
}
cleanupPluginsResourcesIfNeeded(account);