Skip to content

compute

Sample rules

A few rules that use objects from this package:

car_proxy_lb_ssl_policy_no_weak_ciphers
from typing import List, Dict

from cloudrail.knowledge.context.gcp.gcp_environment_context import GcpEnvironmentContext
from cloudrail.knowledge.rules.base_rule import Issue
from cloudrail.knowledge.rules.gcp.gcp_base_rule import GcpBaseRule
from cloudrail.knowledge.rules.rule_parameters.base_paramerter import ParameterType


class ComputeSslPolicyProxyNoWeakCiphersRule(GcpBaseRule):
    def get_id(self) -> str:
        return 'car_proxy_lb_ssl_policy_no_weak_ciphers'

    def execute(self, env_context: GcpEnvironmentContext, parameters: Dict[ParameterType, any]) -> List[Issue]:
        issues: List[Issue] = []
        for global_forwarding_rule in env_context.compute_global_forwarding_rule:
            if global_forwarding_rule.target.is_encrypted:
                if ssl_policy := global_forwarding_rule.target.ssl_policy:
                    if not ssl_policy.min_tls_version == "TLS_1_2":
                        issues.append(
                            Issue(
                                f"The {global_forwarding_rule.get_type()} `{global_forwarding_rule.get_friendly_name()}` is using TLS version less that 1.2 in target "
                                f"{global_forwarding_rule.target.target_type} proxy {global_forwarding_rule.target.get_friendly_name()} "
                                f"with a misconfigured SSL policy {ssl_policy.get_friendly_name()}",
                                global_forwarding_rule,
                                ssl_policy))
                    elif (ssl_policy.profile == "CUSTOM" and not ssl_policy.is_using_secure_ciphers) or \
                            ssl_policy.profile not in ["MODERN", "RESTRICTED", "CUSTOM"]:
                        issues.append(
                            Issue(
                                f"The {global_forwarding_rule.get_type()} `{global_forwarding_rule.get_friendly_name()}` is using weak ciphers in target "
                                f"{global_forwarding_rule.target.target_type} proxy {global_forwarding_rule.target.get_friendly_name()} with a misconfigured SSL policy "
                                f"{ssl_policy.get_friendly_name()}",
                                global_forwarding_rule,
                                ssl_policy))
                else:
                    issues.append(
                        Issue(
                            f"The {global_forwarding_rule.get_type()} `{global_forwarding_rule.get_friendly_name()}` is missing SSL policy",
                            global_forwarding_rule,
                            global_forwarding_rule))
        return issues

    def should_run_rule(self, environment_context: GcpEnvironmentContext) -> bool:
        return bool(environment_context.compute_global_forwarding_rule)
non_car_compute_instance_no_default_service_account_full_access_api
from typing import List, Dict

from cloudrail.knowledge.context.gcp.gcp_environment_context import GcpEnvironmentContext
from cloudrail.knowledge.rules.base_rule import Issue
from cloudrail.knowledge.rules.gcp.gcp_base_rule import GcpBaseRule
from cloudrail.knowledge.rules.rule_parameters.base_paramerter import ParameterType


class ComputeInstanceDoNotUseDefaultServiceAccountFullAccessScopeRule(GcpBaseRule):
    def get_id(self) -> str:
        return 'non_car_compute_instance_no_default_service_account_full_access_api'

    def execute(self, env_context: GcpEnvironmentContext, parameters: Dict[ParameterType, any]) -> List[Issue]:
        issues: List[Issue] = []
        for compute_instance in env_context.compute_instances:
            if compute_instance.is_using_default_service_account and any('cloud-platform' in scope for scope in compute_instance.service_account.scopes):
                issues.append(
                    Issue(
                        f"The {compute_instance.get_type()} `{compute_instance.get_friendly_name()}` uses default service account, "
                        f"and the scope https://www.googleapis.com/auth/cloud-platform",
                        compute_instance,
                        compute_instance))
        return issues

    def should_run_rule(self, environment_context: GcpEnvironmentContext) -> bool:
        return bool(environment_context.compute_instances)
car_vpc_not_publicly_accessible_ssh
from abc import abstractmethod
from typing import List, Dict, Optional, Set
from cloudrail.knowledge.context.gcp.resources.networking_config.network_entity import NetworkEntity
from cloudrail.knowledge.context.gcp.gcp_environment_context import GcpEnvironmentContext
from cloudrail.knowledge.context.gcp.gcp_connection_evaluator import GcpConnectionEvaluator
from cloudrail.knowledge.context.gcp.resources.compute.gcp_compute_forwarding_rule import GcpComputeForwardingRule
from cloudrail.knowledge.context.gcp.resources.compute.gcp_compute_firewall import GcpComputeFirewall
from cloudrail.knowledge.rules.gcp.gcp_base_rule import GcpBaseRule
from cloudrail.knowledge.rules.base_rule import Issue
from cloudrail.knowledge.rules.constants.known_ports import KnownPorts
from cloudrail.knowledge.rules.rule_parameters.base_paramerter import ParameterType


class PublicAccessVpcPortRule(GcpBaseRule):

    def __init__(self, port: KnownPorts) -> None:
        self.port = port

    @abstractmethod
    def get_id(self) -> str:
        pass

    def should_run_rule(self, environment_context: GcpEnvironmentContext) -> bool:
        return bool(environment_context.get_all_network_entities())

    def execute(self, env_context: GcpEnvironmentContext, parameters: Dict[ParameterType, any]) -> List[Issue]:
        issues: List[Issue] = []
        for network_entity in env_context.get_all_network_entities():
            firewalls: Set[GcpComputeFirewall] = GcpConnectionEvaluator.firewalls_allowing_incoming_public_conns_on_port(network_entity, self.port)
            if firewalls:
                forwarding_rules = self.conns_forwarding_on_port(network_entity, self.port)
                public_ip_addresses = network_entity.public_ip_addresses
                for firewall in firewalls:
                    if public_ip_addresses and forwarding_rules:
                        for rule in forwarding_rules:
                            issues.append(
                                Issue(
                                    f"The {network_entity.get_type()} `{network_entity.get_friendly_name()}` "
                                    f"with one of the public IP addresses `{', ' .join(public_ip_addresses)}` "
                                    f"and via load balancer `{rule.get_friendly_name()}"
                                    f"is reachable from the Internet via {self.port.name} port",
                                    network_entity,
                                    firewall))
                    elif public_ip_addresses and not forwarding_rules:
                        issues.append(
                                Issue(
                                    f"The {network_entity.get_type()} `{network_entity.get_friendly_name()}` "
                                    f"with one of the public IP addresses `{', ' .join(public_ip_addresses)}` "
                                    f"is reachable from the Internet via {self.port.name} port",
                                    network_entity,
                                    firewall))
                    elif forwarding_rules and not public_ip_addresses:
                        for rule in forwarding_rules:
                            issues.append(
                                Issue(
                                    f"The {network_entity.get_type()} `{network_entity.get_friendly_name()}` "
                                    f"exposed via load balancer `{rule.get_friendly_name()}` "
                                    f"is reachable from the Internet via {self.port.name} port",
                                    network_entity,
                                    firewall))
        return issues

    @staticmethod
    def conns_forwarding_on_port(network_resource: NetworkEntity, port: int) -> Optional[GcpComputeForwardingRule]:
        return [rule for rule in network_resource.forwarding_rules
                if network_resource.self_link in rule.target_pool.instances
                and port in rule.port_range]

class PublicAccessVpcSshPortRule(PublicAccessVpcPortRule):

    def get_id(self) -> str:
        return 'car_vpc_not_publicly_accessible_ssh'

    def __init__(self):
        super().__init__(KnownPorts.SSH)

class PublicAccessVpcRdpPortRule(PublicAccessVpcPortRule):

    def get_id(self) -> str:
        return 'car_vpc_not_publicly_accessible_rdp'

    def __init__(self):
        super().__init__(KnownPorts.RDP)

FirewallRuleAction (str, Enum)

An enumeration.

GcpComputeFirewall (GcpResource)

Attributes:

Name Type Description
name str

(Required) A unique name of the resource.

network str

(Required) The VPC network name or self_link of the network to attach this firewall to a compute resource.

allow List[GcpComputeFirewallAction]

(Optional) The list of ALLOW rules specified by this firewall.

deny List[GcpComputeFirewallAction]

(Optional) The list of DENY rules specified by this firewall.

destination_ranges Optional[List[str]]

(Optional) If destination ranges are specified, the firewall will apply only to traffic that has destination IP address in these ranges.

direction Optional[GcpComputeFirewallDirection]

(Optional) Direction of traffic to which this firewall applies; default is INGRESS. Possible values are INGRESS and EGRESS.

source_ranges Optional[List[str]]

(Optional) If source ranges are specified, the firewall will apply only to traffic that has source IP address in these ranges.

priority int

(Optional) The priority set for the firewall rule.

disabled bool

An indication if the firewall rule is not enforced on the attached network.

custom_invalidation(self) inherited

A list of manual reasons why this resource should be invalidated

exclude_from_invalidation(self) inherited

A list of attributes that should be excluded from the invalidation process

GcpComputeFirewallAction dataclass

Attributes:

Name Type Description
protocol IpProtocol

(Required) The IP protocol to which this rule applies.

ports PortSet

(Optional) An optional list of ports to which this rule applies. This field is only applicable for UDP or TCP protocol.

action FirewallRuleAction

Rule action (allow or deny)

GcpComputeFirewallDirection (str, Enum)

An enumeration.

GcpComputeForwardingRule (GcpResource)

Attributes:

Name Type Description
name str

(Required) A unique name of the resource.

target str

(Optional) The URL of the target resource to receive the matched traffic.

port_range PortSet

The port range being used to forward traffic to the target.

custom_invalidation(self) inherited

A list of manual reasons why this resource should be invalidated

exclude_from_invalidation(self) inherited

A list of attributes that should be excluded from the invalidation process

GcpComputeGlobalForwardingRule (GcpResource)

Attributes:

Name Type Description
name str

(Required) A unique name of the resource.

target_identifier str

(Required) The URL of the target resource to receive the matched traffic.

custom_invalidation(self) inherited

A list of manual reasons why this resource should be invalidated

exclude_from_invalidation(self) inherited

A list of attributes that should be excluded from the invalidation process

GcpComputeInstance (NetworkEntity)

Attributes:

Name Type Description
name str

A unique name for the compute instance.

zone str

The zone this compute instance located at.

network_interfaces

Networks to attach to the instance.

can_ip_forward bool

(Optional) Whether to allow sending and receiving of packets with non-matching source or destination IPs.

hostname str

(Optional) A custom hostname for the instance.

metadata dict

(Optional) Metadata key/value pairs to make available from within the instance.

service_account Optional[GcpComputeInstanceServiceAccount]

(Optional) Service account to attach to the instance.

shielded_instance_config Optional[GcpComputeInstanceShieldInstCfg]

(Optional) Enable Shielded VM on this instance.

self_link str

The self_link URL used for this resource.

custom_invalidation(self) inherited

A list of manual reasons why this resource should be invalidated

exclude_from_invalidation(self) inherited

A list of attributes that should be excluded from the invalidation process

GcpComputeInstanceNetIntfAccessCfg dataclass

Attributes:

Name Type Description
nat_ip Optional[str]

(Optional) The IP address that will be 1:1 mapped to the instance's network ip.

public_ptr_domain_name Optional[str]

(Optional) The DNS domain name for the public PTR record.

network_tier Optional[str]

(Optional) The networking tier used for configuring this instance. Possible values: PREMIUM, STANDARD.

GcpComputeInstanceNetIntfAliasIpRange dataclass

Attributes:

Name Type Description
ip_cidr_range str

The IP CIDR range represented by this alias IP range.

subnetwork_range_name Optional[str]

(Optional) The subnetwork secondary range name specifying the secondary range.

GcpComputeInstanceNetIntfNicType (str, Enum)

An enumeration.

GcpComputeInstanceNetworkInterface (GcpNetworkInterface) dataclass

Attributes:

Name Type Description
subnetwork Optional[str]

(Optional) The name or self_link of the subnetwork to attach this interface to.

subnetwork_project Optional[str]

(Optional) The project in which the subnetwork belongs.

access_config Optional[List[GcpComputeInstanceNetIntfAccessCfg]]

(Optional) Access configurations, i.e. IPs via which this instance can be accessed via the Internet.

alias_ip_range Optional[List[GcpComputeInstanceNetIntfAliasIpRange]]

(Optional) An array of alias IP ranges for this network interface.

GcpComputeInstanceServiceAccount dataclass

Attributes:

Name Type Description
email Optional[str]

(Optional) The service account e-mail address. If not given, the default Google Compute Engine service account is used.

scopes str

A list of service scopes. Both OAuth2 URLs and gcloud short names are supported.

GcpComputeInstanceShieldInstCfg dataclass

Attributes:

Name Type Description
enable_secure_boot Optional[bool]

(Optional) Verify the digital signature of all boot components, and halt the boot process on failure.

enable_vtpm Optional[bool]

(Optional) Use a virtualized trusted platform module, to encrypt objects like keys and certificates.

enable_integrity_monitoring Optional[bool]

(Optional) Compare the most recent boot measurements to the integrity policy baseline and return a pair of pass/fail results.

GcpComputeNetwork (GcpResource)

name: (Required) A unique name of the resource. network_id: (Optional) an identifier for the resource self_link: (Optional) The URI of the created resource. auto_create_subnetworks: (Optional) When set to true, the network is created in "auto subnet mode" and it will create a subnet for each region automatically across the 10.128.0.0/9 address range. routing_mode: (Optional) The network-wide routing mode to use. Possible values are REGIONAL and GLOBAL.

custom_invalidation(self) inherited

A list of manual reasons why this resource should be invalidated

exclude_from_invalidation(self) inherited

A list of attributes that should be excluded from the invalidation process

GcpComputeNetworkRoutingMode (Enum)

An enumeration.

GcpComputeSslPolicy (GcpResource)

Attributes:

Name Type Description
name str

(Required) A unique name of the resource.

policy_id str

an identifier for the resource with format projects/{{project}}/global/sslPolicies/{{name}}

self_link str

(Optional) The URI of the created resource.

min_tls_version str

(Optional) The minimum version of SSL protocol that can be used by the clients to establish a connection with the load balancer. Default value is TLS_1_0

profile str

(Optional) Profile specifies the set of SSL features that can be used by the load balancer when negotiating SSL with clients

custom_features Optional[List[str]]

(Optional) the set of SSL features. if CUSTOM profile is used this attribute must be set.

custom_invalidation(self) inherited

A list of manual reasons why this resource should be invalidated

exclude_from_invalidation(self) inherited

A list of attributes that should be excluded from the invalidation process

GcpComputeSubNetwork (GcpResource)

name: (Required) A unique name of the resource. subnetwork_id: (Optional) an identifier for the resource self_link: (Optional) The URI of the created resource. region: (Optional) The GCP region for this subnetwork. network_identifier: (Required) The network this subnet belongs to. ip_cidr_range: (Required) The range of internal addresses that are owned by this subnetwork. log_config: (Optional) Denotes the logging options for the subnetwork flow logs.

custom_invalidation(self) inherited

A list of manual reasons why this resource should be invalidated

exclude_from_invalidation(self) inherited

A list of attributes that should be excluded from the invalidation process

GcpComputeSubNetworkLogConfig dataclass

enabled: Indication if the flow logs are enabled or not. aggregation_interval: (Optional) Toggles the aggregation interval for collecting flow logs. flow_sampling : (Optional) The value of the field must be in [0, 1]. Set the sampling rate of VPC flow logs within the subnetwork where 1.0 means all collected logs are reported and 0.0 means no logs are reported. metadata: (Optional) Configures whether metadata fields should be added to the reported VPC flow logs. metadata_fields: (Optional) List of metadata fields that should be added to reported logs. filter_expr : (Optional) Export filter used to define which VPC flow logs should be logged, as as CEL expression.

GcpComputeTargetHttpProxy (GcpComputeTargetProxy)

Attributes:

Name Type Description
name

(Required) A unique name of the resource.

target_id str

an identifier for the resource with format projects/{{project}}/global/targetHttpProxies/{{name}}

self_link

(Optional) The URI of the created resource.

url_map str

A reference to the UrlMap resource that defines the mapping from URL to the BackendService.

is_encrypted: bool property readonly

True if the target protocol is secure (e.g ssl, https)

custom_invalidation(self) inherited

A list of manual reasons why this resource should be invalidated

exclude_from_invalidation(self) inherited

A list of attributes that should be excluded from the invalidation process

GcpComputeTargetHttpsProxy (GcpComputeTargetProxy)

Attributes:

Name Type Description
name

(Required) A unique name of the resource.

target_id str

an identifier for the resource with format projects/{{project}}/global/targetHttpsProxies/{{name}}

self_link

(Optional) The URI of the created resource.

ssl_certificates List[str]

A list of SslCertificate resources that are used to authenticate connections between users and the load balancer. At least one SSL certificate must be specified.

url_map str

A reference to the UrlMap resource that defines the mapping from URL to the BackendService.

ssl_policy_identifier Optional[str]

(Optional) A reference to the SslPolicy resource that will be associated with the TargetSslProxy resource.

is_encrypted: bool property readonly

True if the target protocol is secure (e.g ssl, https)

custom_invalidation(self) inherited

A list of manual reasons why this resource should be invalidated

exclude_from_invalidation(self) inherited

A list of attributes that should be excluded from the invalidation process

GcpComputeTargetPool (GcpResource)

Attributes:

Name Type Description
name str

(Required) A unique name of the resource.

region Optional[str]

(Optional) Where the target pool resides. Defaults to project region.

instances Optional[List[str]]

(Optional) (Optional) List of instances in the pool.

self_link str

The URL self link used for this resource.

custom_invalidation(self) inherited

A list of manual reasons why this resource should be invalidated

exclude_from_invalidation(self) inherited

A list of attributes that should be excluded from the invalidation process

GcpComputeTargetProxy (GcpResource)

A parent resource for all target proxy resources

Attributes:

Name Type Description
name str

(Required) A unique name of the resource.

self_link str

(Optional) The URI of the created resource.

is_encrypted: bool property readonly

True if the target protocol is secure (e.g ssl, https)

custom_invalidation(self) inherited

A list of manual reasons why this resource should be invalidated

exclude_from_invalidation(self) inherited

A list of attributes that should be excluded from the invalidation process

TargetTypes (Enum)

An enumeration.

GcpComputeTargetSslProxy (GcpComputeTargetProxy)

Attributes:

Name Type Description
name

(Required) A unique name of the resource.

target_id str

an identifier for the resource with format projects/{{project}}/global/targetSslProxies/{{name}}

self_link

(Optional) The URI of the created resource.

backend_service str

A reference to the BackendService resource.

ssl_certificates List[str]

A list of SslCertificate resources that are used to authenticate connections between users and the load balancer. At least one SSL certificate must be specified.

ssl_policy_identifier Optional[str]

(Optional) A reference to the SslPolicy resource that will be associated with the TargetSslProxy resource.

is_encrypted: bool property readonly

True if the target protocol is secure (e.g ssl, https)

custom_invalidation(self) inherited

A list of manual reasons why this resource should be invalidated

exclude_from_invalidation(self) inherited

A list of attributes that should be excluded from the invalidation process