feat: Add new gcloud commands, API clients, and third-party libraries across various services.

This commit is contained in:
2026-01-01 20:26:35 +01:00
parent 5e23cbece0
commit a19e592eb7
25221 changed files with 8324611 additions and 0 deletions

View File

@@ -0,0 +1,25 @@
# -*- coding: utf-8 -*- #
# Copyright 2017 Google LLC. All Rights Reserved.
#
# Licensed 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.
"""Commands for reading and manipulating security policies rules."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
class SecurityPolicyRules(base.Group):
"""Read and manipulate Compute Engine security policies rules."""

View File

@@ -0,0 +1,408 @@
# -*- coding: utf-8 -*- #
# Copyright 2022 Google LLC. All Rights Reserved.
#
# Licensed 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.
"""Command for adding exclusions for preconfigured WAF rule evaluation to security policy rules."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from apitools.base.py import encoding
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.api_lib.compute.security_policies import client
from googlecloudsdk.calliope import base
from googlecloudsdk.calliope import exceptions
from googlecloudsdk.command_lib.compute import scope as compute_scope
from googlecloudsdk.command_lib.compute.security_policies import flags as security_policy_flags
from googlecloudsdk.command_lib.compute.security_policies.rules import flags
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
class AddPreconfigWafExclusionHelper(object):
r"""Add an exclusion configuration for preconfigured WAF evaluation into a security policy rule.
*{command}* is used to add an exclusion configuration for preconfigured WAF
evaluation into a security policy rule.
Note that request field exclusions are associated with a target, which can be
a single rule set, or a rule set plus a list of rule IDs under the rule set.
## EXAMPLES
To add specific request field exclusions that are associated with the target
of 'sqli-stable': ['owasp-crs-v030001-id942110-sqli',
'owasp-crs-v030001-id942120-sqli'], run:
$ {command} 1000 \
--security-policy=my-policy \
--target-rule-set=sqli-stable \
--target-rule-ids=owasp-crs-v030001-id942110-sqli,owasp-crs-v030001-id942120-sqli
\
--request-header-to-exclude=op=EQUALS,val=abc \
--request-header-to-exclude=op=STARTS_WITH,val=xyz \
--request-uri-to-exclude=op=EQUALS_ANY
To add specific request field exclusions that are associated with the target
of 'sqli-stable': [], run:
$ {command} 1000 \
--security-policy=my-policy \
--target-rule-set=sqli-stable \
--request-cookie-to-exclude=op=EQUALS_ANY
"""
@classmethod
def Args(cls, parser):
"""Generates the flagset for an AddPreconfigWafExclusion command."""
cls.NAME_ARG = flags.PriorityArgument(
'add the exclusion configuration for preconfigured WAF evaluation'
)
cls.NAME_ARG.AddArgument(
parser,
operation_type=(
'add the exclusion configuration for preconfigured WAF evaluation'
),
cust_metavar='PRIORITY',
)
flags.AddRegionFlag(
parser,
'add the exclusion configuration for preconfigured WAF evaluation')
cls.SECURITY_POLICY_ARG = (
security_policy_flags.SecurityPolicyMultiScopeArgumentForRules())
cls.SECURITY_POLICY_ARG.AddArgument(parser)
flags.AddTargetRuleSet(parser=parser, is_add=True)
flags.AddTargetRuleIds(parser=parser, is_add=True)
flags.AddRequestHeader(parser=parser, is_add=True)
flags.AddRequestCookie(parser=parser, is_add=True)
flags.AddRequestQueryParam(parser=parser, is_add=True)
flags.AddRequestUri(parser=parser, is_add=True)
@classmethod
def _IsIdenticalTarget(cls,
existing_exclusion,
target_rule_set,
target_rule_ids=None):
return target_rule_set == existing_exclusion.targetRuleSet and set(
target_rule_ids) == set(existing_exclusion.targetRuleIds)
@classmethod
def _ConvertRequestFieldToAdd(cls, compute_client, request_field_to_add):
"""Converts RequestFieldToAdd."""
request_field = (
compute_client.messages
.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams())
op = request_field_to_add.get('op') or ''
if op:
request_field.op = (
compute_client.messages
.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams
.OpValueValuesEnum(op))
val = request_field_to_add.get('val') or ''
if val:
request_field.val = val
return request_field
@classmethod
def _AddRequestField(cls, compute_client, existing_request_fields,
request_field_to_add):
"""Adds Request Field."""
new_request_field = cls._ConvertRequestFieldToAdd(compute_client,
request_field_to_add)
for existing_request_field in existing_request_fields:
if existing_request_field == new_request_field:
return
existing_request_fields.append(new_request_field)
@classmethod
def _UpdateExclusion(cls,
compute_client,
existing_exclusion,
request_headers=None,
request_cookies=None,
request_query_params=None,
request_uris=None):
"""Updates Exclusion."""
for request_header in request_headers or []:
cls._AddRequestField(compute_client,
existing_exclusion.requestHeadersToExclude,
request_header)
for request_cookie in request_cookies or []:
cls._AddRequestField(compute_client,
existing_exclusion.requestCookiesToExclude,
request_cookie)
for request_query_param in request_query_params or []:
cls._AddRequestField(compute_client,
existing_exclusion.requestQueryParamsToExclude,
request_query_param)
for request_uri in request_uris or []:
cls._AddRequestField(compute_client,
existing_exclusion.requestUrisToExclude, request_uri)
@classmethod
def _CreateExclusion(cls,
compute_client,
target_rule_set,
target_rule_ids=None,
request_headers=None,
request_cookies=None,
request_query_params=None,
request_uris=None):
"""Creates Exclusion."""
new_exclusion = (
compute_client.messages
.SecurityPolicyRulePreconfiguredWafConfigExclusion())
new_exclusion.targetRuleSet = target_rule_set
for target_rule_id in target_rule_ids or []:
new_exclusion.targetRuleIds.append(target_rule_id)
cls._UpdateExclusion(compute_client, new_exclusion, request_headers,
request_cookies, request_query_params, request_uris)
return new_exclusion
@classmethod
def _UpdatePreconfigWafConfig(cls, compute_client, existing_rule, args):
"""Updates Preconfig WafConfig."""
if existing_rule.preconfiguredWafConfig:
new_preconfig_waf_config = encoding.CopyProtoMessage(
existing_rule.preconfiguredWafConfig)
else:
new_preconfig_waf_config = (
compute_client.messages.SecurityPolicyRulePreconfiguredWafConfig())
for exclusion in new_preconfig_waf_config.exclusions:
if cls._IsIdenticalTarget(exclusion, args.target_rule_set,
args.target_rule_ids or []):
cls._UpdateExclusion(compute_client, exclusion,
args.request_header_to_exclude,
args.request_cookie_to_exclude,
args.request_query_param_to_exclude,
args.request_uri_to_exclude)
return new_preconfig_waf_config
new_exclusion = cls._CreateExclusion(compute_client, args.target_rule_set,
args.target_rule_ids,
args.request_header_to_exclude,
args.request_cookie_to_exclude,
args.request_query_param_to_exclude,
args.request_uri_to_exclude)
new_preconfig_waf_config.exclusions.append(new_exclusion)
return new_preconfig_waf_config
@classmethod
def Run(cls, release_track, args):
"""Validates arguments and patches a security policy rule."""
if not (args.IsSpecified('request_header_to_exclude') or
args.IsSpecified('request_cookie_to_exclude') or
args.IsSpecified('request_query_param_to_exclude') or
args.IsSpecified('request_uri_to_exclude')):
request_field_names = [
'--request-header-to-exclude', '--request-cookie-to-exclude',
'--request-query-param-to-exclude', '--request-uri-to-exclude'
]
raise exceptions.MinimumArgumentException(
request_field_names, 'At least one request field must be specified.')
for request_fields in [
args.request_header_to_exclude or [], args.request_cookie_to_exclude or
[], args.request_query_param_to_exclude or [],
args.request_uri_to_exclude or []
]:
for request_field in request_fields:
op = request_field.get('op') or ''
if not op or op not in [
'EQUALS', 'STARTS_WITH', 'ENDS_WITH', 'CONTAINS', 'EQUALS_ANY'
]:
raise exceptions.InvalidArgumentException(
'op',
'A request field operator must be one of [EQUALS, STARTS_WITH, '
'ENDS_WITH, CONTAINS, EQUALS_ANY].')
holder = base_classes.ComputeApiHolder(release_track)
compute_client = holder.client
ref = None
if args.security_policy:
security_policy_ref = cls.SECURITY_POLICY_ARG.ResolveAsResource(
args,
holder.resources,
default_scope=compute_scope.ScopeEnum.GLOBAL)
if getattr(security_policy_ref, 'region', None) is not None:
ref = holder.resources.Parse(
args.name,
collection='compute.regionSecurityPolicyRules',
params={
'project': properties.VALUES.core.project.GetOrFail,
'region': security_policy_ref.region,
'securityPolicy': args.security_policy,
})
else:
ref = holder.resources.Parse(
args.name,
collection='compute.securityPolicyRules',
params={
'project': properties.VALUES.core.project.GetOrFail,
'securityPolicy': args.security_policy,
},
)
else:
try:
ref = holder.resources.Parse(
args.name,
collection='compute.regionSecurityPolicyRules',
params={
'project': properties.VALUES.core.project.GetOrFail,
'region': getattr(args, 'region', None),
},
)
except (
resources.RequiredFieldOmittedException,
resources.WrongResourceCollectionException,
):
ref = holder.resources.Parse(
args.name,
collection='compute.securityPolicyRules',
params={
'project': properties.VALUES.core.project.GetOrFail,
},
)
security_policy_rule = client.SecurityPolicyRule(
ref, compute_client=compute_client)
existing_rule = security_policy_rule.Describe()[0]
new_preconfig_waf_config = cls._UpdatePreconfigWafConfig(
compute_client, existing_rule, args)
return security_policy_rule.Patch(
preconfig_waf_config=new_preconfig_waf_config)
@base.ReleaseTracks(base.ReleaseTrack.GA)
class AddPreconfigWafExclusionGA(base.UpdateCommand):
r"""Add an exclusion configuration for preconfigured WAF evaluation into a security policy rule.
*{command}* is used to add an exclusion configuration for preconfigured WAF
evaluation into a security policy rule.
Note that request field exclusions are associated with a target, which can be
a single rule set, or a rule set plus a list of rule IDs under the rule set.
## EXAMPLES
To add specific request field exclusions that are associated with the target
of 'sqli-stable': ['owasp-crs-v030001-id942110-sqli',
'owasp-crs-v030001-id942120-sqli'], run:
$ {command} 1000 \
--security-policy=my-policy \
--target-rule-set=sqli-stable \
--target-rule-ids=owasp-crs-v030001-id942110-sqli,owasp-crs-v030001-id942120-sqli
\
--request-header-to-exclude=op=EQUALS,val=abc \
--request-header-to-exclude=op=STARTS_WITH,val=xyz \
--request-uri-to-exclude=op=EQUALS_ANY
To add specific request field exclusions that are associated with the target
of 'sqli-stable': [], run:
$ {command} 1000 \
--security-policy=my-policy \
--target-rule-set=sqli-stable \
--request-cookie-to-exclude=op=EQUALS_ANY
"""
NAME_ARG = None
@classmethod
def Args(cls, parser):
AddPreconfigWafExclusionHelper.Args(
parser,
)
def Run(self, args):
return AddPreconfigWafExclusionHelper.Run(
self.ReleaseTrack(),
args,
)
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class AddPreconfigWafExclusionBeta(AddPreconfigWafExclusionGA):
r"""Add an exclusion configuration for preconfigured WAF evaluation into a security policy rule.
*{command}* is used to add an exclusion configuration for preconfigured WAF
evaluation into a security policy rule.
Note that request field exclusions are associated with a target, which can be
a single rule set, or a rule set plus a list of rule IDs under the rule set.
## EXAMPLES
To add specific request field exclusions that are associated with the target
of 'sqli-stable': ['owasp-crs-v030001-id942110-sqli',
'owasp-crs-v030001-id942120-sqli'], run:
$ {command} 1000 \
--security-policy=my-policy \
--target-rule-set=sqli-stable \
--target-rule-ids=owasp-crs-v030001-id942110-sqli,owasp-crs-v030001-id942120-sqli
\
--request-header-to-exclude=op=EQUALS,val=abc \
--request-header-to-exclude=op=STARTS_WITH,val=xyz \
--request-uri-to-exclude=op=EQUALS_ANY
To add specific request field exclusions that are associated with the target
of 'sqli-stable': [], run:
$ {command} 1000 \
--security-policy=my-policy \
--target-rule-set=sqli-stable \
--request-cookie-to-exclude=op=EQUALS_ANY
"""
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class AddPreconfigWafExclusionAlpha(AddPreconfigWafExclusionBeta):
r"""Add an exclusion configuration for preconfigured WAF evaluation into a security policy rule.
*{command}* is used to add an exclusion configuration for preconfigured WAF
evaluation into a security policy rule.
Note that request field exclusions are associated with a target, which can be
a single rule set, or a rule set plus a list of rule IDs under the rule set.
## EXAMPLES
To add specific request field exclusions that are associated with the target
of 'sqli-stable': ['owasp-crs-v030001-id942110-sqli',
'owasp-crs-v030001-id942120-sqli'], run:
$ {command} 1000 \
--security-policy=my-policy \
--target-rule-set=sqli-stable \
--target-rule-ids=owasp-crs-v030001-id942110-sqli,owasp-crs-v030001-id942120-sqli
\
--request-header-to-exclude=op=EQUALS,val=abc \
--request-header-to-exclude=op=STARTS_WITH,val=xyz \
--request-uri-to-exclude=op=EQUALS_ANY
To add specific request field exclusions that are associated with the target
of 'sqli-stable': [], run:
$ {command} 1000 \
--security-policy=my-policy \
--target-rule-set=sqli-stable \
--request-cookie-to-exclude=op=EQUALS_ANY
"""

View File

@@ -0,0 +1,284 @@
# -*- coding: utf-8 -*- #
# Copyright 2017 Google LLC. All Rights Reserved.
#
# Licensed 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.
"""Command for creating security policies rules."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.api_lib.compute.security_policies import client
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute import scope as compute_scope
from googlecloudsdk.command_lib.compute.security_policies import flags as security_policies_flags
from googlecloudsdk.command_lib.compute.security_policies import security_policies_utils
from googlecloudsdk.command_lib.compute.security_policies.rules import flags
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
class CreateHelper(object):
r"""Create a Compute Engine security policy rule.
*{command}* is used to create security policy rules.
## EXAMPLES
To create a rule at priority 1000 to block the IP range
1.2.3.0/24, run:
$ {command} 1000 \
--action=deny-403 \
--security-policy=my-policy \
--description="block 1.2.3.0/24" \
--src-ip-ranges=1.2.3.0/24
"""
@classmethod
def Args(
cls,
parser,
support_fairshare=False,
support_rpc_status=False,
):
"""Generates the flagset for a Create command."""
cls.NAME_ARG = (flags.PriorityArgument('add'))
cls.NAME_ARG.AddArgument(
parser, operation_type='add', cust_metavar='PRIORITY')
flags.AddRegionFlag(parser, 'add')
cls.SECURITY_POLICY_ARG = (
security_policies_flags.SecurityPolicyMultiScopeArgumentForRules())
cls.SECURITY_POLICY_ARG.AddArgument(parser)
flags.AddMatcherAndNetworkMatcher(parser)
flags.AddAction(
parser,
support_fairshare=support_fairshare)
flags.AddDescription(parser)
flags.AddPreview(parser)
flags.AddRedirectOptions(parser)
flags.AddRateLimitOptions(
parser,
support_rpc_status=support_rpc_status,
)
flags.AddRequestHeadersToAdd(parser)
flags.AddRecaptchaOptions(parser)
parser.display_info.AddCacheUpdater(
security_policies_flags.SecurityPoliciesCompleter)
@classmethod
def Run(
cls,
release_track,
args,
support_rpc_status,
):
"""Validates arguments and creates a security policy rule."""
holder = base_classes.ComputeApiHolder(release_track)
if args.security_policy:
security_policy_ref = cls.SECURITY_POLICY_ARG.ResolveAsResource(
args,
holder.resources,
default_scope=compute_scope.ScopeEnum.GLOBAL)
if getattr(security_policy_ref, 'region', None) is not None:
ref = holder.resources.Parse(
args.name,
collection='compute.regionSecurityPolicyRules',
params={
'project': properties.VALUES.core.project.GetOrFail,
'region': security_policy_ref.region,
'securityPolicy': args.security_policy,
})
else:
ref = holder.resources.Parse(
args.name,
collection='compute.securityPolicyRules',
params={
'project': properties.VALUES.core.project.GetOrFail,
'securityPolicy': args.security_policy,
},
)
else:
try:
ref = holder.resources.Parse(
args.name,
collection='compute.regionSecurityPolicyRules',
params={
'project': properties.VALUES.core.project.GetOrFail,
'region': getattr(args, 'region', None),
},
)
except (
resources.RequiredFieldOmittedException,
resources.WrongResourceCollectionException,
):
ref = holder.resources.Parse(
args.name,
collection='compute.securityPolicyRules',
params={
'project': properties.VALUES.core.project.GetOrFail,
},
)
security_policy_rule = client.SecurityPolicyRule(
ref, compute_client=holder.client)
redirect_options = security_policies_utils.CreateRedirectOptions(
holder.client, args
)
rate_limit_options = security_policies_utils.CreateRateLimitOptions(
holder.client,
args,
support_rpc_status,
)
request_headers_to_add = args.request_headers_to_add
expression_options = security_policies_utils.CreateExpressionOptions(
holder.client, args
)
network_matcher = security_policies_utils.CreateNetworkMatcher(
holder.client, args
)[0]
return security_policy_rule.Create(
src_ip_ranges=args.src_ip_ranges,
expression=args.expression,
expression_options=expression_options,
network_matcher=network_matcher,
action=args.action,
description=args.description,
preview=args.preview,
redirect_options=redirect_options,
rate_limit_options=rate_limit_options,
request_headers_to_add=request_headers_to_add,
)
@base.UniverseCompatible
@base.ReleaseTracks(base.ReleaseTrack.GA)
class CreateGA(base.CreateCommand):
r"""Create a Compute Engine security policy rule.
*{command}* is used to create security policy rules.
## EXAMPLES
To create a rule at priority 1000 to block the IP range
1.2.3.0/24, run:
$ {command} 1000 \
--action=deny-403 \
--security-policy=my-policy \
--description="block 1.2.3.0/24" \
--src-ip-ranges=1.2.3.0/24
"""
SECURITY_POLICY_ARG = None
NAME_ARG = None
_support_rpc_status = False
@classmethod
def Args(cls, parser):
CreateHelper.Args(
parser,
support_rpc_status=cls._support_rpc_status,
)
def Run(self, args):
return CreateHelper.Run(
self.ReleaseTrack(),
args,
support_rpc_status=self._support_rpc_status,
)
@base.UniverseCompatible
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class CreateBeta(base.CreateCommand):
r"""Create a Compute Engine security policy rule.
*{command}* is used to create security policy rules.
## EXAMPLES
To create a rule at priority 1000 to block the IP range
1.2.3.0/24, run:
$ {command} 1000 \
--action=deny-403 \
--security-policy=my-policy \
--description="block 1.2.3.0/24" \
--src-ip-ranges=1.2.3.0/24
"""
SECURITY_POLICY_ARG = None
_support_rpc_status = False
@classmethod
def Args(cls, parser):
CreateHelper.Args(
parser,
support_fairshare=True,
support_rpc_status=cls._support_rpc_status,
)
def Run(self, args):
return CreateHelper.Run(
self.ReleaseTrack(),
args,
support_rpc_status=self._support_rpc_status,
)
@base.UniverseCompatible
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class CreateAlpha(base.CreateCommand):
r"""Create a Compute Engine security policy rule.
*{command}* is used to create security policy rules.
## EXAMPLES
To create a rule at priority 1000 to block the IP range
1.2.3.0/24, run:
$ {command} 1000 \
--action=deny-403 \
--security-policy=my-policy \
--description="block 1.2.3.0/24" \
--src-ip-ranges=1.2.3.0/24
"""
SECURITY_POLICY_ARG = None
_support_rpc_status = True
@classmethod
def Args(cls, parser):
CreateHelper.Args(
parser,
support_fairshare=True,
support_rpc_status=cls._support_rpc_status,
)
def Run(self, args):
return CreateHelper.Run(
self.ReleaseTrack(),
args,
support_rpc_status=self._support_rpc_status,
)

View File

@@ -0,0 +1,178 @@
# -*- coding: utf-8 -*- #
# Copyright 2017 Google LLC. All Rights Reserved.
#
# Licensed 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.
"""Command for deleting security policies rules."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.api_lib.compute import utils
from googlecloudsdk.api_lib.compute.security_policies import client
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute import scope as compute_scope
from googlecloudsdk.command_lib.compute.security_policies import flags as security_policies_flags
from googlecloudsdk.command_lib.compute.security_policies.rules import flags
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
class DeleteHelper(object):
r"""Delete Compute Engine security policy rules.
*{command}* is used to delete security policy rules.
## EXAMPLES
To delete the rule at priority 1000, run:
$ {command} 1000 \
--security-policy=my-policy
"""
SECURITY_POLICY_ARG = None
NAME_ARG = None
@classmethod
def Args(cls, parser):
"""Generates the flagset for a Delete command."""
cls.NAME_ARG = (flags.PriorityArgument('delete', is_plural=True))
cls.NAME_ARG.AddArgument(
parser, operation_type='delete', cust_metavar='PRIORITY')
flags.AddRegionFlag(parser, 'delete')
cls.SECURITY_POLICY_ARG = (
security_policies_flags.SecurityPolicyMultiScopeArgumentForRules()
)
cls.SECURITY_POLICY_ARG.AddArgument(parser)
parser.display_info.AddCacheUpdater(
security_policies_flags.SecurityPoliciesCompleter
)
@classmethod
def Run(cls, release_track, args):
"""Validates arguments and deletes security policy rule(s)."""
holder = base_classes.ComputeApiHolder(release_track)
refs = []
if args.security_policy:
security_policy_ref = cls.SECURITY_POLICY_ARG.ResolveAsResource(
args,
holder.resources,
default_scope=compute_scope.ScopeEnum.GLOBAL)
if getattr(security_policy_ref, 'region', None) is not None:
for name in args.names:
refs.append(holder.resources.Parse(
name,
collection='compute.regionSecurityPolicyRules',
params={
'project': properties.VALUES.core.project.GetOrFail,
'region': security_policy_ref.region,
'securityPolicy': args.security_policy,
}))
else:
for name in args.names:
refs.append(holder.resources.Parse(
name,
collection='compute.securityPolicyRules',
params={
'project': properties.VALUES.core.project.GetOrFail,
'securityPolicy': args.security_policy,
},
))
else:
for name in args.names:
try:
refs.append(holder.resources.Parse(
name,
collection='compute.regionSecurityPolicyRules',
params={
'project': properties.VALUES.core.project.GetOrFail,
'region': getattr(args, 'region', None),
},
))
except (
resources.RequiredFieldOmittedException,
resources.WrongResourceCollectionException,
):
refs.append(holder.resources.Parse(
name,
collection='compute.securityPolicyRules',
params={
'project': properties.VALUES.core.project.GetOrFail,
},
))
utils.PromptForDeletion(refs)
requests = []
for ref in refs:
security_policy_rule = client.SecurityPolicyRule(
ref, compute_client=holder.client)
requests.extend(security_policy_rule.Delete(only_generate_request=True))
return holder.client.MakeRequests(requests)
@base.ReleaseTracks(base.ReleaseTrack.GA)
class DeleteGA(base.DeleteCommand):
r"""Delete Compute Engine security policy rules.
*{command}* is used to delete security policy rules.
## EXAMPLES
To delete the rule at priority 1000, run:
$ {command} 1000 \
--security-policy=my-policy
"""
SECURITY_POLICY_ARG = None
@classmethod
def Args(cls, parser):
DeleteHelper.Args(parser)
def Run(self, args):
return DeleteHelper.Run(self.ReleaseTrack(), args)
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class DeleteBeta(DeleteGA):
r"""Delete Compute Engine security policy rules.
*{command}* is used to delete security policy rules.
## EXAMPLES
To delete the rule at priority 1000, run:
$ {command} 1000 \
--security-policy=my-policy
"""
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class DeleteAlpha(DeleteBeta):
r"""Delete Compute Engine security policy rules.
*{command}* is used to delete security policy rules.
## EXAMPLES
To delete the rule at priority 1000, run:
$ {command} 1000 \
--security-policy=my-policy
"""

View File

@@ -0,0 +1,166 @@
# -*- coding: utf-8 -*- #
# Copyright 2017 Google LLC. All Rights Reserved.
#
# Licensed 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.
"""Command for describing security policies rules."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.api_lib.compute.security_policies import client
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute import scope as compute_scope
from googlecloudsdk.command_lib.compute.security_policies import flags as security_policy_flags
from googlecloudsdk.command_lib.compute.security_policies.rules import flags
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
class DescribeHelper(object):
r"""Describe a Compute Engine security policy rule.
*{command}* displays all data associated with a security policy rule.
## EXAMPLES
To describe the rule at priority 1000, run:
$ {command} 1000 \
--security-policy=my-policy
"""
SECURITY_POLICY_ARG = None
NAME_ARG = None
@classmethod
def Args(cls, parser):
"""Generates the flagset for a Describe command."""
cls.NAME_ARG = (flags.PriorityArgument('describe'))
cls.NAME_ARG.AddArgument(
parser, operation_type='describe', cust_metavar='PRIORITY')
flags.AddRegionFlag(parser, 'describe')
cls.SECURITY_POLICY_ARG = (
security_policy_flags.SecurityPolicyMultiScopeArgumentForRules()
)
cls.SECURITY_POLICY_ARG.AddArgument(parser)
@classmethod
def Run(cls, release_track, args):
"""Validates arguments and describes a security policy rule."""
holder = base_classes.ComputeApiHolder(release_track)
if args.security_policy:
security_policy_ref = cls.SECURITY_POLICY_ARG.ResolveAsResource(
args,
holder.resources,
default_scope=compute_scope.ScopeEnum.GLOBAL)
if getattr(security_policy_ref, 'region', None) is not None:
ref = holder.resources.Parse(
args.name,
collection='compute.regionSecurityPolicyRules',
params={
'project': properties.VALUES.core.project.GetOrFail,
'region': security_policy_ref.region,
'securityPolicy': args.security_policy,
})
else:
ref = holder.resources.Parse(
args.name,
collection='compute.securityPolicyRules',
params={
'project': properties.VALUES.core.project.GetOrFail,
'securityPolicy': args.security_policy,
},
)
else:
try:
ref = holder.resources.Parse(
args.name,
collection='compute.regionSecurityPolicyRules',
params={
'project': properties.VALUES.core.project.GetOrFail,
'region': getattr(args, 'region', None),
},
)
except (
resources.RequiredFieldOmittedException,
resources.WrongResourceCollectionException,
):
ref = holder.resources.Parse(
args.name,
collection='compute.securityPolicyRules',
params={
'project': properties.VALUES.core.project.GetOrFail,
},
)
security_policy_rule = client.SecurityPolicyRule(
ref, compute_client=holder.client)
return security_policy_rule.Describe()
@base.ReleaseTracks(base.ReleaseTrack.GA)
class DescribeGA(base.DescribeCommand):
r"""Describe a Compute Engine security policy rule.
*{command}* displays all data associated with a security policy rule.
## EXAMPLES
To describe the rule at priority 1000, run:
$ {command} 1000 \
--security-policy=my-policy
"""
SECURITY_POLICY_ARG = None
@classmethod
def Args(cls, parser):
DescribeHelper.Args(parser)
def Run(self, args):
return DescribeHelper.Run(self.ReleaseTrack(), args)
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class DescribeBeta(DescribeGA):
r"""Describe a Compute Engine security policy rule.
*{command}* displays all data associated with a security policy rule.
## EXAMPLES
To describe the rule at priority 1000, run:
$ {command} 1000 \
--security-policy=my-policy
"""
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class DescribeAlpha(DescribeBeta):
r"""Describe a Compute Engine security policy rule.
*{command}* displays all data associated with a security policy rule.
## EXAMPLES
To describe the rule at priority 1000, run:
$ {command} 1000 \
--security-policy=my-policy
"""

View File

@@ -0,0 +1,491 @@
# -*- coding: utf-8 -*- #
# Copyright 2022 Google LLC. All Rights Reserved.
#
# Licensed 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.
"""Command for removing exclusions for preconfigured WAF rule evaluation from security policy rules."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.api_lib.compute.security_policies import client
from googlecloudsdk.calliope import base
from googlecloudsdk.calliope import exceptions
from googlecloudsdk.command_lib.compute import scope as compute_scope
from googlecloudsdk.command_lib.compute.security_policies import flags as security_policy_flags
from googlecloudsdk.command_lib.compute.security_policies.rules import flags
from googlecloudsdk.core import properties
class RemovePreconfigWafExclusionHelper(object):
r"""Remove an exclusion configuration for preconfigured WAF evaluation from a security policy rule.
*{command}* is used to remove an exclusion configuration for preconfigured WAF
evaluation from a security policy rule.
Note that request field exclusions are associated with a target, which can be
a single rule set, or a rule set plus a list of rule IDs under the rule set.
It is possible to remove request field exclusions at 3 levels:
- Remove specific request field exclusions that are associated with a matching
target.
- Remove all the request field exclusions that are associated with a matching
target.
- Remove all the request field exclusions that are configured under the
security policy rule, regardless of the target.
## EXAMPLES
To remove specific request field exclusions that are associated with the
target of 'sqli-stable': ['owasp-crs-v030001-id942110-sqli',
'owasp-crs-v030001-id942120-sqli'], run:
$ {command} 1000 \
--security-policy=my-policy \
--target-rule-set=sqli-stable \
--target-rule-ids=owasp-crs-v030001-id942110-sqli,owasp-crs-v030001-id942120-sqli
\
--request-header-to-exclude=op=EQUALS,val=abc \
--request-header-to-exclude=op=STARTS_WITH,val=xyz \
--request-uri-to-exclude=op=EQUALS_ANY
To remove all the request field exclusions that are associated with the target
of 'sqli-stable': ['owasp-crs-v030001-id942110-sqli',
'owasp-crs-v030001-id942120-sqli'], run:
$ {command} 1000 \
--security-policy=my-policy \
--target-rule-set=sqli-stable \
--target-rule-ids=owasp-crs-v030001-id942110-sqli,owasp-crs-v030001-id942120-sqli
To remove all the request field exclusions that are associated with the target
of 'sqli-stable': [], run:
$ {command} 1000 \
--security-policy=my-policy \
--target-rule-set=sqli-stable
To remove all the request field exclusions that are configured under the
security policy rule, regardless of the target, run:
$ {command} 1000 \
--security-policy=my-policy \
--target-rule-set=*
"""
@classmethod
def Args(cls, parser):
"""Generates the flagset for a RemovePreconfigWafExclusion command."""
cls.NAME_ARG = flags.PriorityArgument(
'remove the exclusion configuration for preconfigured WAF evaluation'
)
cls.NAME_ARG.AddArgument(
parser,
operation_type=(
'remove the exclusion configuration for preconfigured WAF'
' evaluation'
),
cust_metavar='PRIORITY',
)
flags.AddRegionFlag(
parser,
'remove the exclusion configuration for preconfigured WAF evaluation')
cls.SECURITY_POLICY_ARG = (
security_policy_flags.SecurityPolicyMultiScopeArgumentForRules())
cls.SECURITY_POLICY_ARG.AddArgument(parser)
flags.AddTargetRuleSet(parser=parser, is_add=False)
flags.AddTargetRuleIds(parser=parser, is_add=False)
flags.AddRequestHeader(parser=parser, is_add=False)
flags.AddRequestCookie(parser=parser, is_add=False)
flags.AddRequestQueryParam(parser=parser, is_add=False)
flags.AddRequestUri(parser=parser, is_add=False)
@classmethod
def _IsIdenticalTarget(cls,
existing_exclusion,
target_rule_set,
target_rule_ids=None):
return target_rule_set == existing_exclusion.targetRuleSet and set(
target_rule_ids) == set(existing_exclusion.targetRuleIds)
@classmethod
def _ConvertRequestFieldToAdd(cls, compute_client, request_field_to_remove):
"""Converts RequestFieldToAdd."""
request_field = (
compute_client.messages
.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams())
op = request_field_to_remove.get('op') or ''
if op:
request_field.op = (
compute_client.messages
.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams
.OpValueValuesEnum(op))
val = request_field_to_remove.get('val') or ''
if val:
request_field.val = val
return request_field
@classmethod
def _RemoveRequestFields(cls, existing_request_fields,
request_fields_to_remove):
new_request_fields = []
for existing_request_field in existing_request_fields:
if existing_request_field not in request_fields_to_remove:
new_request_fields.append(existing_request_field)
return new_request_fields
@classmethod
def _UpdateExclusion(cls,
compute_client,
existing_exclusion,
request_headers=None,
request_cookies=None,
request_query_params=None,
request_uris=None):
"""Updates Exclusion."""
new_exclusion = (
compute_client.messages
.SecurityPolicyRulePreconfiguredWafConfigExclusion())
new_exclusion.targetRuleSet = existing_exclusion.targetRuleSet
for target_rule_id in existing_exclusion.targetRuleIds or []:
new_exclusion.targetRuleIds.append(target_rule_id)
request_headers_to_remove = []
for request_header in request_headers or []:
request_headers_to_remove.append(
cls._ConvertRequestFieldToAdd(compute_client, request_header))
new_exclusion.requestHeadersToExclude.extend(
cls._RemoveRequestFields(existing_exclusion.requestHeadersToExclude,
request_headers_to_remove))
request_cookies_to_remove = []
for request_cookie in request_cookies or []:
request_cookies_to_remove.append(
cls._ConvertRequestFieldToAdd(compute_client, request_cookie))
new_exclusion.requestCookiesToExclude.extend(
cls._RemoveRequestFields(existing_exclusion.requestCookiesToExclude,
request_cookies_to_remove))
request_query_params_to_remove = []
for request_query_param in request_query_params or []:
request_query_params_to_remove.append(
cls._ConvertRequestFieldToAdd(compute_client, request_query_param))
new_exclusion.requestQueryParamsToExclude.extend(
cls._RemoveRequestFields(
existing_exclusion.requestQueryParamsToExclude,
request_query_params_to_remove))
request_uris_to_remove = []
for request_uri in request_uris or []:
request_uris_to_remove.append(
cls._ConvertRequestFieldToAdd(compute_client, request_uri))
new_exclusion.requestUrisToExclude.extend(
cls._RemoveRequestFields(existing_exclusion.requestUrisToExclude,
request_uris_to_remove))
if not (new_exclusion.requestHeadersToExclude or
new_exclusion.requestCookiesToExclude or
new_exclusion.requestQueryParamsToExclude or
new_exclusion.requestUrisToExclude):
return None
return new_exclusion
@classmethod
def _UpdatePreconfigWafConfig(cls, compute_client, existing_rule, args):
"""Updates Preconfig WafConfig."""
new_preconfig_waf_config = (
compute_client.messages.SecurityPolicyRulePreconfiguredWafConfig())
if args.target_rule_set == '*':
return new_preconfig_waf_config
has_request_field_args = False
if (args.IsSpecified('request_header_to_exclude') or
args.IsSpecified('request_cookie_to_exclude') or
args.IsSpecified('request_query_param_to_exclude') or
args.IsSpecified('request_uri_to_exclude')):
has_request_field_args = True
if existing_rule.preconfiguredWafConfig:
exclusions = existing_rule.preconfiguredWafConfig.exclusions
else:
exclusions = []
for exclusion in exclusions:
if cls._IsIdenticalTarget(exclusion, args.target_rule_set,
args.target_rule_ids or []):
if has_request_field_args:
new_exclusion = cls._UpdateExclusion(
compute_client, exclusion, args.request_header_to_exclude,
args.request_cookie_to_exclude,
args.request_query_param_to_exclude, args.request_uri_to_exclude)
if new_exclusion:
new_preconfig_waf_config.exclusions.append(new_exclusion)
else:
new_preconfig_waf_config.exclusions.append(exclusion)
return new_preconfig_waf_config
@classmethod
def Run(cls, release_track, args):
"""Validates arguments and patches a security policy rule."""
if args.target_rule_set == '*':
if (args.IsSpecified('target_rule_ids') or
args.IsSpecified('request_header_to_exclude') or
args.IsSpecified('request_cookie_to_exclude') or
args.IsSpecified('request_query_param_to_exclude') or
args.IsSpecified('request_uri_to_exclude')):
raise exceptions.InvalidArgumentException(
'target-rule-set',
'Arguments in [--target-rule-ids, --request-header-to-exclude, '
'--request-cookie-to-exclude, --request-query-param-to-exclude, '
'--request-uri-to-exclude] cannot be specified when '
'--target-rule-set is set to *.')
for request_fields in [
args.request_header_to_exclude or [], args.request_cookie_to_exclude or
[], args.request_query_param_to_exclude or [],
args.request_uri_to_exclude or []
]:
for request_field in request_fields:
op = request_field.get('op') or ''
if not op or op not in [
'EQUALS', 'STARTS_WITH', 'ENDS_WITH', 'CONTAINS', 'EQUALS_ANY'
]:
raise exceptions.InvalidArgumentException(
'op',
'A request field operator must be one of [EQUALS, STARTS_WITH, '
'ENDS_WITH, CONTAINS, EQUALS_ANY].')
holder = base_classes.ComputeApiHolder(release_track)
compute_client = holder.client
ref = None
security_policy_ref = cls.SECURITY_POLICY_ARG.ResolveAsResource(
args, holder.resources, default_scope=compute_scope.ScopeEnum.GLOBAL)
if getattr(security_policy_ref, 'region', None) is not None:
ref = holder.resources.Parse(
args.name,
collection='compute.regionSecurityPolicyRules',
params={
'project': properties.VALUES.core.project.GetOrFail,
'region': security_policy_ref.region,
'securityPolicy': args.security_policy,
})
else:
ref = holder.resources.Parse(
args.name,
collection='compute.securityPolicyRules',
params={
'project': properties.VALUES.core.project.GetOrFail,
'securityPolicy': args.security_policy
})
security_policy_rule = client.SecurityPolicyRule(
ref, compute_client=compute_client)
existing_rule = security_policy_rule.Describe()[0]
new_preconfig_waf_config = cls._UpdatePreconfigWafConfig(
compute_client, existing_rule, args)
return security_policy_rule.Patch(
preconfig_waf_config=new_preconfig_waf_config)
@base.ReleaseTracks(base.ReleaseTrack.GA)
class RemovePreconfigWafExclusionGA(base.UpdateCommand):
r"""Remove an exclusion configuration for preconfigured WAF evaluation from a security policy rule.
*{command}* is used to remove an exclusion configuration for preconfigured WAF
evaluation from a security policy rule.
Note that request field exclusions are associated with a target, which can be
a single rule set, or a rule set plus a list of rule IDs under the rule set.
It is possible to remove request field exclusions at 3 levels:
- Remove specific request field exclusions that are associated with a matching
target.
- Remove all the request field exclusions that are associated with a matching
target.
- Remove all the request field exclusions that are configured under the
security policy rule, regardless of the target.
## EXAMPLES
To remove specific request field exclusions that are associated with the
target of 'sqli-stable': ['owasp-crs-v030001-id942110-sqli',
'owasp-crs-v030001-id942120-sqli'], run:
$ {command} 1000 \
--security-policy=my-policy \
--target-rule-set=sqli-stable \
--target-rule-ids=owasp-crs-v030001-id942110-sqli,owasp-crs-v030001-id942120-sqli
\
--request-header-to-exclude=op=EQUALS,val=abc \
--request-header-to-exclude=op=STARTS_WITH,val=xyz \
--request-uri-to-exclude=op=EQUALS_ANY
To remove all the request field exclusions that are associated with the target
of 'sqli-stable': ['owasp-crs-v030001-id942110-sqli',
'owasp-crs-v030001-id942120-sqli'], run:
$ {command} 1000 \
--security-policy=my-policy \
--target-rule-set=sqli-stable \
--target-rule-ids=owasp-crs-v030001-id942110-sqli,owasp-crs-v030001-id942120-sqli
To remove all the request field exclusions that are associated with the target
of 'sqli-stable': [], run:
$ {command} 1000 \
--security-policy=my-policy \
--target-rule-set=sqli-stable
To remove all the request field exclusions that are configured under the
security policy rule, regardless of the target, run:
$ {command} 1000 \
--security-policy=my-policy \
--target-rule-set=*
"""
SECURITY_POLICY_ARG = None
NAME_ARG = None
@classmethod
def Args(cls, parser):
RemovePreconfigWafExclusionHelper.Args(
parser,
)
def Run(self, args):
return RemovePreconfigWafExclusionHelper.Run(
self.ReleaseTrack(),
args,
)
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class RemovePreconfigWafExclusionBeta(RemovePreconfigWafExclusionGA):
r"""Remove an exclusion configuration for preconfigured WAF evaluation from a security policy rule.
*{command}* is used to remove an exclusion configuration for preconfigured WAF
evaluation from a security policy rule.
Note that request field exclusions are associated with a target, which can be
a single rule set, or a rule set plus a list of rule IDs under the rule set.
It is possible to remove request field exclusions at 3 levels:
- Remove specific request field exclusions that are associated with a matching
target.
- Remove all the request field exclusions that are associated with a matching
target.
- Remove all the request field exclusions that are configured under the
security policy rule, regardless of the target.
## EXAMPLES
To remove specific request field exclusions that are associated with the
target of 'sqli-stable': ['owasp-crs-v030001-id942110-sqli',
'owasp-crs-v030001-id942120-sqli'], run:
$ {command} 1000 \
--security-policy=my-policy \
--target-rule-set=sqli-stable \
--target-rule-ids=owasp-crs-v030001-id942110-sqli,owasp-crs-v030001-id942120-sqli
\
--request-header-to-exclude=op=EQUALS,val=abc \
--request-header-to-exclude=op=STARTS_WITH,val=xyz \
--request-uri-to-exclude=op=EQUALS_ANY
To remove all the request field exclusions that are associated with the target
of 'sqli-stable': ['owasp-crs-v030001-id942110-sqli',
'owasp-crs-v030001-id942120-sqli'], run:
$ {command} 1000 \
--security-policy=my-policy \
--target-rule-set=sqli-stable \
--target-rule-ids=owasp-crs-v030001-id942110-sqli,owasp-crs-v030001-id942120-sqli
To remove all the request field exclusions that are associated with the target
of 'sqli-stable': [], run:
$ {command} 1000 \
--security-policy=my-policy \
--target-rule-set=sqli-stable
To remove all the request field exclusions that are configured under the
security policy rule, regardless of the target, run:
$ {command} 1000 \
--security-policy=my-policy \
--target-rule-set=*
"""
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class RemovePreconfigWafExclusionAlpha(RemovePreconfigWafExclusionBeta):
r"""Remove an exclusion configuration for preconfigured WAF evaluation from a security policy rule.
*{command}* is used to remove an exclusion configuration for preconfigured WAF
evaluation from a security policy rule.
Note that request field exclusions are associated with a target, which can be
a single rule set, or a rule set plus a list of rule IDs under the rule set.
It is possible to remove request field exclusions at 3 levels:
- Remove specific request field exclusions that are associated with a matching
target.
- Remove all the request field exclusions that are associated with a matching
target.
- Remove all the request field exclusions that are configured under the
security policy rule, regardless of the target.
## EXAMPLES
To remove specific request field exclusions that are associated with the
target of 'sqli-stable': ['owasp-crs-v030001-id942110-sqli',
'owasp-crs-v030001-id942120-sqli'], run:
$ {command} 1000 \
--security-policy=my-policy \
--target-rule-set=sqli-stable \
--target-rule-ids=owasp-crs-v030001-id942110-sqli,owasp-crs-v030001-id942120-sqli
\
--request-header-to-exclude=op=EQUALS,val=abc \
--request-header-to-exclude=op=STARTS_WITH,val=xyz \
--request-uri-to-exclude=op=EQUALS_ANY
To remove all the request field exclusions that are associated with the target
of 'sqli-stable': ['owasp-crs-v030001-id942110-sqli',
'owasp-crs-v030001-id942120-sqli'], run:
$ {command} 1000 \
--security-policy=my-policy \
--target-rule-set=sqli-stable \
--target-rule-ids=owasp-crs-v030001-id942110-sqli,owasp-crs-v030001-id942120-sqli
To remove all the request field exclusions that are associated with the target
of 'sqli-stable': [], run:
$ {command} 1000 \
--security-policy=my-policy \
--target-rule-set=sqli-stable
To remove all the request field exclusions that are configured under the
security policy rule, regardless of the target, run:
$ {command} 1000 \
--security-policy=my-policy \
--target-rule-set=*
"""

View File

@@ -0,0 +1,367 @@
# -*- coding: utf-8 -*- #
# Copyright 2017 Google LLC. All Rights Reserved.
#
# Licensed 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.
"""Command for updating security policies rules."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.api_lib.compute.security_policies import client
from googlecloudsdk.calliope import base
from googlecloudsdk.calliope import exceptions
from googlecloudsdk.command_lib.compute import scope as compute_scope
from googlecloudsdk.command_lib.compute.security_policies import flags as security_policy_flags
from googlecloudsdk.command_lib.compute.security_policies import security_policies_utils
from googlecloudsdk.command_lib.compute.security_policies.rules import flags
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
class UpdateHelper(object):
r"""Update a Compute Engine security policy rule.
*{command}* is used to update security policy rules.
## EXAMPLES
To update the description and IP ranges of a rule at priority
1000, run:
$ {command} 1000 \
--security-policy=my-policy \
--description="block 1.2.3.4/32" \
--src-ip-ranges=1.2.3.4/32
"""
@classmethod
def Args(
cls,
parser,
support_fairshare=False,
support_rpc_status=False,
):
"""Generates the flagset for an Update command."""
cls.NAME_ARG = (flags.PriorityArgument('update'))
cls.NAME_ARG.AddArgument(
parser, operation_type='update', cust_metavar='PRIORITY')
flags.AddRegionFlag(parser, 'update')
cls.SECURITY_POLICY_ARG = (
security_policy_flags.SecurityPolicyMultiScopeArgumentForRules()
)
cls.SECURITY_POLICY_ARG.AddArgument(parser)
flags.AddMatcherAndNetworkMatcher(parser, required=False)
flags.AddAction(
parser,
required=False,
support_fairshare=support_fairshare)
flags.AddDescription(parser)
flags.AddPreview(parser, for_update=True)
flags.AddRedirectOptions(parser)
flags.AddRateLimitOptions(
parser,
support_rpc_status=support_rpc_status,
)
flags.AddRequestHeadersToAdd(parser)
flags.AddRecaptchaOptions(parser)
@classmethod
def Run(
cls,
release_track,
args,
support_rpc_status,
):
"""Validates arguments and patches a security policy rule."""
modified_fields = [
args.description,
args.src_ip_ranges,
args.action,
args.preview is not None,
args.network_user_defined_fields,
args.network_src_ip_ranges,
args.network_dest_ip_ranges,
args.network_ip_protocols,
args.network_src_ports,
args.network_dest_ports,
args.network_src_region_codes,
args.network_src_asns,
args.redirect_type,
args.redirect_target,
args.request_headers_to_add,
args.rate_limit_threshold_count,
args.rate_limit_threshold_interval_sec,
args.conform_action,
args.exceed_action,
args.enforce_on_key,
args.enforce_on_key_name,
args.ban_threshold_count,
args.ban_threshold_interval_sec,
args.ban_duration_sec,
args.recaptcha_action_site_keys,
args.recaptcha_session_site_keys,
]
min_args = [
'--description',
'--src-ip-ranges',
'--expression',
'--action',
'--preview',
'--network-user-defined-fields',
'--network-src-ip-ranges',
'--network-dest-ip-ranges',
'--network-ip-protocols',
'--network-src-ports',
'--network-dest-ports',
'--network-src-region-codes',
'--redirect-type',
'--redirect-target',
'--request-headers-to-add',
'--rate-limit-threshold-count',
'--rate-limit-threshold-interval-sec',
'--conform-action',
'--exceed-action',
'--enforce-on-key',
'--enforce-on-key-name',
'--ban-threshold-count',
'--ban-threshold-interval-sec',
'--ban-duration-sec',
'--recaptcha_action_site_keys',
'--recaptcha_session_site_keys',
]
if support_rpc_status:
modified_fields.extend([
args.exceed_action_rpc_status_code,
args.exceed_action_rpc_status_message,
])
min_args.extend([
'--exceed-action-rpc-status-code',
'--exceed-action-rpc-status-message',
])
if not any(
[args.IsSpecified(field[2:].replace('-', '_')) for field in min_args]):
raise exceptions.MinimumArgumentException(
min_args, 'At least one property must be modified.')
holder = base_classes.ComputeApiHolder(release_track)
if args.security_policy:
security_policy_ref = cls.SECURITY_POLICY_ARG.ResolveAsResource(
args,
holder.resources,
default_scope=compute_scope.ScopeEnum.GLOBAL)
if getattr(security_policy_ref, 'region', None) is not None:
ref = holder.resources.Parse(
args.name,
collection='compute.regionSecurityPolicyRules',
params={
'project': properties.VALUES.core.project.GetOrFail,
'region': security_policy_ref.region,
'securityPolicy': args.security_policy,
})
else:
ref = holder.resources.Parse(
args.name,
collection='compute.securityPolicyRules',
params={
'project': properties.VALUES.core.project.GetOrFail,
'securityPolicy': args.security_policy,
},
)
else:
try:
ref = holder.resources.Parse(
args.name,
collection='compute.regionSecurityPolicyRules',
params={
'project': properties.VALUES.core.project.GetOrFail,
'region': getattr(args, 'region', None),
},
)
except (
resources.RequiredFieldOmittedException,
resources.WrongResourceCollectionException,
):
ref = holder.resources.Parse(
args.name,
collection='compute.securityPolicyRules',
params={
'project': properties.VALUES.core.project.GetOrFail,
},
)
security_policy_rule = client.SecurityPolicyRule(
ref, compute_client=holder.client)
redirect_options = security_policies_utils.CreateRedirectOptions(
holder.client, args
)
rate_limit_options = security_policies_utils.CreateRateLimitOptions(
holder.client, args, support_rpc_status
)
request_headers_to_add = args.request_headers_to_add
expression_options = security_policies_utils.CreateExpressionOptions(
holder.client, args
)
result = security_policies_utils.CreateNetworkMatcher(
holder.client, args
)
network_matcher = result[0]
update_mask = result[1]
if args.IsSpecified('action') and args.action not in ['redirect']:
update_mask.append('redirect_options')
if args.IsSpecified('action') and args.action not in [
'throttle',
'rate-based-ban',
'fairshare',
]:
update_mask.append('rate_limit_options')
elif args.IsSpecified('exceed_action') and args.exceed_action not in [
'redirect'
]:
update_mask.append('rate_limit_options.exceed_redirect_options')
update_mask_str = ','.join(update_mask)
return security_policy_rule.Patch(
src_ip_ranges=args.src_ip_ranges,
expression=args.expression,
expression_options=expression_options,
network_matcher=network_matcher,
action=args.action,
description=args.description,
preview=args.preview,
redirect_options=redirect_options,
rate_limit_options=rate_limit_options,
request_headers_to_add=request_headers_to_add,
update_mask=update_mask_str if update_mask_str else None,
)
@base.UniverseCompatible
@base.ReleaseTracks(base.ReleaseTrack.GA)
class UpdateGA(base.UpdateCommand):
r"""Update a Compute Engine security policy rule.
*{command}* is used to update security policy rules.
## EXAMPLES
To update the description and IP ranges of a rule at priority
1000, run:
$ {command} 1000 \
--security-policy=my-policy \
--description="block 1.2.3.4/32" \
--src-ip-ranges=1.2.3.4/32
"""
SECURITY_POLICY_ARG = None
NAME_ARG = None
_support_rpc_status = False
@classmethod
def Args(cls, parser):
UpdateHelper.Args(
parser,
support_rpc_status=cls._support_rpc_status,
)
def Run(self, args):
return UpdateHelper.Run(
self.ReleaseTrack(),
args,
self._support_rpc_status,
)
@base.UniverseCompatible
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class UpdateBeta(base.UpdateCommand):
r"""Update a Compute Engine security policy rule.
*{command}* is used to update security policy rules.
## EXAMPLES
To update the description and IP ranges of a rule at priority
1000, run:
$ {command} 1000 \
--security-policy=my-policy \
--description="block 1.2.3.4/32" \
--src-ip-ranges=1.2.3.4/32
"""
SECURITY_POLICY_ARG = None
_support_rpc_status = False
@classmethod
def Args(cls, parser):
UpdateHelper.Args(
parser,
support_fairshare=True,
support_rpc_status=cls._support_rpc_status,
)
def Run(self, args):
return UpdateHelper.Run(
self.ReleaseTrack(),
args,
self._support_rpc_status,
)
@base.UniverseCompatible
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class UpdateAlpha(base.UpdateCommand):
r"""Update a Compute Engine security policy rule.
*{command}* is used to update security policy rules.
## EXAMPLES
To update the description and IP ranges of a rule at priority
1000, run:
$ {command} 1000 \
--security-policy=my-policy \
--description="block 1.2.3.4/32" \
--src-ip-ranges=1.2.3.4/32
"""
SECURITY_POLICY_ARG = None
_support_rpc_status = True
@classmethod
def Args(cls, parser):
UpdateHelper.Args(
parser,
support_fairshare=True,
support_rpc_status=cls._support_rpc_status,
)
def Run(self, args):
return UpdateHelper.Run(
self.ReleaseTrack(),
args,
self._support_rpc_status,
)