|
| 1 | +""" |
| 2 | +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 3 | +SPDX-License-Identifier: MIT-0 |
| 4 | +""" |
| 5 | + |
| 6 | +from __future__ import annotations |
| 7 | + |
| 8 | +import logging |
| 9 | +from collections import deque |
| 10 | +from ipaddress import IPv4Network, IPv6Network, ip_network |
| 11 | +from typing import Any, Iterator |
| 12 | + |
| 13 | +from cfnlint.context import Path |
| 14 | +from cfnlint.jsonschema import ValidationError, ValidationResult, Validator |
| 15 | +from cfnlint.rules.helpers import get_value_from_path |
| 16 | +from cfnlint.rules.jsonschema.CfnLintKeyword import CfnLintKeyword |
| 17 | + |
| 18 | +LOGGER = logging.getLogger(__name__) |
| 19 | + |
| 20 | + |
| 21 | +class VpcSubnetCidr(CfnLintKeyword): |
| 22 | + id = "E3059" |
| 23 | + shortdesc = "Validate subnet CIDRs are within the CIDRs of the VPC" |
| 24 | + description = ( |
| 25 | + "When specifying subnet CIDRs for a VPC the subnet CIDRs " |
| 26 | + "most be within the VPC CIDRs" |
| 27 | + ) |
| 28 | + source_url = "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet.html" |
| 29 | + tags = ["resources", "ec2", "vpc", "subnet"] |
| 30 | + |
| 31 | + def __init__(self) -> None: |
| 32 | + super().__init__( |
| 33 | + keywords=[ |
| 34 | + "Resources/AWS::EC2::VPC/Properties", |
| 35 | + ], |
| 36 | + ) |
| 37 | + |
| 38 | + def _validate_subnets( |
| 39 | + self, |
| 40 | + source: IPv4Network | IPv6Network, |
| 41 | + destination: IPv4Network | IPv6Network, |
| 42 | + ) -> bool: |
| 43 | + if isinstance(source, IPv4Network) and isinstance(destination, IPv4Network): |
| 44 | + if source.subnet_of(destination): |
| 45 | + return True |
| 46 | + return False |
| 47 | + elif isinstance(source, IPv6Network) and isinstance(destination, IPv6Network): |
| 48 | + if source.subnet_of(destination): |
| 49 | + return True |
| 50 | + return False |
| 51 | + return False |
| 52 | + |
| 53 | + def _create_network(self, cidr: Any) -> IPv4Network | IPv6Network | None: |
| 54 | + if not isinstance(cidr, str): |
| 55 | + return None |
| 56 | + |
| 57 | + try: |
| 58 | + return ip_network(cidr) |
| 59 | + except Exception as e: |
| 60 | + LOGGER.debug(f"Unable to create network from {cidr}", e) |
| 61 | + |
| 62 | + return None |
| 63 | + |
| 64 | + def _get_vpc_cidrs( |
| 65 | + self, validator: Validator, instance: dict[str, Any] |
| 66 | + ) -> Iterator[tuple[IPv4Network | IPv6Network | None, Validator]]: |
| 67 | + for key in [ |
| 68 | + "Ipv4IpamPoolId", |
| 69 | + "Ipv6IpamPoolId", |
| 70 | + "Ipv6Pool", |
| 71 | + "AmazonProvidedIpv6CidrBlock", |
| 72 | + ]: |
| 73 | + for value, value_validator in get_value_from_path( |
| 74 | + validator, |
| 75 | + instance, |
| 76 | + deque([key]), |
| 77 | + ): |
| 78 | + if value is None: |
| 79 | + continue |
| 80 | + yield None, value_validator |
| 81 | + |
| 82 | + for key in ["CidrBlock", "Ipv6CidrBlock"]: |
| 83 | + for cidr, cidr_validator in get_value_from_path( |
| 84 | + validator, |
| 85 | + instance, |
| 86 | + deque([key]), |
| 87 | + ): |
| 88 | + |
| 89 | + if cidr is None: |
| 90 | + continue |
| 91 | + yield self._create_network(cidr), cidr_validator |
| 92 | + |
| 93 | + def validate( |
| 94 | + self, validator: Validator, keywords: Any, instance: Any, schema: dict[str, Any] |
| 95 | + ) -> ValidationResult: |
| 96 | + |
| 97 | + if not validator.cfn.graph: |
| 98 | + return |
| 99 | + |
| 100 | + vpc_ipv4_networks: list[IPv4Network] = [] |
| 101 | + vpc_ipv6_networks: list[IPv6Network] = [] |
| 102 | + for vpc_network, _ in self._get_vpc_cidrs(validator, instance): |
| 103 | + if not vpc_network: |
| 104 | + return |
| 105 | + if isinstance(vpc_network, IPv4Network): |
| 106 | + vpc_ipv4_networks.append(vpc_network) |
| 107 | + # you can't specify IPV6 networks on a VPC |
| 108 | + |
| 109 | + template_validator = validator.evolve( |
| 110 | + context=validator.context.evolve(path=Path()) |
| 111 | + ) |
| 112 | + |
| 113 | + # dynamic vpc network (using IPAM or AWS provided) |
| 114 | + # allows to validate subnet overlapping even if using |
| 115 | + # dynamic networks |
| 116 | + has_dynamic_network = False |
| 117 | + |
| 118 | + for source, _ in validator.cfn.graph.graph.in_edges( |
| 119 | + validator.context.path.path[1] |
| 120 | + ): |
| 121 | + if ( |
| 122 | + validator.cfn.graph.graph.nodes[source].get("resource_type") |
| 123 | + == "AWS::EC2::VPCCidrBlock" |
| 124 | + ): |
| 125 | + for cidr_props, cidr_validator in get_value_from_path( |
| 126 | + template_validator, |
| 127 | + validator.cfn.template, |
| 128 | + deque(["Resources", source, "Properties"]), |
| 129 | + ): |
| 130 | + for cidr_network, _ in self._get_vpc_cidrs( |
| 131 | + cidr_validator, cidr_props |
| 132 | + ): |
| 133 | + if not cidr_network: |
| 134 | + has_dynamic_network = True |
| 135 | + continue |
| 136 | + if isinstance(cidr_network, IPv4Network): |
| 137 | + vpc_ipv4_networks.append(cidr_network) |
| 138 | + else: |
| 139 | + vpc_ipv6_networks.append(cidr_network) |
| 140 | + |
| 141 | + subnets: list[tuple[IPv4Network | IPv6Network, deque]] = [] |
| 142 | + for source, _ in validator.cfn.graph.graph.in_edges( |
| 143 | + validator.context.path.path[1] |
| 144 | + ): |
| 145 | + if ( |
| 146 | + validator.cfn.graph.graph.nodes[source].get("resource_type") |
| 147 | + == "AWS::EC2::Subnet" |
| 148 | + ): |
| 149 | + for subnet_props, source_validator in get_value_from_path( |
| 150 | + template_validator, |
| 151 | + validator.cfn.template, |
| 152 | + deque(["Resources", source, "Properties"]), |
| 153 | + ): |
| 154 | + for subnet_network, subnet_validator in self._get_vpc_cidrs( |
| 155 | + source_validator, subnet_props |
| 156 | + ): |
| 157 | + if not subnet_network: |
| 158 | + continue |
| 159 | + |
| 160 | + subnets.append( |
| 161 | + (subnet_network, subnet_validator.context.path.path) |
| 162 | + ) |
| 163 | + if has_dynamic_network: |
| 164 | + continue |
| 165 | + if not any( |
| 166 | + self._validate_subnets( |
| 167 | + subnet_network, |
| 168 | + vpc_network, |
| 169 | + ) |
| 170 | + for vpc_network in vpc_ipv4_networks + vpc_ipv6_networks |
| 171 | + ): |
| 172 | + if isinstance(subnet_network, IPv4Network): |
| 173 | + # Every VPC has to have a ipv4 network |
| 174 | + # we continue if there isn't one |
| 175 | + if not vpc_ipv4_networks: |
| 176 | + continue |
| 177 | + reprs = ( |
| 178 | + "is not a valid subnet of " |
| 179 | + f"{[f'{str(v)}' for v in vpc_ipv4_networks]!r}" |
| 180 | + ) |
| 181 | + else: |
| 182 | + if not vpc_ipv6_networks: |
| 183 | + reprs = ( |
| 184 | + "is specified on a VPC that has " |
| 185 | + "no ipv6 networks defined" |
| 186 | + ) |
| 187 | + else: |
| 188 | + reprs = ( |
| 189 | + "is not a valid subnet of " |
| 190 | + f"{[f'{str(v)}' for v in vpc_ipv6_networks]!r}" |
| 191 | + ) |
| 192 | + yield ValidationError( |
| 193 | + (f"{str(subnet_network)!r} {reprs}"), |
| 194 | + rule=self, |
| 195 | + path_override=subnet_validator.context.path.path, |
| 196 | + ) |
| 197 | + continue |
0 commit comments