Ejemplo n.º 1
0
    def _process_resource(self, resource):
        rule_set = NetworkRuleSet(default_action=self.data['default-action'])

        if 'ip-rules' in self.data:
            rule_set.ip_rules = [
                IPRule(
                    ip_address_or_range=r['ip-address-or-range'],
                    action='Allow')  # 'Allow' is the only allowed action
                for r in self.data['ip-rules']]

        if 'virtual-network-rules' in self.data:
            rule_set.virtual_network_rules = [
                VirtualNetworkRule(
                    virtual_network_resource_id=r['virtual-network-resource-id'],
                    action='Allow')  # 'Allow' is the only allowed action
                for r in self.data['virtual-network-rules']]

        if len(self.data.get('bypass', [])) > 0:
            rule_set.bypass = '******'.join(self.data['bypass'])
        else:
            rule_set.bypass = '******'

        self.client.storage_accounts.update(
            resource['resourceGroup'],
            resource['name'],
            StorageAccountUpdateParameters(network_rule_set=rule_set))
Ejemplo n.º 2
0
    def _process_resource(self, resource):
        rules = self._build_ip_rules(resource, self.data.get('ip-rules', []))

        # Build out the ruleset model to update the resource
        rule_set = NetworkRuleSet(default_action=self.data.get('default-action', 'Deny'))

        # If the user has too many rules log and skip
        if len(rules) > self.rule_limit:
            self._log.error("Skipped updating firewall for %s. "
                            "%s exceeds maximum rule count of %s." %
                            (resource['name'], len(rules), self.rule_limit))
            return

        # Add IP rules
        rule_set.ip_rules = [IPRule(ip_address_or_range=r) for r in rules]

        # Add VNET rules
        vnet_rules = self._build_vnet_rules(resource, self.data.get('virtual-network-rules', []))
        rule_set.virtual_network_rules = [
            VirtualNetworkRule(virtual_network_resource_id=r) for r in vnet_rules]

        # Configure BYPASS
        rule_set.bypass = self._build_bypass_rules(resource, self.data.get('bypass', []))

        # Update resource
        self.client.storage_accounts.update(
            resource['resourceGroup'],
            resource['name'],
            StorageAccountUpdateParameters(network_rule_set=rule_set))
Ejemplo n.º 3
0
    def create_storage_account(
        self,
        account_name: str,
        subnets: List[str] = None,
        sku: str = "Premium_LRS",
        kind: str = "FileStorage",
        access_tier: str = "Hot",
    ) -> str:
        self.logger.info("Creating storage account")

        if subnets:
            network_rules = NetworkRuleSet(
                virtual_network_rules=[
                    VirtualNetworkRule(action="Allow",
                                       virtual_network_resource_id=subnet)
                    for subnet in set(subnets)
                ],
                default_action="Deny",
                ip_rules=[],
            )

        else:
            network_rules = NetworkRuleSet(
                virtual_network_rules=[],
                default_action="Allow",
                ip_rules=[],
            )

        storage_account = self.client(
            StorageManagementClient).storage_accounts.create(
                self.rsg,
                account_name,
                parameters=StorageAccountCreateParameters(
                    sku=StorageSku(name=sku),
                    kind=kind,
                    location=self.get_location(),
                    access_tier=access_tier,
                    allow_blob_public_access=False,
                    enable_https_traffic_only=True,
                    network_rule_set=network_rules,
                ),
            )
        storage_account.result()

        access_key = (
            self.client(StorageManagementClient).storage_accounts.list_keys(
                self.rsg, account_name).keys[0].value)

        return access_key
Ejemplo n.º 4
0
    def _process_resource(self, resource):
        # Build out the ruleset model to update the resource
        rule_set = NetworkRuleSet(
            default_action=self.data.get('default-action', 'Deny'))

        # Add IP rules
        if self.data.get('ip-rules') is not None:
            existing_ip = [
                r['value'] for r in resource['properties']['networkAcls'].get(
                    'ipRules', [])
            ]
            ip_rules = self._build_ip_rules(existing_ip,
                                            self.data.get('ip-rules', []))

            # If the user has too many rules raise exception
            if len(ip_rules) > self.rule_limit:
                raise ValueError(
                    "Skipped updating firewall for %s. "
                    "%s exceeds maximum rule count of %s." %
                    (resource['name'], len(ip_rules), self.rule_limit))

            rule_set.ip_rules = [
                IPRule(ip_address_or_range=r) for r in ip_rules
            ]

        # Add VNET rules
        if self.data.get('virtual-network-rules') is not None:
            existing_vnet = \
                [r['id'] for r in
                 resource['properties']['networkAcls'].get('virtualNetworkRules', [])]
            vnet_rules = \
                self._build_vnet_rules(existing_vnet, self.data.get('virtual-network-rules', []))
            rule_set.virtual_network_rules = \
                [VirtualNetworkRule(virtual_network_resource_id=r) for r in vnet_rules]

        # Configure BYPASS
        if self.data.get('bypass-rules') is not None:
            existing_bypass = resource['properties']['networkAcls'].get(
                'bypass', '').split(',')
            rule_set.bypass = self._build_bypass_rules(
                existing_bypass, self.data.get('bypass-rules', []))

        # Update resource
        self.client.storage_accounts.update(
            resource['resourceGroup'], resource['name'],
            StorageAccountUpdateParameters(network_rule_set=rule_set))
def run_action(credentials, rule, entity, params):
    logging.info(f'Parameters are: {params}')
    vnet_group_name, vnet_name, subnet_name = params
    logging.info(f'{__file__} - ${run_action.__name__} started')
    subscription_id = entity['accountNumber']
    group_name = entity['resourceGroup']['name']
    storage_account_name = entity['name']
    logging.info(
        f'{__file__} - subscription_id : {subscription_id} - group_name : {group_name} - storage_account : {storage_account_name}'
    )

    subnet_path = '/subscriptions/' + subscription_id + '/resourceGroups/' + vnet_group_name + \
        '/providers/Microsoft.Network/virtualNetworks/' + \
        vnet_name + '/subnets/' + subnet_name

    if not subscription_id or not credentials:
        return raise_credentials_error()

    try:
        storage_client = StorageManagementClient(credentials, subscription_id)
        storage_client.storage_accounts.update(
            group_name, storage_account_name,
            StorageAccountUpdateParameters(network_rule_set=NetworkRuleSet(
                default_action='Deny',
                virtual_network_rules=[
                    VirtualNetworkRule(virtual_network_resource_id=subnet_path)
                ])))
        msg = f'Private network access was successfully configured for storage account: {storage_account_name}'
        logging.info(f'{__file__} - {msg}')
        return f'{msg}'

    except CloudError as e:
        msg = f'Unexpected error : {e.message}'
        if 'SubnetsHaveNoServiceEndpointsConfigured' in msg:
            logging.info(
                f'Unable to set private access as the VNet does not have Service Endpoints configured'
            )
        logging.info(f'{__file__} - {msg}')
        return msg
Ejemplo n.º 6
0
network_client = NetworkManagementClient(credentials, subscription_id)
resource_client = ResourceManagementClient(credentials, subscription_id)
storage_client = StorageManagementClient(credentials, subscription_id)

resource_group_params = {'location':LOCATION}
resource_client.resource_groups.create_or_update(GROUP_NAME, resource_group_params)

vnet_params = { 'location': LOCATION, 'address_space' : { 'address_prefixes': [VNET_AP] } }
async_vnet_creation = network_client.virtual_networks.create_or_update(GROUP_NAME, VNET_NAME, vnet_params)
async_vnet_creation.wait()
ep = ServiceEndpointPropertiesFormat(service='Microsoft.Storage')
ep_list = [ep]
subnet = Subnet(address_prefix = SB_AP, service_endpoints = ep_list)
async_vnet_subnet_creation = network_client.subnets.create_or_update(GROUP_NAME, VNET_NAME, SB_NAME, subnet)
async_vnet_subnet_creation.wait()
if async_vnet_subnet_creation.status() == 'Succeeded':
    sb_result = async_vnet_subnet_creation.result()
    virtual_network_resource_id = sb_result.id
    vr = VirtualNetworkRule(virtual_network_resource_id=virtual_network_resource_id)
    vnets = [vr]
    ns = NetworkRuleSet(bypass='******', virtual_network_rules=vnets, default_action='Deny')
    storage_client = StorageManagementClient(credentials, subscription_id)
    sku = Sku(name=SkuName.standard_lrs)
    st1 = StorageAccountCreateParameters(sku=sku, kind=Kind.storage, location=LOCATION, network_rule_set=ns)
    storage_async_operation = storage_client.storage_accounts.create(GROUP_NAME, STORAGE_ACCOUNT_NAME, st1, location=LOCATION)
    #stlist = storage_client.storage_accounts.list()

print("Done")