Skip to content

Commit

Permalink
PLA-21661 - Remediation job to enable logging for Key Vault (#42)
Browse files Browse the repository at this point in the history
  • Loading branch information
kshrutik authored Jan 11, 2021
1 parent 6cbdef4 commit c5aae32
Show file tree
Hide file tree
Showing 9 changed files with 554 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
# Enable Logging For Keyvault

This job enables Key Vault Logging.

### Applicable Rule

##### Rule ID:
5c8c26687a550e1fb6560c72

##### Rule Name:
Logging For Keyvault Enabled

## Getting Started
### Prerequisites
The provided Azure service principal must have the following permissions:
`Microsoft.Storage/storageAccounts/read`
`Microsoft.Storage/storageAccounts/write`
`Microsoft.Insights/DiagnosticSettings/Write`

A sample role with requisite permissions can be found [here](minimum_permissions.json)

More information about already builtin roles and permissions can be found [here](https://docs.microsoft.com/en-us/azure/role-based-access-control/built-in-roles)

### Running the script
You may run this script using following commands:

```shell script
pip install -r requirements.txt
python3 azure_key_vault_logging_for_keyvault_enabled.py
```
## Running the tests
You may run test using following command under vss-remediation-worker-job-code-python directory:

```shell script
pip install -r requirements-dev.txt
python3 -m pytest test
```
## Deployment
Provision a Virtual Machine Create an EC2 instance to use for the worker. The minimum required specifications are 128 MB memory and 1/2 Core CPU.
Setup Docker Install Docker on the newly provisioned EC2 instance. You can refer to the [docs here](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/docker-basics.html) for more information.
Deploy the worker image SSH into the EC2 instance and run the command below to deploy the worker image:
```shell script
docker run --rm -it --name worker \
-e VSS_CLIENT_ID={ENTER CLIENT ID}
-e VSS_CLIENT_SECRET={ENTER CLIENT SECRET} \
vmware/vss-remediation-worker:latest-python
```
## Contributing
The Secure State team welcomes contributions from the community. If you wish to contribute code and you have not signed our contributor license agreement (CLA), our bot will update the issue when you open a Pull Request. For any questions about the CLA process, please refer to our [FAQ](https://cla.vmware.com/faq).

All contributions to this repository must be signed as described on that page. Your signature certifies that you wrote the patch or have the right to pass it on as an open-source patch.

For more detailed information, refer to [CONTRIBUTING.md](../../../CONTRIBUTING.md).
## Versioning
We use SemVer for versioning. For the versions available, see the tags on this repository.

## Authors
* **VMware Secure State** - *Initial work*
See also the list of [contributors](https://github.com/vmware-samples/secure-state-remediation-jobs/graphs/contributors) who participated in this project.

## License
This project is licensed under the Apache License - see the [LICENSE](https://github.com/vmware-samples/secure-state-remediation-jobs/blob/master/LICENSE.txt) file for details
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,206 @@
# Copyright (c) 2020 VMware Inc.
#
# 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.

import json
import os
import sys
import logging

from azure.identity import ClientSecretCredential
from azure.mgmt.keyvault import KeyVaultManagementClient
from azure.mgmt.monitor import MonitorClient
from azure.mgmt.storage import StorageManagementClient
from azure.mgmt.storage.models import (
StorageAccountCreateParameters,
NetworkRuleSet,
Sku,
SkuName,
SkuTier,
DefaultAction,
)
from azure.mgmt.monitor.models import (
DiagnosticSettingsResource,
LogSettings,
RetentionPolicy,
)

logging.basicConfig(level=logging.INFO)


def generate_name(prefix):
prefix = "".join(i for i in prefix if i.islower() or i.isdigit())
if len(prefix) >= 12:
prefix = str(prefix[:11])
result_str = prefix + "keyvaultlogs"
return result_str


def create_storage_account(
resource_group_name, name, region, storage_client,
):
create_params = StorageAccountCreateParameters(
location=region,
sku=Sku(name=SkuName.STANDARD_LRS, tier=SkuTier.STANDARD),
kind="StorageV2",
enable_https_traffic_only=True,
network_rule_set=NetworkRuleSet(default_action=DefaultAction.DENY),
)
poller = storage_client.storage_accounts.begin_create(
resource_group_name=resource_group_name,
account_name=name,
parameters=create_params,
)
return poller.result()


class EnableKeyVaultLogging(object):
def parse(self, payload):
"""Parse payload received from Remediation Service.
:param payload: JSON string containing parameters received from the remediation service.
:type payload: str.
:returns: Dictionary of parsed parameters
:rtype: dict
:raises: KeyError, JSONDecodeError
"""
remediation_entry = json.loads(payload)

object_id = remediation_entry["notificationInfo"]["FindingInfo"]["ObjectId"]

region = remediation_entry["notificationInfo"]["FindingInfo"]["Region"]

object_chain = remediation_entry["notificationInfo"]["FindingInfo"][
"ObjectChain"
]
object_chain_dict = json.loads(object_chain)
subscription_id = object_chain_dict["cloudAccountId"]

properties = object_chain_dict["properties"]
resource_group_name = ""

for property in properties:
if property["name"] == "ResourceGroup" and property["type"] == "string":
resource_group_name = property["stringV"]
break

logging.info("parsed params")
logging.info(f" resource_group_name: {resource_group_name}")
logging.info(f" account_name: {object_id}")
logging.info(f" subscription_id: {subscription_id}")
logging.info(f" region: {region}")

return {
"resource_group_name": resource_group_name,
"key_vault_name": object_id,
"subscription_id": subscription_id,
"region": region,
}

def remediate(
self,
keyvault_client,
monitor_client,
storage_client,
resource_group_name,
key_vault_name,
region,
):
"""Enable key vault logging
:param keyvault_client: Instance of the Azure KeyVaultManagementClient.
:param storage_client: Instance of the Azure StorageManagementClient.
:param monitor_client: Instance of the Azure MonitorClient.
:param resource_group_name: The name of the resource group to which the storage account belongs.
:param key_vault_name: The name of the key vault.
:param region: The region in which the key vault is present.
:type resource_group_name: str.
:type key_vault_name: str.
:type region: str.
:returns: Integer signaling success or failure
:rtype: int
:raises: msrestazure.azure_exceptions.CloudError
"""
key_vault = keyvault_client.vaults.get(
resource_group_name=resource_group_name, vault_name=key_vault_name,
)
try:
stg_name = generate_name(key_vault_name)
logging.info(" Creating a Storage Account")
logging.info(" executing client_storage.storage_accounts.begin_create")
logging.info(f" resource_group_name={resource_group_name}")
logging.info(f" account_name={stg_name}")
stg_account = create_storage_account(
resource_group_name, stg_name, region, storage_client
)
log = LogSettings(
category="AuditEvent",
enabled=True,
retention_policy=RetentionPolicy(enabled=True, days=180),
)

logging.info(" Creating a Diagnostic setting for key vault logs")
logging.info(
" executing monitor_client.diagnostic_settings.create_or_update"
)
logging.info(f" resource_uri={key_vault.id}")
logging.info(f" name={key_vault_name}")

monitor_client.diagnostic_settings.create_or_update(
resource_uri=key_vault.id,
name=key_vault_name,
parameters=DiagnosticSettingsResource(
storage_account_id=stg_account.id, logs=[log],
),
)
except Exception as e:
logging.error(f"{str(e)}")
raise

return 0

def run(self, args):
"""Run the remediation job.
:param args: List of arguments provided to the job.
:type args: list.
:returns: int
"""
params = self.parse(args[1])

credentials = ClientSecretCredential(
client_id=os.environ.get("AZURE_CLIENT_ID"),
client_secret=os.environ.get("AZURE_CLIENT_SECRET"),
tenant_id=os.environ.get("AZURE_TENANT_ID"),
)
credentials_stg = ClientSecretCredential(
client_id=os.environ.get("AZURE_CLIENT_ID"),
client_secret=os.environ.get("AZURE_CLIENT_SECRET"),
tenant_id=os.environ.get("AZURE_TENANT_ID"),
)
storage_client = StorageManagementClient(
credentials_stg, params["subscription_id"]
)
keyvault_client = KeyVaultManagementClient(
credentials, params["subscription_id"]
)
monitor_client = MonitorClient(credentials, params["subscription_id"])
return self.remediate(
keyvault_client,
monitor_client,
storage_client,
params["resource_group_name"],
params["key_vault_name"],
params["region"],
)


if __name__ == "__main__":
sys.exit(EnableKeyVaultLogging().run(sys.argv))
Loading

0 comments on commit c5aae32

Please sign in to comment.