-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
Copy pathcustom.py
2568 lines (2104 loc) · 112 KB
/
custom.py
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
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# pylint: disable=too-many-lines
import codecs
import hashlib
import json
import math
import os
import re
import struct
import time
import uuid
from ipaddress import ip_network
from azure.cli.command_modules.keyvault._client_factory import get_client_factory, Clients, is_azure_stack_profile
from azure.cli.command_modules.keyvault._validators import _construct_vnet, secret_text_encoding_values
from azure.cli.command_modules.keyvault.security_domain.jwe import JWE
from azure.cli.command_modules.keyvault.security_domain.security_domain import Datum, SecurityDomainRestoreData
from azure.cli.command_modules.keyvault.security_domain.shared_secret import SharedSecret
from azure.cli.command_modules.keyvault.security_domain.sp800_108 import KDF
from azure.cli.command_modules.keyvault.security_domain.utils import Utils
from azure.cli.core import telemetry
from azure.cli.core.azclierror import InvalidArgumentValueError, RequiredArgumentMissingError,\
MutuallyExclusiveArgumentError
from azure.cli.core.profiles import ResourceType, AZURE_API_PROFILES, SDKProfile
from azure.cli.core.util import sdk_no_wait
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa, ec
from cryptography.hazmat.primitives.serialization import load_pem_private_key, Encoding, PublicFormat
from cryptography.exceptions import UnsupportedAlgorithm
from cryptography.x509 import load_pem_x509_certificate
from knack.log import get_logger
from knack.util import CLIError
logger = get_logger(__name__)
def _not_less_than(current_profile, resource_type, min_api_version, sub_resource_name=None):
if current_profile not in AZURE_API_PROFILES:
raise CLIError('Unsupported profile: {}'.format(current_profile))
profile = AZURE_API_PROFILES[current_profile]
if resource_type not in profile:
raise CLIError('ResourceType {} not in Profile {}'.format(resource_type, current_profile))
if not sub_resource_name:
api_version = profile[resource_type]
if isinstance(api_version, SDKProfile):
return api_version.default_api_version >= min_api_version
return api_version >= min_api_version
sdk_profile = profile[resource_type]
if not isinstance(sdk_profile, SDKProfile):
raise CLIError('Invalid SDKProfile {} in Profile {}'.format(resource_type, current_profile))
sub_profile = sdk_profile.profile
if sub_resource_name not in sub_profile:
raise CLIError('SubResource {} not in ResourceType {} under Profile {}'.
format(sub_resource_name, resource_type, current_profile))
api_version = sub_profile[sub_resource_name]
return api_version >= min_api_version
def _azure_stack_wrapper(cmd, client, function_name, resource_type, min_api_version, sub_resource_name=None, **kwargs):
no_wait = False
if 'no_wait' in kwargs:
no_wait = kwargs.pop('no_wait')
if _not_less_than(cmd.cli_ctx.cloud.profile, resource_type, min_api_version, sub_resource_name):
function_name = 'begin_' + function_name
return sdk_no_wait(no_wait, getattr(client, function_name), **kwargs)
return getattr(client, function_name)(**kwargs)
def _default_certificate_profile(cmd):
def get_model(x):
return cmd.loader.get_sdk(x, resource_type=ResourceType.DATA_KEYVAULT_CERTIFICATES, mod='_generated_models')
Action = get_model('Action')
ActionType = get_model('ActionType')
KeyUsageType = get_model('KeyUsageType')
CertificateAttributes = get_model('CertificateAttributes')
CertificatePolicy = get_model('CertificatePolicy')
IssuerParameters = get_model('IssuerParameters')
KeyProperties = get_model('KeyProperties')
LifetimeAction = get_model('LifetimeAction')
SecretProperties = get_model('SecretProperties')
X509CertificateProperties = get_model('X509CertificateProperties')
Trigger = get_model('Trigger')
template = CertificatePolicy(
key_properties=KeyProperties(
exportable=True,
key_type=u'RSA',
key_size=2048,
reuse_key=True
),
secret_properties=SecretProperties(
content_type=u'application/x-pkcs12'
),
x509_certificate_properties=X509CertificateProperties(
key_usage=[
KeyUsageType.c_rl_sign,
KeyUsageType.data_encipherment,
KeyUsageType.digital_signature,
KeyUsageType.key_encipherment,
KeyUsageType.key_agreement,
KeyUsageType.key_cert_sign
],
subject=u'CN=CLIGetDefaultPolicy',
validity_in_months=12
),
lifetime_actions=[LifetimeAction(
trigger=Trigger(
days_before_expiry=90
),
action=Action(
action_type=ActionType.auto_renew
)
)],
issuer_parameters=IssuerParameters(
name=u'Self',
),
attributes=CertificateAttributes(
enabled=True
)
)
del template.id
del template.attributes
del template.issuer_parameters.certificate_type
del template.lifetime_actions[0].trigger.lifetime_percentage
del template.x509_certificate_properties.subject_alternative_names
del template.x509_certificate_properties.ekus
return template
def _scaffold_certificate_profile(cmd):
def get_model(x):
return cmd.loader.get_sdk(x, resource_type=ResourceType.DATA_KEYVAULT_CERTIFICATES, mod='_generated_models')
Action = get_model('Action')
ActionType = get_model('ActionType')
KeyUsageType = get_model('KeyUsageType')
CertificateAttributes = get_model('CertificateAttributes')
CertificatePolicy = get_model('CertificatePolicy')
IssuerParameters = get_model('IssuerParameters')
KeyProperties = get_model('KeyProperties')
LifetimeAction = get_model('LifetimeAction')
SecretProperties = get_model('SecretProperties')
X509CertificateProperties = get_model('X509CertificateProperties')
SubjectAlternativeNames = get_model('SubjectAlternativeNames')
Trigger = get_model('Trigger')
template = CertificatePolicy(
key_properties=KeyProperties(
exportable=True,
key_type=u'(optional) RSA or RSA-HSM (default RSA)',
key_size=2048,
reuse_key=True
),
secret_properties=SecretProperties(
content_type=u'application/x-pkcs12 or application/x-pem-file'
),
x509_certificate_properties=X509CertificateProperties(
key_usage=[
KeyUsageType.c_rl_sign,
KeyUsageType.data_encipherment,
KeyUsageType.digital_signature,
KeyUsageType.key_encipherment,
KeyUsageType.key_agreement,
KeyUsageType.key_cert_sign
],
subject_alternative_names=SubjectAlternativeNames(
emails=[u'hello@contoso.com'],
dns_names=[u'hr.contoso.com', u'm.contoso.com'],
upns=[]
),
subject=u'C=US, ST=WA, L=Redmond, O=Contoso, OU=Contoso HR, CN=www.contoso.com',
ekus=[u'1.3.6.1.5.5.7.3.1'],
validity_in_months=24
),
lifetime_actions=[LifetimeAction(
trigger=Trigger(
days_before_expiry=90
),
action=Action(
action_type=ActionType.auto_renew
)
)],
issuer_parameters=IssuerParameters(
name=u'Unknown, Self, or {IssuerName}',
certificate_type=u'(optional) DigiCert, GlobalSign or WoSign'
),
attributes=CertificateAttributes(
enabled=True
)
)
del template.id
del template.attributes
return template
def delete_vault_or_hsm(cmd, client, resource_group_name=None, vault_name=None, hsm_name=None, no_wait=False):
if is_azure_stack_profile(cmd) or vault_name:
return client.delete(resource_group_name=resource_group_name, vault_name=vault_name)
assert hsm_name
hsm_client = get_client_factory(ResourceType.MGMT_KEYVAULT, Clients.managed_hsms)(cmd.cli_ctx, None)
logger.warning('This command will soft delete the resource, and you will still be billed until it is purged. '
'For more information, go to https://aka.ms/doc/KeyVaultMHSMSoftDelete')
return sdk_no_wait(
no_wait, hsm_client.begin_delete,
resource_group_name=resource_group_name,
name=hsm_name
)
def get_deleted_vault_or_hsm(cmd, client, location=None, vault_name=None, hsm_name=None):
if is_azure_stack_profile(cmd) or vault_name:
return client.get_deleted(vault_name=vault_name, location=location)
hsm_client = get_client_factory(ResourceType.MGMT_KEYVAULT, Clients.managed_hsms)(cmd.cli_ctx, None)
return hsm_client.get_deleted(name=hsm_name, location=location)
def purge_vault_or_hsm(cmd, client, location=None, vault_name=None, hsm_name=None, # pylint: disable=unused-argument
no_wait=False):
if is_azure_stack_profile(cmd) or vault_name:
return sdk_no_wait(
no_wait,
client.begin_purge_deleted,
location=location,
vault_name=vault_name
)
hsm_client = get_client_factory(ResourceType.MGMT_KEYVAULT, Clients.managed_hsms)(cmd.cli_ctx, None)
return sdk_no_wait(
no_wait,
hsm_client.begin_purge_deleted,
location=location,
name=hsm_name
)
def list_deleted_vault_or_hsm(cmd, client, resource_type=None):
if is_azure_stack_profile(cmd):
return client.list_deleted()
if resource_type is None:
hsm_client = get_client_factory(ResourceType.MGMT_KEYVAULT, Clients.managed_hsms)(cmd.cli_ctx, None)
resources = []
resources.extend(client.list_deleted())
resources.extend(hsm_client.list_deleted())
return resources
if resource_type == 'hsm':
hsm_client = get_client_factory(ResourceType.MGMT_KEYVAULT, Clients.managed_hsms)(cmd.cli_ctx, None)
return hsm_client.list_deleted()
if resource_type == 'vault':
return client.list_deleted()
raise CLIError('Unsupported resource type: {}'.format(resource_type))
def list_vault_or_hsm(cmd, client, resource_group_name=None, resource_type=None):
if is_azure_stack_profile(cmd):
return list_vault(client, resource_group_name)
if resource_type is None:
hsm_client = get_client_factory(ResourceType.MGMT_KEYVAULT, Clients.managed_hsms)(cmd.cli_ctx, None)
resources = []
try:
resources.extend(list_vault(client, resource_group_name))
resources.extend(list_hsm(hsm_client, resource_group_name))
except: # pylint: disable=bare-except
pass
return resources
if resource_type == 'hsm':
hsm_client = get_client_factory(ResourceType.MGMT_KEYVAULT, Clients.managed_hsms)(cmd.cli_ctx, None)
return list_hsm(hsm_client, resource_group_name)
if resource_type == 'vault':
return list_vault(client, resource_group_name)
raise CLIError('Unsupported resource type: {}'.format(resource_type))
def list_hsm(client, resource_group_name=None):
hsm_list = client.list_by_resource_group(resource_group_name=resource_group_name) \
if resource_group_name else client.list_by_subscription()
return list(hsm_list)
def list_vault(client, resource_group_name=None):
vault_list = client.list_by_resource_group(resource_group_name=resource_group_name) \
if resource_group_name else client.list()
return list(vault_list)
def _get_current_user_object_id(graph_client):
current_user = graph_client.signed_in_user_get()
return current_user['id']
def _get_object_id_by_spn(graph_client, spn):
accounts = list(graph_client.service_principal_list(
filter="servicePrincipalNames/any(c:c eq '{}')".format(spn)))
if not accounts:
logger.warning("Unable to find user with spn '%s'", spn)
return None
if len(accounts) > 1:
logger.warning("Multiple service principals found with spn '%s'. "
"You can avoid this by specifying object id.", spn)
return None
return accounts[0]['id']
def _get_object_id_by_upn(graph_client, upn):
accounts = list(graph_client.user_list(filter="userPrincipalName eq '{}'".format(upn)))
if not accounts:
logger.warning("Unable to find user with upn '%s'", upn)
return None
if len(accounts) > 1:
logger.warning("Multiple users principals found with upn '%s'. "
"You can avoid this by specifying object id.", upn)
return None
return accounts[0]['id']
def _get_object_id_from_subscription(graph_client, subscription):
if not subscription:
return None
if subscription['user']:
if subscription['user']['type'] == 'user':
return _get_object_id_by_upn(graph_client, subscription['user']['name'])
if subscription['user']['type'] == 'servicePrincipal':
return _get_object_id_by_spn(graph_client, subscription['user']['name'])
logger.warning("Unknown user type '%s'", subscription['user']['type'])
else:
logger.warning('Current credentials are not from a user or service principal. '
'Azure Key Vault does not work with certificate credentials.')
return None
def _get_object_id(graph_client, subscription=None, spn=None, upn=None):
if spn:
return _get_object_id_by_spn(graph_client, spn)
if upn:
return _get_object_id_by_upn(graph_client, upn)
return _get_object_id_from_subscription(graph_client, subscription)
def _create_network_rule_set(cmd, bypass=None, default_action=None):
NetworkRuleSet = cmd.get_models('NetworkRuleSet', resource_type=ResourceType.MGMT_KEYVAULT)
NetworkRuleBypassOptions = cmd.get_models('NetworkRuleBypassOptions', resource_type=ResourceType.MGMT_KEYVAULT)
NetworkRuleAction = cmd.get_models('NetworkRuleAction', resource_type=ResourceType.MGMT_KEYVAULT)
return NetworkRuleSet(bypass=bypass or NetworkRuleBypassOptions.azure_services.value,
default_action=default_action or NetworkRuleAction.allow.value)
# region KeyVault Vault
def get_default_policy(cmd, scaffold=False): # pylint: disable=unused-argument
"""
Get a default certificate policy to be used with `az keyvault certificate create`
:param bool scaffold: create a fully formed policy structure with default values
:return: policy dict
:rtype: dict
"""
return _scaffold_certificate_profile(cmd) if scaffold else _default_certificate_profile(cmd)
def recover_vault_or_hsm(cmd, client, resource_group_name=None, location=None, vault_name=None, hsm_name=None,
no_wait=False):
if is_azure_stack_profile(cmd) or vault_name:
return recover_vault(cmd=cmd,
client=client,
resource_group_name=resource_group_name,
location=location,
vault_name=vault_name,
no_wait=no_wait)
if hsm_name:
hsm_client = get_client_factory(ResourceType.MGMT_KEYVAULT, Clients.managed_hsms)(cmd.cli_ctx, None)
return recover_hsm(cmd=cmd,
client=hsm_client,
resource_group_name=resource_group_name,
location=location,
hsm_name=hsm_name,
no_wait=no_wait)
def recover_hsm(cmd, client, hsm_name, resource_group_name, location, no_wait=False):
from azure.cli.core._profile import Profile, _TENANT_ID
ManagedHsm = cmd.get_models('ManagedHsm', resource_type=ResourceType.MGMT_KEYVAULT)
ManagedHsmSku = cmd.get_models('ManagedHsmSku', resource_type=ResourceType.MGMT_KEYVAULT)
# tenantId and sku shouldn't be required
profile = Profile(cli_ctx=cmd.cli_ctx)
tenant_id = profile.get_subscription(subscription=cmd.cli_ctx.data.get('subscription_id', None))[_TENANT_ID]
# Use 'Recover' as 'create_mode' temporarily since it's a bug from service side making 'create_mode' case-sensitive
# Will change it back to CreateMode.recover.value('recover') from SDK definition after service fix
parameters = ManagedHsm(location=location,
sku=ManagedHsmSku(name='Standard_B1', family='B'),
properties={'tenant_id': tenant_id, 'create_mode': 'Recover'})
return sdk_no_wait(
no_wait, client.begin_create_or_update,
resource_group_name=resource_group_name,
name=hsm_name,
parameters=parameters
)
def recover_vault(cmd, client, vault_name, resource_group_name, location, no_wait=False):
from azure.cli.core._profile import Profile, _TENANT_ID
VaultCreateOrUpdateParameters = cmd.get_models('VaultCreateOrUpdateParameters',
resource_type=ResourceType.MGMT_KEYVAULT)
CreateMode = cmd.get_models('CreateMode', resource_type=ResourceType.MGMT_KEYVAULT)
# tenantId and sku shouldn't be required
Sku = cmd.get_models('Sku', resource_type=ResourceType.MGMT_KEYVAULT)
SkuName = cmd.get_models('SkuName', resource_type=ResourceType.MGMT_KEYVAULT)
profile = Profile(cli_ctx=cmd.cli_ctx)
tenant_id = profile.get_subscription(subscription=cmd.cli_ctx.data.get('subscription_id', None))[_TENANT_ID]
params = VaultCreateOrUpdateParameters(location=location,
properties={'tenant_id': tenant_id,
'sku': Sku(name=SkuName.standard.value, family='A'),
'create_mode': CreateMode.recover.value})
return _azure_stack_wrapper(cmd, client, 'create_or_update',
resource_type=ResourceType.MGMT_KEYVAULT,
min_api_version='2018-02-14',
resource_group_name=resource_group_name,
vault_name=vault_name,
parameters=params,
no_wait=no_wait)
def _parse_network_acls(cmd, resource_group_name, network_acls_json, network_acls_ips, network_acls_vnets,
bypass, default_action):
if network_acls_json is None:
network_acls_json = {}
rule_names = ['ip', 'vnet']
for rn in rule_names:
if rn not in network_acls_json:
network_acls_json[rn] = []
if network_acls_ips:
for ip_rule in network_acls_ips:
if ip_rule not in network_acls_json['ip']:
network_acls_json['ip'].append(ip_rule)
if network_acls_vnets:
for vnet_rule in network_acls_vnets:
if vnet_rule not in network_acls_json['vnet']:
network_acls_json['vnet'].append(vnet_rule)
VirtualNetworkRule = cmd.get_models('VirtualNetworkRule', resource_type=ResourceType.MGMT_KEYVAULT)
IPRule = cmd.get_models('IPRule', resource_type=ResourceType.MGMT_KEYVAULT)
network_acls = _create_network_rule_set(cmd, bypass, default_action)
from msrestazure.tools import is_valid_resource_id
network_acls.virtual_network_rules = []
for vnet_rule in network_acls_json.get('vnet', []):
items = vnet_rule.split('/')
if len(items) == 2:
vnet_name = items[0].lower()
subnet_name = items[1].lower()
vnet = _construct_vnet(cmd, resource_group_name, vnet_name, subnet_name)
network_acls.virtual_network_rules.append(VirtualNetworkRule(id=vnet))
else:
subnet_id = vnet_rule.lower()
if is_valid_resource_id(subnet_id):
network_acls.virtual_network_rules.append(VirtualNetworkRule(id=subnet_id))
else:
raise CLIError('Invalid VNet rule: {}. Format: {{vnet_name}}/{{subnet_name}} or {{subnet_id}}'.
format(vnet_rule))
network_acls.ip_rules = []
for ip_rule in network_acls_json.get('ip', []):
network_acls.ip_rules.append(IPRule(value=ip_rule))
return network_acls
def get_vault_or_hsm(cmd, client, resource_group_name, vault_name=None, hsm_name=None):
if is_azure_stack_profile(cmd) or vault_name:
return client.get(resource_group_name=resource_group_name, vault_name=vault_name)
hsm_client = get_client_factory(ResourceType.MGMT_KEYVAULT, Clients.managed_hsms)(cmd.cli_ctx, None)
return hsm_client.get(resource_group_name=resource_group_name, name=hsm_name)
def create_vault_or_hsm(cmd, client, # pylint: disable=too-many-locals
resource_group_name, vault_name=None, hsm_name=None,
administrators=None,
location=None, sku=None,
enabled_for_deployment=None,
enabled_for_disk_encryption=None,
enabled_for_template_deployment=None,
enable_rbac_authorization=None,
enable_purge_protection=None,
retention_days=None,
network_acls=None,
network_acls_ips=None,
network_acls_vnets=None,
bypass=None,
default_action=None,
no_self_perms=None,
tags=None,
no_wait=False,
public_network_access=None,
):
if is_azure_stack_profile(cmd) or vault_name:
return create_vault(cmd=cmd,
client=client,
resource_group_name=resource_group_name,
vault_name=vault_name,
location=location,
sku=sku,
enabled_for_deployment=enabled_for_deployment,
enabled_for_disk_encryption=enabled_for_disk_encryption,
enabled_for_template_deployment=enabled_for_template_deployment,
enable_rbac_authorization=enable_rbac_authorization,
enable_purge_protection=enable_purge_protection,
retention_days=retention_days,
network_acls=network_acls,
network_acls_ips=network_acls_ips,
network_acls_vnets=network_acls_vnets,
bypass=bypass,
default_action=default_action,
no_self_perms=no_self_perms,
tags=tags,
no_wait=no_wait,
public_network_access=public_network_access)
if hsm_name:
hsm_client = get_client_factory(ResourceType.MGMT_KEYVAULT, Clients.managed_hsms)(cmd.cli_ctx, None)
from msrest.exceptions import ValidationError
try:
return create_hsm(cmd=cmd,
client=hsm_client,
resource_group_name=resource_group_name,
hsm_name=hsm_name,
administrators=administrators,
location=location,
sku=sku,
enable_purge_protection=enable_purge_protection,
retention_days=retention_days,
bypass=bypass,
default_action=default_action,
tags=tags,
no_wait=no_wait)
except ValidationError as ex:
error_msg = str(ex)
if 'Parameter \'name\' must conform to the following pattern' in error_msg:
error_msg = 'Managed HSM name must be between 3-24 alphanumeric characters. ' \
'The name must begin with a letter, end with a letter or digit, ' \
'and not contain hyphens.'
raise CLIError(error_msg)
def create_hsm(cmd, client,
resource_group_name, hsm_name, administrators, location=None, sku=None,
enable_purge_protection=None,
retention_days=None,
public_network_access=None,
bypass=None,
default_action=None,
tags=None,
no_wait=False): # pylint: disable=unused-argument
if not administrators:
raise CLIError('Please specify --administrators')
administrators = [admin.strip().replace('\r', '').replace('\n', '') for admin in administrators]
from azure.cli.core._profile import Profile, _TENANT_ID
if not sku:
sku = 'Standard_B1'
ManagedHsm = cmd.get_models('ManagedHsm', resource_type=ResourceType.MGMT_KEYVAULT)
ManagedHsmProperties = cmd.get_models('ManagedHsmProperties', resource_type=ResourceType.MGMT_KEYVAULT)
ManagedHsmSku = cmd.get_models('ManagedHsmSku', resource_type=ResourceType.MGMT_KEYVAULT)
profile = Profile(cli_ctx=cmd.cli_ctx)
tenant_id = profile.get_subscription(subscription=cmd.cli_ctx.data.get('subscription_id', None))[_TENANT_ID]
properties = ManagedHsmProperties(tenant_id=tenant_id,
enable_purge_protection=enable_purge_protection,
soft_delete_retention_in_days=retention_days,
initial_admin_object_ids=administrators,
network_acls=_create_network_rule_set(cmd, bypass, default_action),
public_network_access=public_network_access)
parameters = ManagedHsm(location=location,
tags=tags,
sku=ManagedHsmSku(name=sku, family='B'),
properties=properties)
return sdk_no_wait(no_wait, client.begin_create_or_update,
resource_group_name=resource_group_name,
name=hsm_name,
parameters=parameters)
def wait_hsm(client, hsm_name, resource_group_name):
return client.get(resource_group_name=resource_group_name, name=hsm_name)
def create_vault(cmd, client, # pylint: disable=too-many-locals, too-many-statements
resource_group_name, vault_name, location=None, sku=None,
enabled_for_deployment=None,
enabled_for_disk_encryption=None,
enabled_for_template_deployment=None,
enable_rbac_authorization=None,
enable_purge_protection=None,
retention_days=None,
network_acls=None,
network_acls_ips=None,
network_acls_vnets=None,
bypass=None,
default_action=None,
no_self_perms=None,
tags=None,
no_wait=False,
public_network_access=None):
from azure.core.exceptions import HttpResponseError
try:
vault = client.get(resource_group_name=resource_group_name, vault_name=vault_name)
if vault:
raise InvalidArgumentValueError('The specified vault: {} already exists'.format(vault_name))
except HttpResponseError:
# if client.get raise exception, we can take it as no existing vault found
# just continue the normal creation process
pass
from azure.cli.core._profile import Profile, _TENANT_ID
from azure.cli.command_modules.role import graph_client_factory, GraphError
VaultCreateOrUpdateParameters = cmd.get_models('VaultCreateOrUpdateParameters',
resource_type=ResourceType.MGMT_KEYVAULT)
Permissions = cmd.get_models('Permissions', resource_type=ResourceType.MGMT_KEYVAULT)
KeyPermissions = cmd.get_models('KeyPermissions', resource_type=ResourceType.MGMT_KEYVAULT)
SecretPermissions = cmd.get_models('SecretPermissions', resource_type=ResourceType.MGMT_KEYVAULT)
CertificatePermissions = cmd.get_models('CertificatePermissions', resource_type=ResourceType.MGMT_KEYVAULT)
StoragePermissions = cmd.get_models('StoragePermissions', resource_type=ResourceType.MGMT_KEYVAULT)
AccessPolicyEntry = cmd.get_models('AccessPolicyEntry', resource_type=ResourceType.MGMT_KEYVAULT)
Sku = cmd.get_models('Sku', resource_type=ResourceType.MGMT_KEYVAULT)
VaultProperties = cmd.get_models('VaultProperties', resource_type=ResourceType.MGMT_KEYVAULT)
profile = Profile(cli_ctx=cmd.cli_ctx)
graph_client = graph_client_factory(cmd.cli_ctx)
subscription = profile.get_subscription(subscription=cmd.cli_ctx.data.get('subscription_id', None))
tenant_id = subscription[_TENANT_ID]
# if bypass or default_action was specified create a NetworkRuleSet
# if neither were specified we will parse it from parameter `--network-acls`
if cmd.supported_api_version(resource_type=ResourceType.MGMT_KEYVAULT, min_api='2018-02-14'):
if network_acls or network_acls_ips or network_acls_vnets:
network_acls = _parse_network_acls(
cmd, resource_group_name, network_acls, network_acls_ips, network_acls_vnets, bypass, default_action)
else:
network_acls = _create_network_rule_set(cmd, bypass, default_action)
if no_self_perms or enable_rbac_authorization:
access_policies = []
else:
if cmd.supported_api_version(resource_type=ResourceType.MGMT_KEYVAULT, min_api='2019-09-01'):
permissions = Permissions(keys=[KeyPermissions.all],
secrets=[SecretPermissions.all],
certificates=[CertificatePermissions.all],
storage=[StoragePermissions.all])
else:
permissions = Permissions(keys=[KeyPermissions.get,
KeyPermissions.create,
KeyPermissions.delete,
KeyPermissions.list,
KeyPermissions.update,
KeyPermissions.import_enum,
KeyPermissions.backup,
KeyPermissions.restore,
KeyPermissions.recover],
secrets=[
SecretPermissions.get,
SecretPermissions.list,
SecretPermissions.set,
SecretPermissions.delete,
SecretPermissions.backup,
SecretPermissions.restore,
SecretPermissions.recover],
certificates=[
CertificatePermissions.get,
CertificatePermissions.list,
CertificatePermissions.delete,
CertificatePermissions.create,
CertificatePermissions.import_enum,
CertificatePermissions.update,
CertificatePermissions.managecontacts,
CertificatePermissions.getissuers,
CertificatePermissions.listissuers,
CertificatePermissions.setissuers,
CertificatePermissions.deleteissuers,
CertificatePermissions.manageissuers,
CertificatePermissions.recover],
storage=[
StoragePermissions.get,
StoragePermissions.list,
StoragePermissions.delete,
StoragePermissions.set,
StoragePermissions.update,
StoragePermissions.regeneratekey,
StoragePermissions.setsas,
StoragePermissions.listsas,
StoragePermissions.getsas,
StoragePermissions.deletesas])
try:
object_id = _get_current_user_object_id(graph_client)
except GraphError:
object_id = _get_object_id(graph_client, subscription=subscription)
if not object_id:
raise CLIError('Cannot create vault.\nUnable to query active directory for information '
'about the current user.\nYou may try the --no-self-perms flag to '
'create a vault without permissions.')
access_policies = [AccessPolicyEntry(tenant_id=tenant_id,
object_id=object_id,
permissions=permissions)]
if not sku:
sku = 'standard'
properties = VaultProperties(tenant_id=tenant_id,
sku=Sku(name=sku, family='A'),
access_policies=access_policies,
vault_uri=None,
enabled_for_deployment=enabled_for_deployment,
enabled_for_disk_encryption=enabled_for_disk_encryption,
enabled_for_template_deployment=enabled_for_template_deployment,
enable_rbac_authorization=enable_rbac_authorization,
enable_purge_protection=enable_purge_protection,
soft_delete_retention_in_days=int(retention_days),
public_network_access=public_network_access)
if hasattr(properties, 'network_acls'):
properties.network_acls = network_acls
parameters = VaultCreateOrUpdateParameters(location=location,
tags=tags,
properties=properties)
return _azure_stack_wrapper(cmd, client, 'create_or_update',
resource_type=ResourceType.MGMT_KEYVAULT,
min_api_version='2018-02-14',
resource_group_name=resource_group_name,
vault_name=vault_name,
parameters=parameters,
no_wait=no_wait)
def update_vault_setter(cmd, client, parameters, resource_group_name, vault_name, no_wait=False):
VaultCreateOrUpdateParameters = cmd.get_models('VaultCreateOrUpdateParameters',
resource_type=ResourceType.MGMT_KEYVAULT)
return _azure_stack_wrapper(cmd, client, 'create_or_update',
resource_type=ResourceType.MGMT_KEYVAULT,
min_api_version='2018-02-14',
resource_group_name=resource_group_name,
vault_name=vault_name,
parameters=VaultCreateOrUpdateParameters(
location=parameters.location,
tags=parameters.tags,
properties=parameters.properties),
no_wait=no_wait)
def update_hsm_setter(cmd, client, parameters, resource_group_name, name, no_wait=False):
ManagedHsm = cmd.get_models('ManagedHsm', resource_type=ResourceType.MGMT_KEYVAULT)
return sdk_no_wait(no_wait, client.begin_create_or_update,
resource_group_name=resource_group_name,
name=name,
parameters=ManagedHsm(
sku=parameters.sku,
tags=parameters.tags,
location=parameters.location,
properties=parameters.properties))
def update_vault(cmd, instance,
enabled_for_deployment=None,
enabled_for_disk_encryption=None,
enabled_for_template_deployment=None,
enable_rbac_authorization=None,
enable_purge_protection=None,
retention_days=None,
bypass=None,
default_action=None,
public_network_access=None):
if enabled_for_deployment is not None:
instance.properties.enabled_for_deployment = enabled_for_deployment
if enabled_for_disk_encryption is not None:
instance.properties.enabled_for_disk_encryption = enabled_for_disk_encryption
if enabled_for_template_deployment is not None:
instance.properties.enabled_for_template_deployment = enabled_for_template_deployment
if enable_rbac_authorization is not None:
instance.properties.enable_rbac_authorization = enable_rbac_authorization
if enable_purge_protection is not None:
instance.properties.enable_purge_protection = enable_purge_protection
if retention_days is not None:
instance.properties.soft_delete_retention_in_days = int(retention_days)
if bypass or default_action and (hasattr(instance.properties, 'network_acls')):
if instance.properties.network_acls is None:
instance.properties.network_acls = _create_network_rule_set(cmd, bypass, default_action)
else:
if bypass:
instance.properties.network_acls.bypass = bypass
if default_action:
instance.properties.network_acls.default_action = default_action
if public_network_access is not None:
instance.properties.public_network_access = public_network_access
return instance
def update_hsm(cmd, instance,
enable_purge_protection=None,
bypass=None,
default_action=None,
secondary_locations=None,
public_network_access=None):
if enable_purge_protection is not None:
instance.properties.enable_purge_protection = enable_purge_protection
if secondary_locations is not None:
# service not ready
raise InvalidArgumentValueError('--secondary-locations has not been supported yet for hsm')
if public_network_access is not None:
instance.properties.public_network_access = public_network_access
if bypass or default_action and (hasattr(instance.properties, 'network_acls')):
if instance.properties.network_acls is None:
instance.properties.network_acls = _create_network_rule_set(cmd, bypass, default_action)
else:
if bypass:
instance.properties.network_acls.bypass = bypass
if default_action:
instance.properties.network_acls.default_action = default_action
return instance
def _object_id_args_helper(cli_ctx, object_id, spn, upn):
if not object_id:
from azure.cli.command_modules.role import graph_client_factory
graph_client = graph_client_factory(cli_ctx)
object_id = _get_object_id(graph_client, spn=spn, upn=upn)
if not object_id:
raise CLIError('Unable to get object id from principal name.')
return object_id
def _permissions_distinct(permissions):
if permissions:
return list(set(permissions))
return permissions
def set_policy(cmd, client, resource_group_name, vault_name,
object_id=None, application_id=None, spn=None, upn=None, key_permissions=None, secret_permissions=None,
certificate_permissions=None, storage_permissions=None, no_wait=False):
""" Update security policy settings for a Key Vault. """
VaultCreateOrUpdateParameters = cmd.get_models('VaultCreateOrUpdateParameters',
resource_type=ResourceType.MGMT_KEYVAULT)
AccessPolicyEntry = cmd.get_models('AccessPolicyEntry', resource_type=ResourceType.MGMT_KEYVAULT)
Permissions = cmd.get_models('Permissions', resource_type=ResourceType.MGMT_KEYVAULT)
object_id = _object_id_args_helper(cmd.cli_ctx, object_id, spn, upn)
vault = client.get(resource_group_name=resource_group_name,
vault_name=vault_name)
key_permissions = _permissions_distinct(key_permissions)
secret_permissions = _permissions_distinct(secret_permissions)
certificate_permissions = _permissions_distinct(certificate_permissions)
storage_permissions = _permissions_distinct(storage_permissions)
try:
enable_rbac_authorization = getattr(vault.properties, 'enable_rbac_authorization')
except: # pylint: disable=bare-except
pass
else:
if enable_rbac_authorization:
raise CLIError('Cannot set policies to a vault with \'--enable-rbac-authorization\' specified')
# Find the existing policy to set
policy = next((p for p in vault.properties.access_policies
if object_id.lower() == p.object_id.lower() and
(application_id or '').lower() == (p.application_id or '').lower() and
vault.properties.tenant_id.lower() == p.tenant_id.lower()), None)
if not policy:
# Add new policy as none found
vault.properties.access_policies.append(AccessPolicyEntry(
tenant_id=vault.properties.tenant_id,
object_id=object_id,
application_id=application_id,
permissions=Permissions(keys=key_permissions,
secrets=secret_permissions,
certificates=certificate_permissions,
storage=storage_permissions)))
else:
# Modify existing policy.
# If key_permissions is not set, use prev. value (similarly with secret_permissions).
keys = policy.permissions.keys if key_permissions is None else key_permissions
secrets = policy.permissions.secrets if secret_permissions is None else secret_permissions
certs = policy.permissions.certificates \
if certificate_permissions is None else certificate_permissions
storage = policy.permissions.storage if storage_permissions is None else storage_permissions
policy.permissions = Permissions(keys=keys, secrets=secrets, certificates=certs, storage=storage)
return _azure_stack_wrapper(cmd, client, 'create_or_update',
resource_type=ResourceType.MGMT_KEYVAULT,
min_api_version='2018-02-14',
resource_group_name=resource_group_name,
vault_name=vault_name,
parameters=VaultCreateOrUpdateParameters(
location=vault.location,
tags=vault.tags,
properties=vault.properties),
no_wait=no_wait)
def add_network_rule(cmd, client, resource_group_name, vault_name, ip_address=None, subnet=None,
vnet_name=None, no_wait=False): # pylint: disable=unused-argument
""" Add a network rule to the network ACLs for a Key Vault. """
VirtualNetworkRule = cmd.get_models('VirtualNetworkRule', resource_type=ResourceType.MGMT_KEYVAULT)
IPRule = cmd.get_models('IPRule', resource_type=ResourceType.MGMT_KEYVAULT)
VaultCreateOrUpdateParameters = cmd.get_models('VaultCreateOrUpdateParameters',
resource_type=ResourceType.MGMT_KEYVAULT)
vault = client.get(resource_group_name=resource_group_name, vault_name=vault_name)
vault.properties.network_acls = vault.properties.network_acls or _create_network_rule_set(cmd)
rules = vault.properties.network_acls
if not subnet and not ip_address:
logger.warning('No subnet or ip address supplied.')
to_update = False
if subnet:
rules.virtual_network_rules = rules.virtual_network_rules or []
# if the rule already exists, don't add again
to_modify = True
for x in rules.virtual_network_rules:
if x.id.lower() == subnet.lower():
to_modify = False
break
if to_modify:
rules.virtual_network_rules.append(VirtualNetworkRule(id=subnet))
to_update = True
if ip_address:
rules.ip_rules = rules.ip_rules or []
# if the rule already exists, don't add again
for ip in ip_address:
to_modify = True
for x in rules.ip_rules:
existing_ip_network = ip_network(x.value)
new_ip_network = ip_network(ip)
if new_ip_network.overlaps(existing_ip_network):
logger.warning("IP/CIDR %s overlaps with %s, which exists already. Not adding duplicates.",
ip, x.value)
to_modify = False
break
if to_modify:
rules.ip_rules.append(IPRule(value=ip))
to_update = True
# if we didn't modify the network rules just return the vault as is