> ## Documentation Index
> Fetch the complete documentation index at: https://cloudanix.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Patch Installation Should Be Done On Systems Manager

### More Info:

This rule checks if the compliance status of the AWS Systems Manager patch compliance is COMPLIANT or NON\_COMPLIANT after the patch installation on the instance. The rule is compliant if the field status is COMPLIANT.

### Risk Level

Medium

### Address

Security

### Compliance Standards

CBP,RBI\_MD\_ITF,RBI\_UCB

### Triage and Remediation

<Tabs>
  <Tab title="Remediation">
    ### Remediation

    <AccordionGroup>
      <Accordion title="Using Console" defaultOpen="true">
        To remediate the misconfiguration of patch installation not being done on Systems Manager for AWS EC2 instances, follow these steps using the AWS Management Console:

        1. **Access AWS Systems Manager Console**:
           * Log in to your AWS account and navigate to the AWS Management Console.
           * Go to the Systems Manager service by typing "Systems Manager" in the search bar and selecting it.

        2. **Create a Patch Baseline**:
           * In the Systems Manager console, navigate to the left-hand menu and click on "Patch Manager" under the "Actions" section.
           * Click on "Patch Baselines" in the left-hand menu and then click on the "Create patch baseline" button.
           * Enter a name and description for the patch baseline, and configure the patch rules according to your requirements.
           * Click on the "Create patch baseline" button to save the configuration.

        3. **Create a Patch Group**:
           * In the Systems Manager console, navigate to the left-hand menu and click on "Patch Manager" under the "Actions" section.
           * Click on "Patch Groups" in the left-hand menu and then click on the "Create patch group" button.
           * Enter a name for the patch group and select the instances that you want to include in this group.
           * Click on the "Create patch group" button to save the configuration.

        4. **Schedule Patching**:
           * In the Systems Manager console, navigate to the left-hand menu and click on "Patch Manager" under the "Actions" section.
           * Click on "Patch Manager" in the left-hand menu and then click on the "Patch now" button.
           * Select the patch baseline and patch group that you created in the previous steps.
           * Configure the schedule for patching according to your requirements and click on the "Patch now" button to initiate the patching process.

        5. **Monitor Patching Progress**:
           * In the Systems Manager console, navigate to the left-hand menu and click on "Patch Manager" under the "Actions" section.
           * Click on "Patch Manager" in the left-hand menu to view the patching status of your instances.
           * Monitor the progress of patch installation and ensure that all instances are successfully patched.

        By following these steps, you can remediate the misconfiguration of patch installation not being done on Systems Manager for AWS EC2 instances and ensure that your instances are up to date with the latest patches and security updates.

        #
      </Accordion>

      <Accordion title="Using CLI">
        To remediate the misconfiguration of patch installation not being done on Systems Manager for AWS EC2 instances using AWS CLI, follow these steps:

        1. Install and configure AWS CLI:
           * If you haven't already installed the AWS CLI, you can follow the instructions here: [https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-quickstart.html](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-quickstart.html)

        2. Identify the EC2 instances that need patching:
           * You can list all EC2 instances in your AWS account using the following AWS CLI command:
             ```
             aws ec2 describe-instances --query 'Reservations[*].Instances[*].[InstanceId, State.Name]' --output table
             ```

        3. Attach an IAM role with the necessary permissions to the EC2 instances:
           * Create an IAM role with the necessary permissions for Systems Manager. You can create a role with the `AmazonSSMManagedInstanceCore` managed policy attached.
           * Attach this IAM role to the EC2 instances that need patching. You can do this by modifying the instance attributes using the AWS CLI:
             ```
             aws ec2 modify-instance-attribute --instance-id <instance-id> --iam-instance-profile Name=<role-name>
             ```

        4. Install the SSM Agent on the EC2 instances:
           * The Systems Manager requires the SSM Agent to be installed on the EC2 instances. You can automate the installation process using AWS Systems Manager Run Command or manually install the agent on each instance. Here is an example of how to install the agent using AWS Systems Manager Run Command:
             ```
             aws ssm send-command --document-name "AWS-InstallAWSPatchInstallUnifiedAgent" --targets "Key=InstanceIds,Values=<instance-id>" --parameters '{"sourceType":["github"],"sourceInfo":["aws-quickstart/quickstart-awspatchbaseline"],"packageName":["awspatchbaseline"],"version":["latest"]}' --timeout-seconds 600 --max-concurrency "50" --max-errors "0" --output-s3-bucket-name "<bucket-name>" --output-s3-key-prefix "<prefix>"
             ```

        5. Configure Patch Baseline in Systems Manager:
           * Create a patch baseline in AWS Systems Manager to define the patching schedule and rules for your EC2 instances. You can do this using the AWS Management Console or AWS CLI.
           * Here is an example of how to create a patch baseline using AWS CLI:
             ```
             aws ssm create-patch-baseline --name "MyPatchBaseline" --approval-rules "PatchRules=[{PatchFilterGroup:{PatchFilters=[{Key=PRODUCT,Values=[WindowsServer2019]},{Key=CLASSIFICATION,Values=[Critical,SecurityUpdates]}],PatchFilterGroupType=and}],ApproveAfterDays=7,ComplianceLevel=CRITICAL}"
             ```

        6. Schedule patching for EC2 instances:
           * You can schedule patching for your EC2 instances by creating a maintenance window in AWS Systems Manager and associating it with the patch baseline you created. You can do this using the AWS Management Console or AWS CLI.
           * Here is an example of how to create a maintenance window using AWS CLI:
             ```
             aws ssm create-maintenance-window --name "MyMaintenanceWindow" --schedule "CronExpression=<cron-expression>" --duration 3 --cutoff 1 --allow-unassociated-targets
             ```

        By following these steps, you can remediate the misconfiguration of patch installation not being done on Systems Manager for AWS EC2 instances using AWS CLI.
      </Accordion>

      <Accordion title="Using Python">
        To remediate the misconfiguration of not having patch installations done on AWS EC2 instances using Systems Manager, you can use the following Python script to automate the process:

        1. Install the necessary Python libraries:

        ```bash theme={null}
        pip install boto3
        ```

        2. Use the following Python script to create a patch baseline and schedule patch installations for your EC2 instances:

        ```python theme={null}
        import boto3

        # Initialize the boto3 client
        ssm = boto3.client('ssm')

        # Define the EC2 instance IDs for which you want to schedule patch installations
        instance_ids = ['INSTANCE_ID_1', 'INSTANCE_ID_2']

        # Create a patch baseline
        response = ssm.create_patch_baseline(
            Name='MyPatchBaseline',
            OperatingSystem='WINDOWS',  # Change this to 'AMAZON_LINUX' if using Amazon Linux
            ApprovalRules={
                'PatchRules': [
                    {
                        'PatchFilterGroup': {
                            'PatchFilters': [
                                {
                                    'Key': 'CLASSIFICATION',
                                    'Values': ['Security']
                                }
                            ]
                        },
                        'ApproveAfterDays': 0
                    }
                ]
            }
        )

        # Get the patch baseline ID
        baseline_id = response['BaselineId']

        # Create a patch group for the EC2 instances
        response = ssm.register_target_with_maintenance_window(
            WindowId='MAINTENANCE_WINDOW_ID',
            ResourceType='INSTANCE',
            Targets=[
                {
                    'Key': 'InstanceIds',
                    'Values': instance_ids
                }
            ],
            OwnerInformation='Patch Group'
        )

        # Get the patch group ID
        patch_group_id = response['WindowTargetId']

        # Create a maintenance window task to install patches
        response = ssm.register_task_with_maintenance_window(
            WindowId='MAINTENANCE_WINDOW_ID',
            Targets=[
                {
                    'Key': 'WindowTargetIds',
                    'Values': [patch_group_id]
                }
            ],
            TaskArn='AWS-RunPatchBaseline',
            TaskType='RUN_COMMAND',
            Priority=1,
            ServiceRoleArn='MAINTENANCE_WINDOW_ROLE_ARN',
            TaskInvocationParameters={
                'MaintenanceWindowRunCommandParameters': {
                    'DocumentHash': 'DOCUMENT_HASH',
                    'DocumentHashType': 'Sha256',
                    'Parameters': {
                        'Operation': ['Install'],
                        'BaselineOverride': [baseline_id]
                    }
                }
            }
        )

        # Get the maintenance window task ID
        task_id = response['WindowTaskId']

        print(f'Patch installations scheduled for EC2 instances {instance_ids} using Systems Manager with maintenance window task ID {task_id}')
        ```

        3. Replace the following placeholders in the script:
           * `INSTANCE_ID_1`, `INSTANCE_ID_2`: Replace these with the actual EC2 instance IDs for which you want to schedule patch installations.
           * `MAINTENANCE_WINDOW_ID`: Replace this with the ID of the maintenance window in which you want to schedule the patch installations.
           * `MAINTENANCE_WINDOW_ROLE_ARN`: Replace this with the ARN of the IAM role that has permissions to run Systems Manager tasks in the maintenance window.
           * `DOCUMENT_HASH`: Replace this with the hash of the AWS-RunPatchBaseline document. You can get this from the Systems Manager Documents page in the AWS Management Console.

        4. Run the Python script to create a patch baseline, register the EC2 instances in a patch group, and schedule patch installations using Systems Manager.

        This script will help you automate the process of scheduling patch installations for your EC2 instances in AWS using Systems Manager.
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>
