-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathcustom.py
More file actions
3278 lines (2997 loc) · 153 KB
/
custom.py
File metadata and controls
3278 lines (2997 loc) · 153 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
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# pylint: disable=protected-access, line-too-long, raise-missing-from
# pylint: disable=too-many-lines, too-many-branches, too-many-statements
import copy
from knack.util import CLIError
from knack.log import get_logger
from azure.cli.core.aaz import has_value, register_command
from azure.cli.core.util import sdk_no_wait
from azure.cli.core.azclierror import UserFault, ServiceError, ValidationError, ArgumentUsageError
from azure.cli.core.commands.client_factory import get_subscription_id
from azure.mgmt.core.tools import resource_id
from ._client_factory import network_client_factory
from .aaz.latest.network.firewall import Create as _AzureFirewallCreate, Update as _AzureFirewallUpdate, \
Show as _AzureFirewallShow
from .aaz.latest.network.firewall.policy import Create as _AzureFirewallPoliciesCreate, \
Update as _AzureFirewallPoliciesUpdate, Deploy as _AzureFirewallPoliciesDeploy
from .aaz.latest.network.firewall.policy.rule_collection_group import Create as _RuleCollectionGroupCreate, \
Update as _RuleCollectionGroupUpdate
from .aaz.latest.network.firewall.policy.intrusion_detection import Show as _PolicyIntrusionDetectionShow
from .aaz.latest.network.firewall.policy.draft.intrusion_detection import Show as _PolicyDraftIntrusionDetectionShow
from .aaz.latest.network.firewall.policy.draft import Create as _AzureFirewallPolicyDraftsCreate, \
Update as _AzureFirewallPolicyDraftsUpdate
from .aaz.latest.network.firewall.policy.rule_collection_group.draft import Create as _RuleCollectionGroupDraftCreate, \
Update as _RuleCollectionGroupDraftUpdate
logger = get_logger(__name__)
def _generic_list(cli_ctx, operation_name, resource_group_name):
ncf = network_client_factory(cli_ctx)
operation_group = getattr(ncf, operation_name)
if resource_group_name:
return operation_group.list(resource_group_name)
return operation_group.list_all()
def _get_property(items, name):
result = next((x for x in items if x.name.lower() == name.lower()), None)
if not result:
raise CLIError(f"Property '{name}' does not exist")
return result
def _upsert(parent, collection_name, obj_to_add, key_name, warn=True):
if not getattr(parent, collection_name, None):
setattr(parent, collection_name, [])
collection = getattr(parent, collection_name, None)
value = getattr(obj_to_add, key_name)
if value is None:
raise CLIError(
f"Unable to resolve a value for key '{key_name}' with which to match.")
match = next((x for x in collection if getattr(x, key_name, None) == value), None)
if match:
if warn:
logger.warning("Item '%s' already exists. Replacing with new values.", value)
collection.remove(match)
collection.append(obj_to_add)
def _find_item_at_path(instance, path):
# path accepts the pattern property/name/property/name
curr_item = instance
path_comps = path.split('.')
for i, comp in enumerate(path_comps):
if i % 2:
# name
curr_item = next((x for x in curr_item if x.name == comp), None)
else:
# property
curr_item = getattr(curr_item, comp, None)
if not curr_item:
raise CLIError(f"unable to find '{comp}'...")
return curr_item
# region AzureFirewall
class AzureFirewallCreate(_AzureFirewallCreate):
@classmethod
def _build_arguments_schema(cls, *args, **kwargs):
from azure.cli.core.aaz import AAZListArg, AAZStrArg, AAZBoolArg, AAZResourceIdArg, AAZResourceIdArgFormat, \
AAZIntArg, AAZIntArgFormat
args_schema = super()._build_arguments_schema(*args, **kwargs)
args_schema.private_ranges = AAZListArg(
options=['--private-ranges'],
help="Space-separated list of SNAT privaterange. Validate values are single Ip, "
"Ipprefixes or a single special value \"IANAPrivateRanges\".")
args_schema.private_ranges.Element = AAZStrArg()
args_schema.allow_active_ftp = AAZBoolArg(
options=['--allow-active-ftp'],
help="Allow Active FTP. By default it is false. It's only allowed for azure firewall on virtual network.")
args_schema.enable_fat_flow_logging = AAZBoolArg(
options=['--enable-fat-flow-logging', '--fat-flow-logging'],
help="Allow fat flow logging. By default it is false.")
args_schema.enable_udp_log_optimization = AAZBoolArg(
options=['--enable-udp-log-optimization', '--udp-log-optimization'],
help="Allow UDP log optimization. By default it is false.")
args_schema.dns_servers = AAZListArg(
options=['--dns-servers'],
arg_group="DNS",
help="Space-separated list of DNS server IP addresses.")
args_schema.dns_servers.Element = AAZStrArg()
args_schema.enable_dns_proxy = AAZBoolArg(
options=['--enable-dns-proxy'],
arg_group="DNS",
help="Enable DNS Proxy.")
args_schema.route_server_id = AAZStrArg(
options=['--route-server-id'],
help="The Route Server Id for the firewall.")
args_schema.conf_name = AAZStrArg(
options=["--conf-name"],
arg_group="Data Traffic IP Configuration",
help="Name of the IP configuration.",
)
args_schema.vnet_name = AAZStrArg(
options=["--vnet-name"],
arg_group="Data Traffic IP Configuration",
help="The virtual network (VNet) name. It should contain one subnet called \"AzureFirewallSubnet\".",
)
args_schema.public_ip = AAZResourceIdArg(
options=["--public-ip"],
arg_group="Data Traffic IP Configuration",
help="Name or ID of the public IP to use.",
fmt=AAZResourceIdArgFormat(
template="/subscriptions/{subscription}/resourceGroups/{resource_group}/providers/Microsoft.Network/publicIPAddresses/{}"
),
)
args_schema.enable_explicit_proxy = AAZBoolArg(
options=["--enable-explicit-proxy"],
arg_group="Explicit Proxy",
help="When set to true, explicit proxy mode is enabled.",
)
args_schema.http_port = AAZIntArg(
options=["--http-port"],
arg_group="Explicit Proxy",
help="Port number for explicit proxy http protocol, cannot be greater than 64000.",
fmt=AAZIntArgFormat(
maximum=64000,
minimum=0,
),
)
args_schema.enable_pac_file = AAZBoolArg(
options=["--enable-pac-file"],
arg_group="Explicit Proxy",
help="When set to true, pac file port and url needs to be provided.",
)
args_schema.pac_file_port = AAZIntArg(
options=["--pac-file-port"],
arg_group="Explicit Proxy",
help="Port number for firewall to serve PAC file.",
)
args_schema.pac_file = AAZStrArg(
options=["--pac-file"],
arg_group="Explicit Proxy",
help="SAS URL for PAC file.",
)
args_schema.m_public_ip._fmt = AAZResourceIdArgFormat(
template="/subscriptions/{subscription}/resourceGroups/{resource_group}/providers/Microsoft.Network"
"/publicIPAddresses/{}",
)
args_schema.firewall_policy._fmt = AAZResourceIdArgFormat(
template="/subscriptions/{subscription}/resourceGroups/{resource_group}/providers/Microsoft.Network"
"/firewallPolicies/{}",
)
args_schema.virtual_hub._fmt = AAZResourceIdArgFormat(
template="/subscriptions/{subscription}/resourceGroups/{resource_group}/providers/Microsoft.Network"
"/virtualHubs/{}",
)
args_schema.additional_properties._registered = False
args_schema.ip_configurations._registered = False
args_schema.mgmt_ip_conf_subnet._registered = False
return args_schema
def pre_operations(self):
args = self.ctx.args
if has_value(args.public_ip_count) and has_value(args.public_ip):
raise CLIError(
'usage error: Cannot add both --public-ip-count and --public-ip at the same time.')
if has_value(args.sku):
sku = args.sku.to_serialized_data()
if sku.lower() == 'azfw_hub':
if not has_value(args.virtual_hub):
raise CLIError(
'usage error: virtual hub is mandatory for azure firewall on virtual hub.')
if not has_value(args.public_ip_count) and not has_value(args.public_ip):
raise CLIError(
'usage error: One of public-ip or public-ip-count should be provided for azure firewall on virtual hub.')
if has_value(args.allow_active_ftp):
raise CLIError('usage error: allow active ftp is not allowed for azure firewall on virtual hub.')
if has_value(args.public_ip):
args.ip_configurations = [{
"name": args.conf_name if has_value(args.conf_name) else "AzureFirewallIpConfiguration0",
"public_ip_address": args.public_ip}]
if has_value(args.firewall_policy) and any([args.enable_dns_proxy, args.dns_servers]):
raise CLIError('usage error: firewall policy and dns settings cannot co-exist.')
# validate basic sku firewall
if has_value(args.tier) and has_value(args.sku):
tier = args.tier.to_serialized_data()
if tier.lower() == 'basic' and sku.lower() == 'azfw_vnet' \
and not all([args.m_conf_name, args.m_public_ip]):
err_msg = "When creating Basic SKU firewall, both --m-conf-name and --m-public-ip-address should be provided."
raise ValidationError(err_msg)
args.additional_properties = {}
if has_value(args.private_ranges):
private_ranges = args.private_ranges.to_serialized_data()
args.additional_properties['Network.SNAT.PrivateRanges'] = ', '.join(private_ranges)
if not has_value(args.sku) or sku.lower() == 'azfw_vnet':
if not has_value(args.firewall_policy):
if has_value(args.enable_dns_proxy):
# service side requires lowercase
if args.enable_dns_proxy:
args.additional_properties['Network.DNS.EnableProxy'] = 'true'
else:
args.additional_properties['Network.DNS.EnableProxy'] = 'false'
if has_value(args.dns_servers):
dns_servers = args.dns_servers.to_serialized_data()
args.additional_properties['Network.DNS.Servers'] = ','.join(dns_servers or '')
if has_value(args.allow_active_ftp) and args.allow_active_ftp:
args.additional_properties['Network.FTP.AllowActiveFTP'] = 'true'
if has_value(args.enable_fat_flow_logging) and args.enable_fat_flow_logging:
args.additional_properties['Network.AdditionalLogs.EnableFatFlowLogging'] = 'true'
if has_value(args.enable_udp_log_optimization) and args.enable_udp_log_optimization:
args.additional_properties['Network.AdditionalLogs.EnableUdpLogOptimization'] = 'true'
if has_value(args.route_server_id):
args.additional_properties['Network.RouteServerInfo.RouteServerID'] = args.route_server_id
if has_value(args.conf_name) and has_value(args.sku) and sku.lower() == 'azfw_vnet':
subnet_id = resource_id(
subscription=get_subscription_id(self.cli_ctx),
resource_group=args.resource_group,
namespace='Microsoft.Network',
type='virtualNetworks',
name=args.vnet_name,
child_type_1='subnets',
child_name_1='AzureFirewallSubnet'
)
args.ip_configurations = [{"name": args.conf_name,
"subnet": subnet_id if has_value(subnet_id) else None,
"public_ip_address": args.public_ip if has_value(args.public_ip) else None}]
if has_value(args.tier) and has_value(args.sku):
if tier.lower() == 'basic' and sku.lower() == 'azfw_vnet':
management_subnet_id = resource_id(
subscription=get_subscription_id(self.cli_ctx),
resource_group=args.resource_group,
namespace='Microsoft.Network',
type='virtualNetworks',
name=args.vnet_name,
child_type_1='subnets',
child_name_1='AzureFirewallManagementSubnet'
)
args.mgmt_ip_conf_subnet = management_subnet_id
if has_value(args.enable_explicit_proxy):
args.additional_properties['Network.ExplicitProxy.EnableExplicitProxy'] = args.enable_explicit_proxy
if has_value(args.http_port):
args.additional_properties['Network.ExplicitProxy.HttpPort'] = args.http_port
if has_value(args.enable_pac_file):
args.additional_properties['Network.ExplicitProxy.EnablePacFile'] = args.enable_pac_file
if has_value(args.pac_file_port):
args.additional_properties['Network.ExplicitProxy.PacFilePort'] = args.pac_file_port
if has_value(args.pac_file):
args.additional_properties['Network.ExplicitProxy.PacFile'] = args.pac_file
# pylint: disable=too-many-branches disable=too-many-statements
class AzureFirewallUpdate(_AzureFirewallUpdate):
@classmethod
def _build_arguments_schema(cls, *args, **kwargs):
from azure.cli.core.aaz import AAZListArg, AAZStrArg, AAZBoolArg, AAZResourceIdArgFormat
args_schema = super()._build_arguments_schema(*args, **kwargs)
args_schema.private_ranges = AAZListArg(
options=['--private-ranges'],
help="Space-separated list of SNAT private ranges. Valid values are single IP, "
"IP prefixes or a single special value \"IANAPrivateRanges\".",
nullable=True)
args_schema.private_ranges.Element = AAZStrArg(nullable=True)
args_schema.allow_active_ftp = AAZBoolArg(
options=['--allow-active-ftp'],
help="Allow Active FTP. By default it is false. It's only allowed for azure firewall on virtual network.",
nullable=True, )
args_schema.enable_fat_flow_logging = AAZBoolArg(
options=['--enable-fat-flow-logging', '--fat-flow-logging'],
help="Allow fat flow logging. By default it is false.",
nullable=True)
args_schema.enable_udp_log_optimization = AAZBoolArg(
options=['--enable-udp-log-optimization', '--udp-log-optimization'],
help="Allow UDP log optimization. By default it is false.",
nullable=True)
args_schema.dns_servers = AAZListArg(
options=['--dns-servers'],
arg_group="DNS",
help="Space-separated list of DNS server IP addresses.",
nullable=True)
args_schema.dns_servers.Element = AAZStrArg(nullable=True)
args_schema.enable_dns_proxy = AAZBoolArg(
options=['--enable-dns-proxy'],
arg_group="DNS",
help="Enable DNS Proxy.",
nullable=True)
args_schema.public_ips = AAZListArg(
options=['--public-ips'],
arg_group="Virtual Hub Public Ip",
help="Space-separated list of Public IP addresses associated with azure firewall. "
"It's used to delete public ip addresses from this firewall.",
nullable=True)
args_schema.public_ips.Element = AAZStrArg(nullable=True)
# "Network.RouteServerInfo.RouteServerID"
args_schema.route_server_id = AAZStrArg(
options=['--route-server-id'],
help="The Route Server Id for the firewall.",
nullable=True)
args_schema.virtual_hub._fmt = AAZResourceIdArgFormat(
template="/subscriptions/{subscription}/resourceGroups/{resource_group}/providers/Microsoft.Network"
"/virtualHubs/{}",
)
args_schema.addresses._registered = False
args_schema.additional_properties._registered = False
return args_schema
def pre_operations(self):
args = self.ctx.args
if has_value(args.firewall_policy) and any([args.enable_dns_proxy, args.dns_servers]):
raise CLIError('usage error: firewall policy and dns settings cannot co-exist.')
if all([args.public_ips, args.public_ip_count]):
raise CLIError('Cannot add and remove public ip addresses at same time.')
if has_value(args.virtual_hub):
if args.virtual_hub == '':
args.virtual_hub = None
def pre_instance_update(self, instance):
args = self.ctx.args
if has_value(args.private_ranges):
if not has_value(instance.properties.additional_properties):
instance.properties.additional_properties = {}
private_ranges = args.private_ranges.to_serialized_data()
instance.properties.additional_properties['Network.SNAT.PrivateRanges'] = ', '.join(private_ranges)
if has_value(args.enable_dns_proxy):
if not has_value(instance.properties.additional_properties):
instance.properties.additional_properties = {}
# service side requires lowercase
if args.enable_dns_proxy:
instance.properties.additional_properties['Network.DNS.EnableProxy'] = 'true'
else:
instance.properties.additional_properties['Network.DNS.EnableProxy'] = 'false'
if has_value(args.dns_servers):
if not has_value(instance.properties.additional_properties):
instance.properties.additional_properties = {}
dns_servers = args.dns_servers.to_serialized_data()
instance.properties.additional_properties['Network.DNS.Servers'] = ','.join(dns_servers or '')
if has_value(args.route_server_id):
if not has_value(instance.properties.additional_properties):
instance.properties.additional_properties = {}
instance.properties.additional_properties['Network.RouteServerInfo.RouteServerID'] = args.route_server_id
if has_value(args.public_ips):
try:
if instance.hub_ip_addresses is not None:
pass
except AttributeError:
raise CLIError('Cannot delete public ip addresses from vhub without creation.')
if has_value(args.public_ip_count):
try:
if has_value(instance.hub_ip_addresses.public_i_ps.count) and \
args.public_ip_count.to_serialized_data() > \
instance.hub_ip_addresses.public_i_ps.count.to_serialized_data(): # pylint: disable=line-too-long
instance.hub_ip_addresses.public_i_ps.count = args.public_ip_count
else:
raise CLIError('Cannot decrease the count of hub ip addresses through --count.')
except AttributeError:
pass
if has_value(args.public_ips):
try:
if len(args.public_ips.to_serialized_data()) > \
instance.hub_ip_addresses.public_i_ps.count.to_serialized_data():
raise CLIError('Number of public ip addresses must be less than or equal to existing ones.')
from azure.cli.core.aaz.utils import assign_aaz_list_arg
args.addresses = assign_aaz_list_arg(
args.addresses,
args.public_ips,
element_transformer=lambda _, public_ip: {"address": public_ip}
)
args.public_ip_count = len(args.public_ips.to_serialized_data())
# instance.hub_ip_addresses.public_i_ps.addresses = [{"address": ip} for ip in args.hub_public_ip_addresses] # pylint: disable=line-too-long
# instance.hub_ip_addresses.public_i_ps.count = len(args.hub_public_ip_addresses.to_serialized_data())
except AttributeError as err:
raise CLIError('Public Ip addresses must exist before deleting them.') from err
if has_value(args.allow_active_ftp):
if not has_value(instance.properties.additional_properties):
instance.properties.additional_properties = {}
if args.allow_active_ftp:
instance.properties.additional_properties['Network.FTP.AllowActiveFTP'] = 'true'
elif 'Network.FTP.AllowActiveFTP' in instance.properties.additional_properties:
del instance.properties.additional_properties['Network.FTP.AllowActiveFTP']
if has_value(args.enable_fat_flow_logging):
if not has_value(instance.properties.additional_properties):
instance.properties.additional_properties = {}
if args.enable_fat_flow_logging:
instance.properties.additional_properties['Network.AdditionalLogs.EnableFatFlowLogging'] = 'true'
elif 'Network.AdditionalLogs.EnableFatFlowLogging' in instance.properties.additional_properties:
del instance.properties.additional_properties['Network.AdditionalLogs.EnableFatFlowLogging']
if has_value(args.enable_udp_log_optimization):
if not has_value(instance.properties.additional_properties):
instance.properties.additional_properties = {}
if args.enable_udp_log_optimization:
instance.properties.additional_properties['Network.AdditionalLogs.EnableUdpLogOptimization'] = 'true'
elif 'Network.AdditionalLogs.EnableUdpLogOptimization' in instance.properties.additional_properties:
del instance.properties.additional_properties['Network.AdditionalLogs.EnableUdpLogOptimization']
# pylint: disable=unused-argument
def create_af_ip_configuration(cmd, resource_group_name, azure_firewall_name, item_name,
public_ip_address, virtual_network_name=None, subnet='AzureFirewallSubnet',
management_item_name=None, management_public_ip_address=None,
management_virtual_network_name=None, management_subnet='AzureFirewallManagementSubnet'):
AzureFirewallIPConfiguration, SubResource = cmd.get_models('AzureFirewallIPConfiguration', 'SubResource')
client = network_client_factory(cmd.cli_ctx).azure_firewalls
af = client.get(resource_group_name, azure_firewall_name)
config = AzureFirewallIPConfiguration(
name=item_name,
public_ip_address=SubResource(id=public_ip_address) if public_ip_address else None,
subnet=SubResource(id=subnet) if subnet else None
)
_upsert(af, 'ip_configurations', config, 'name', warn=False)
if management_item_name is not None:
management_config = AzureFirewallIPConfiguration(
name=management_item_name,
public_ip_address=SubResource(id=management_public_ip_address) if management_public_ip_address else None,
subnet=SubResource(id=management_subnet) if management_subnet else None
)
af.management_ip_configuration = management_config
poller = client.begin_create_or_update(resource_group_name, azure_firewall_name, af)
return _get_property(poller.result().ip_configurations, item_name)
def create_af_management_ip_configuration(cmd, resource_group_name, azure_firewall_name, item_name,
public_ip_address, virtual_network_name, # pylint: disable=unused-argument
subnet='AzureFirewallManagementSubnet'):
AzureFirewallIPConfiguration, SubResource = cmd.get_models('AzureFirewallIPConfiguration', 'SubResource')
client = network_client_factory(cmd.cli_ctx).azure_firewalls
af = client.get(resource_group_name, azure_firewall_name)
config = AzureFirewallIPConfiguration(
name=item_name,
public_ip_address=SubResource(id=public_ip_address) if public_ip_address else None,
subnet=SubResource(id=subnet) if subnet else None
)
af.management_ip_configuration = config
poller = client.create_or_update(resource_group_name, azure_firewall_name, af)
return poller.result().management_ip_configuration
def update_af_management_ip_configuration(cmd, instance, public_ip_address=None, virtual_network_name=None,
# pylint: disable=unused-argument
subnet='AzureFirewallManagementSubnet'):
SubResource = cmd.get_models('SubResource')
if public_ip_address is not None:
instance.management_ip_configuration.public_ip_address = SubResource(id=public_ip_address)
if subnet is not None:
instance.management_ip_configuration.subnet = SubResource(id=subnet)
return instance
def set_af_management_ip_configuration(cmd, resource_group_name, azure_firewall_name, parameters):
client = network_client_factory(cmd.cli_ctx).azure_firewalls
poller = client.create_or_update(resource_group_name, azure_firewall_name, parameters)
return poller.result().management_ip_configuration
def show_af_management_ip_configuration(cmd, resource_group_name, azure_firewall_name):
client = network_client_factory(cmd.cli_ctx).azure_firewalls
af = client.get(resource_group_name, azure_firewall_name)
return af.management_ip_configuration
def delete_af_management_ip_configuration(cmd, resource_group_name, azure_firewall_name):
client = network_client_factory(cmd.cli_ctx).azure_firewalls
af = client.get(resource_group_name, azure_firewall_name)
af.management_ip_configuration = None
poller = client.create_or_update(resource_group_name, azure_firewall_name, af)
return poller.result().management_ip_configuration
def delete_af_ip_configuration(cmd, resource_group_name, resource_name, item_name,
no_wait=False): # pylint: disable=unused-argument
client = network_client_factory(cmd.cli_ctx).azure_firewalls
af = client.get(resource_group_name, resource_name)
keep_items = \
[x for x in af.ip_configurations if x.name.lower() != item_name.lower()]
af.ip_configurations = keep_items if keep_items else None
if not keep_items:
if af.management_ip_configuration is not None:
logger.warning('Management ip configuration cannot exist without regular ip config. Delete it as well.')
af.management_ip_configuration = None
if no_wait:
sdk_no_wait(no_wait, client.create_or_update, resource_group_name, resource_name, af)
else:
result = sdk_no_wait(no_wait, client.begin_create_or_update, resource_group_name, resource_name, af).result()
if next((x for x in getattr(result, 'ip_configurations') if x.name.lower() == item_name.lower()), None):
raise CLIError(f"Failed to delete '{item_name}' on '{resource_name}'")
def build_af_rule_list(item_param_name, collection_param_name):
import sys
def list_func(cmd, resource_group_name, firewall_name, collection_name):
client = network_client_factory(cmd.cli_ctx).azure_firewalls
af = client.get(resource_group_name, firewall_name)
return _find_item_at_path(af, f'{collection_param_name}.{collection_name}')
func_name = f'list_af_{item_param_name}s'
setattr(sys.modules[__name__], func_name, list_func)
return func_name
def build_af_rule_show(item_param_name, collection_param_name):
import sys
def show_func(cmd, resource_group_name, firewall_name, collection_name, item_name):
client = network_client_factory(cmd.cli_ctx).azure_firewalls
af = client.get(resource_group_name, firewall_name)
return _find_item_at_path(af, f'{collection_param_name}.{collection_name}.rules.{item_name}')
func_name = f'show_af_{item_param_name}'
setattr(sys.modules[__name__], func_name, show_func)
return func_name
def build_af_rule_delete(item_param_name, collection_param_name):
import sys
def delete_func(cmd, resource_group_name, firewall_name, collection_name, item_name):
client = network_client_factory(cmd.cli_ctx).azure_firewalls
af = client.get(resource_group_name, firewall_name)
collection = _find_item_at_path(af, f'{collection_param_name}.{collection_name}')
collection.rules = [rule for rule in collection.rules if rule.name != item_name]
client.begin_create_or_update(resource_group_name, firewall_name, af)
func_name = f'delete_af_{item_param_name}'
setattr(sys.modules[__name__], func_name, delete_func)
return func_name
def _upsert_af_rule(cmd, resource_group_name, firewall_name, collection_param_name, collection_class,
item_class, item_name, params, collection_params):
client = network_client_factory(cmd.cli_ctx).azure_firewalls
af = client.get(resource_group_name, firewall_name)
collection = getattr(af, collection_param_name, [])
collection_name = collection_params.get('name', '')
priority = collection_params.get('priority', None)
action = collection_params.get('action', None)
collection_match = next((x for x in collection if x.name.lower() == collection_name.lower()), None)
usage_error = CLIError("usage error: --collection-name EXISTING_NAME | --collection-name NEW_NAME --priority"
" INT --action ACTION")
if collection_match:
if any([priority, action['type']]):
logger.warning("Rule collection '%s' already exists.", collection_params['name'])
raise usage_error
else:
if not all([priority, action['type']]):
logger.warning("Rule collection '%s' does not exist and needs to be created.", collection_params['name'])
raise usage_error
# create new collection
logger.warning("Creating rule collection '%s'.", collection_params['name'])
collection_match = collection_class(**collection_params)
collection_match.rules = []
collection_match.rules.append(item_class(**params))
_upsert(af, collection_param_name, collection_match, 'name', warn=False)
af = client.begin_create_or_update(resource_group_name, firewall_name, af).result()
return _find_item_at_path(af, f'{collection_param_name}.{collection_name}.rules.{item_name}')
def create_af_network_rule(cmd, resource_group_name, azure_firewall_name, collection_name, item_name,
destination_ports, protocols, destination_fqdns=None, source_addresses=None,
destination_addresses=None, description=None, priority=None, action=None,
source_ip_groups=None, destination_ip_groups=None):
AzureFirewallNetworkRule, AzureFirewallNetworkRuleCollection = cmd.get_models(
'AzureFirewallNetworkRule', 'AzureFirewallNetworkRuleCollection')
params = {
'name': item_name,
'description': description,
'source_addresses': source_addresses,
'destination_addresses': destination_addresses,
'destination_ports': destination_ports,
'destination_fqdns': destination_fqdns,
'protocols': protocols,
'destination_ip_groups': destination_ip_groups,
'source_ip_groups': source_ip_groups
}
collection_params = {
'name': collection_name,
'priority': priority,
'action': {'type': action}
}
return _upsert_af_rule(cmd, resource_group_name, azure_firewall_name,
'network_rule_collections', AzureFirewallNetworkRuleCollection, AzureFirewallNetworkRule,
item_name, params, collection_params)
def create_af_nat_rule(cmd, resource_group_name, azure_firewall_name, collection_name, item_name,
destination_addresses, destination_ports, protocols, translated_port, source_addresses=None,
translated_address=None, translated_fqdn=None, description=None, priority=None, action=None,
source_ip_groups=None):
AzureFirewallNatRule, AzureFirewallNatRuleCollection = cmd.get_models(
'AzureFirewallNatRule', 'AzureFirewallNatRuleCollection')
params = {
'name': item_name,
'description': description,
'source_addresses': source_addresses,
'destination_addresses': destination_addresses,
'destination_ports': destination_ports,
'protocols': protocols,
'translated_address': translated_address,
'translated_port': translated_port,
'translated_fqdn': translated_fqdn,
'source_ip_groups': source_ip_groups
}
collection_params = {
'name': collection_name,
'priority': priority,
'action': {'type': action}
}
return _upsert_af_rule(cmd, resource_group_name, azure_firewall_name,
'nat_rule_collections', AzureFirewallNatRuleCollection, AzureFirewallNatRule,
item_name, params, collection_params)
def create_af_application_rule(cmd, resource_group_name, azure_firewall_name, collection_name, item_name,
protocols, description=None, source_addresses=None, target_fqdns=None,
fqdn_tags=None, priority=None, action=None, source_ip_groups=None):
AzureFirewallApplicationRule, AzureFirewallApplicationRuleCollection = cmd.get_models(
'AzureFirewallApplicationRule', 'AzureFirewallApplicationRuleCollection')
params = {
'name': item_name,
'description': description,
'source_addresses': source_addresses,
'protocols': protocols,
'target_fqdns': target_fqdns,
'fqdn_tags': fqdn_tags,
'source_ip_groups': source_ip_groups
}
collection_params = {
'name': collection_name,
'priority': priority,
'action': {'type': action}
}
return _upsert_af_rule(cmd, resource_group_name, azure_firewall_name,
'application_rule_collections', AzureFirewallApplicationRuleCollection,
AzureFirewallApplicationRule, item_name, params, collection_params)
@register_command(
"network firewall threat-intel-allowlist create",
)
class ThreatIntelAllowListCreate(_AzureFirewallUpdate):
"""Create an Azure Firewall Threat Intelligence Allow List.
:example: Create a threat intelligence allow list
az network firewall threat-intel-allowlist create -g MyResourceGroup -n MyFirewall --ip-addresses 10.0.0.0 10.0.0.1 --fqdns *.microsoft.com www.bing.com *google.com
"""
@classmethod
def _build_arguments_schema(cls, *args, **kwargs):
from azure.cli.core.aaz import AAZListArg, AAZStrArg
args_schema = super()._build_arguments_schema(*args, **kwargs)
args_schema.name._required = True
args_schema.name._id_part = None
args_schema.ip_addresses = AAZListArg(
options=['--ip-addresses'],
help='Space-separated list of IPv4 addresses.'
)
args_schema.ip_addresses.Element = AAZStrArg()
args_schema.fqdns = AAZListArg(
options=['--fqdns'],
help='Space-separated list of FQDNs'
)
args_schema.fqdns.Element = AAZStrArg()
args_schema.firewall_policy._registered = False
args_schema.threat_intel_mode._registered = False
args_schema.addresses._registered = False
args_schema.public_ip_count._registered = False
args_schema.additional_properties._registered = False
args_schema.virtual_hub._registered = False
args_schema.zones._registered = False
args_schema.tags._registered = False
return args_schema
def pre_instance_update(self, instance):
args = self.ctx.args
if has_value(args.ip_addresses):
if not has_value(instance.properties.additional_properties):
instance.properties.additional_properties = {}
instance.properties.additional_properties['ThreatIntel.Whitelist.IpAddresses'] = ', '.join(args.ip_addresses.to_serialized_data())
if has_value(args.fqdns):
if not has_value(instance.properties.additional_properties):
instance.properties.additional_properties = {}
instance.properties.additional_properties['ThreatIntel.Whitelist.FQDNs'] = ', '.join(args.fqdns.to_serialized_data())
def _output(self, *args, **kwargs):
output = super()._output(*args, **kwargs)
output.update({
**output.pop('additionalProperties')
})
return output
@register_command(
"network firewall threat-intel-allowlist update",
)
class ThreatIntelAllowListUpdate(_AzureFirewallUpdate):
"""Update Azure Firewall Threat Intelligence Allow List.
:example: Update a threat intelligence allow list
az network firewall threat-intel-allowlist update -g MyResourceGroup -n MyFirewall --ip-addresses
"""
@classmethod
def _build_arguments_schema(cls, *args, **kwargs):
from azure.cli.core.aaz import AAZListArg, AAZStrArg
args_schema = super()._build_arguments_schema(*args, **kwargs)
args_schema.name._required = True
args_schema.name._id_part = None
args_schema.ip_addresses = AAZListArg(
options=['--ip-addresses'],
help='Space-separated list of IPv4 addresses.'
)
args_schema.ip_addresses.Element = AAZStrArg()
args_schema.fqdns = AAZListArg(
options=['--fqdns'],
help='Space-separated list of FQDNs'
)
args_schema.fqdns.Element = AAZStrArg()
args_schema.firewall_policy._registered = False
args_schema.threat_intel_mode._registered = False
args_schema.addresses._registered = False
args_schema.public_ip_count._registered = False
args_schema.additional_properties._registered = False
args_schema.virtual_hub._registered = False
args_schema.zones._registered = False
args_schema.tags._registered = False
return args_schema
def pre_instance_update(self, instance):
args = self.ctx.args
if has_value(args.ip_addresses):
if not has_value(instance.properties.additional_properties):
instance.properties.additional_properties = {}
instance.properties.additional_properties['ThreatIntel.Whitelist.IpAddresses'] = ', '.join(
args.ip_addresses.to_serialized_data())
if has_value(args.fqdns):
if not has_value(instance.properties.additional_properties):
instance.properties.additional_properties = {}
instance.properties.additional_properties['ThreatIntel.Whitelist.FQDNs'] = ', '.join(
args.fqdns.to_serialized_data())
def _output(self, *args, **kwargs):
output = super()._output(*args, **kwargs)
output.update({
**output.pop('additionalProperties')
})
return output
@register_command(
"network firewall threat-intel-allowlist show",
)
class ThreatIntelAllowListShow(_AzureFirewallShow):
"""
Get the details of an Azure Firewall Threat Intelligence Allow List.
"""
@classmethod
def _build_arguments_schema(cls, *args, **kwargs):
args_schema = super()._build_arguments_schema(*args, **kwargs)
args_schema.name._required = True
args_schema.name._id_part = None
return args_schema
def _output(self, *args, **kwargs):
output = super()._output(*args, **kwargs)
return output['additionalProperties']
@register_command(
"network firewall threat-intel-allowlist delete",
)
class ThreatIntelAllowListDelete(_AzureFirewallUpdate):
"""
Delete an Azure Firewall Threat Intelligence Allow List.
"""
@classmethod
def _build_arguments_schema(cls, *args, **kwargs):
args_schema = super()._build_arguments_schema(*args, **kwargs)
args_schema.name._required = True
args_schema.name._id_part = None
args_schema.firewall_policy._registered = False
args_schema.threat_intel_mode._registered = False
args_schema.addresses._registered = False
args_schema.public_ip_count._registered = False
args_schema.additional_properties._registered = False
args_schema.virtual_hub._registered = False
args_schema.zones._registered = False
args_schema.tags._registered = False
return args_schema
def pre_instance_update(self, instance):
if has_value(instance.properties.additional_properties):
instance.properties.additional_properties._data.pop('ThreatIntel.Whitelist.IpAddresses', None)
instance.properties.additional_properties._data.pop('ThreatIntel.Whitelist.FQDNs', None)
def _output(self, *args, **kwargs):
output = super()._output(*args, **kwargs)
output.update({
**output.pop('additionalProperties')
})
return output
# endregion
# region AzureFirewallPolicies
# pylint: disable=too-many-locals
class AzureFirewallPoliciesCreate(_AzureFirewallPoliciesCreate):
@classmethod
def _build_arguments_schema(cls, *args, **kwargs):
from azure.cli.core.aaz import AAZListArg, AAZResourceIdArg, AAZResourceIdArgFormat
args_schema = super()._build_arguments_schema(*args, **kwargs)
args_schema.identity = AAZListArg(
options=['--identity'],
help="Space-separated list of ManagedIdentity Resource IDs."
)
args_schema.identity.Element = AAZResourceIdArg(
fmt=AAZResourceIdArgFormat(
template="/subscriptions/{subscription}/resourceGroups/{resource_group}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{}",
)
)
args_schema.base_policy._fmt = AAZResourceIdArgFormat(
template="/subscriptions/{subscription}/resourceGroups/{resource_group}/providers/Microsoft.Network"
"/firewallPolicies/{}",
)
args_schema.user_assigned_identities._registered = False
return args_schema
def pre_operations(self):
args = self.ctx.args
if has_value(args.identity):
identities = [id.to_serialized_data() for id in args.identity]
args.identity_type = "UserAssigned"
args.user_assigned_identities = {id: {} for id in identities}
if has_value(args.dns_servers):
if not has_value(args.enable_dns_proxy):
args.enable_dns_proxy = False
class AzureFirewallPoliciesUpdate(_AzureFirewallPoliciesUpdate):
@classmethod
def _build_arguments_schema(cls, *args, **kwargs):
from azure.cli.core.aaz import AAZListArg, AAZResourceIdArg, AAZResourceIdArgFormat, AAZStrArg
args_schema = super()._build_arguments_schema(*args, **kwargs)
args_schema.identity = AAZListArg(
options=['--identity'],
help="Space-separated list of ManagedIdentity Resource IDs."
)
args_schema.identity.Element = AAZResourceIdArg(
fmt=AAZResourceIdArgFormat(
template="/subscriptions/{subscription}/resourceGroups/{resource_group}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{}",
)
)
args_schema.identity_type = AAZStrArg(
options=['--identity-type'],
help="The type of identity used for the firewall policy.Set None to remove the identity."
)
args_schema.user_assigned_identities._registered = False
args_schema.configuration._registered = False
return args_schema
def pre_operations(self):
args = self.ctx.args
if has_value(args.identity):
identities = [id.to_serialized_data() for id in args.identity]
args.identity_type = "UserAssigned"
args.user_assigned_identities = {id: {} for id in identities}
elif(has_value(args.identity_type == 'None')):
args.identity_type = "None"
args.user_assigned_identities = None
elif args.sku == 'Basic':
args.identity_type = "None"
args.user_assigned_identities = None
class AzureFirewallPolicyIntrusionDetectionAdd(_AzureFirewallPoliciesUpdate):
"""
Add override for intrusion signature or a bypass rule or private ranges list for intrusion detection
"""
@classmethod
def _build_arguments_schema(cls, *args, **kwargs):
from azure.cli.core.aaz import AAZStrArg, AAZListArg, AAZArgEnum, AAZResourceIdArg, AAZResourceIdArgFormat
args_schema = super()._build_arguments_schema(*args, **kwargs)
args_schema.name._options = ['--policy-name']
args_schema.signature_id = AAZStrArg(
options=['--signature-id'],
help="Signature id for override"
)
args_schema.signature_mode = AAZStrArg(
options=['--mode'],
help="The override signature state"
)
args_schema.signature_mode.enum = AAZArgEnum({'Off': 'off', 'Alert': 'Alert', 'Deny': 'Deny'})
args_schema.bypass_rule_name = AAZStrArg(
options=['--rule-name'],
help="Name of the bypass traffic rule"
)
args_schema.bypass_rule_description = AAZStrArg(
options=['--rule-description'],
help="Description of the bypass traffic rule"
)
args_schema.bypass_rule_protocol = AAZStrArg(
options=['--rule-protocol'],
help="The bypass traffic rule protocol"
)
args_schema.bypass_rule_protocol.enum = AAZArgEnum({'TCP': 'TCP', 'UDP': 'UDP', 'ICMP': 'ICMP', 'Any': 'Any'})
args_schema.bypass_rule_source_addresses = AAZListArg(
options=['--rule-src-addresses'],
help="Space-separated list of source IP addresses or ranges for this rule"
)
args_schema.bypass_rule_source_addresses.Element = AAZStrArg()
args_schema.bypass_rule_destination_addresses = AAZListArg(
options=['--rule-dest-addresses'],
help="Space-separated list of destination IP addresses or ranges for bypass traffic rule"
)
args_schema.bypass_rule_destination_addresses.Element = AAZStrArg()
args_schema.bypass_rule_destination_ports = AAZListArg(
options=['--rule-dest-ports'],
help="Space-separated list of destination ports or ranges for bypass traffic rule"
)
args_schema.bypass_rule_destination_ports.Element = AAZStrArg()
args_schema.bypass_rule_source_ip_groups = AAZListArg(
options=['--rule-src-ip-groups'],
help="Space-separated list of source IpGroups for bypass traffic rule"
)
args_schema.bypass_rule_source_ip_groups.Element = AAZStrArg()
args_schema.bypass_rule_destination_ip_groups = AAZListArg(
options=['--rule-dest-ip-groups'],
help="Space-separated list of destination IpGroups for bypass traffic rule"
)
args_schema.bypass_rule_destination_ip_groups.Element = AAZResourceIdArg(
fmt=AAZResourceIdArgFormat(
template="/subscriptions/{subscription}/resourceGroups/{resource_group}/providers/Microsoft.Network/ipGroups/{}"
)
)
args_schema.user_assigned_identities._registered = False
return args_schema
def pre_instance_update(self, instance):
from azure.cli.core.azclierror import RequiredArgumentMissingError, InvalidArgumentValueError
args = self.ctx.args
if not has_value(instance.properties.intrusion_detection):
raise RequiredArgumentMissingError(
'Intrusion detection mode is not set. Setting it by update command first')
if has_value(args.signature_id) and has_value(args.signature_mode):
signature_override = {
'id': args.signature_id,
'mode': args.signature_mode
}