AWS Feed
Create CIS hardened Windows images using EC2 Image Builder
Many organizations today require their systems to be compliant with the CIS (Center for Internet Security) Benchmarks. Enterprises have adopted the guidelines or benchmarks drawn by CIS to maintain secure systems. Creating secure Linux or Windows Server images on the cloud and on-premises can involve manual update processes or require teams to build automation scripts to maintain images. This blog post details the process of automating the creation of CIS compliant Windows images using EC2 Image Builder.
EC2 Image Builder simplifies the building, testing, and deployment of Virtual Machine and container images for use on AWS or on-premises. Keeping Virtual Machine and container images up-to-date can be time consuming, resource intensive, and error-prone. Currently, customers either manually update and snapshot VMs or have teams that build automation scripts to maintain images. EC2 Image Builder significantly reduces the effort of keeping images up-to-date and secure by providing a simple graphical interface, built-in automation, and AWS-provided security settings. With Image Builder, there are no manual steps for updating an image nor do you have to build your own automation pipeline. EC2 Image Builder is offered at no cost, other than the cost of the underlying AWS resources used to create, store, and share the images.
Hardening is the process of applying security policies to a system and thereby, an Amazon Machine Image (AMI) with the CIS security policies in place would be a CIS hardened AMI. CIS benchmarks are a published set of recommendations that describe the security policies required to be CIS-compliant. They cover a wide range of platforms including Windows Server and Linux. For example, a few recommendations in a Windows Server environment are to:
- Have a password requirement and rotation policy.
- Set an idle timer to lock the instance if there is no activity.
- Prevent guest users from using Remote Desktop Protocol (RDP) to access the instance.
While Deploying CIS L1 hardened AMIs with EC2 Image Builder discusses about Linux AMIs, this blog post demonstrates how EC2 Image Builder can be used to publish hardened Windows 2019 AMIs. This solutions uses the following AWS services:
EC2 Image Builder provides all the necessary resources needed for publishing AMIs and that involves –
- Creating a pipeline by providing details such as a name, description, tags, and a schedule to run automated builds.
- Creating a recipe by providing a name and version, select a source operating system image, and choose components to add for building and testing. Components are the building blocks that are consumed by an image recipe or a container recipe. For example, packages for installation, security hardening steps, and tests. The selected source operating system image and components make up an image recipe.
- Defining infrastructure configuration – Image Builder launches Amazon EC2 instances in your account to customize images and run validation tests. The Infrastructure configuration settings specify infrastructure details for the instances that will run in your AWS account during the build process.
- After the build is complete and has passed all its tests, the pipeline automatically distributes the developed AMIs to the select AWS accounts and regions as defined in the distribution configuration.
More details on creating an Image Builder pipeline using the AWS console wizard can be found here.
Solution Overview and prerequisites
The objective of this pipeline is to publish CIS L1 compliant Windows 2019 AMIs and this is achieved by applying a Windows Group Policy Object(GPO) stored in an Amazon S3 bucket for creating the hardened AMIs. The workflow includes the following steps:
- Download and modify the CIS Microsoft Windows Server 2019 Benchmark Build Kit available on the Center for Internet Security website. Note: Access to the benchmarks on the CIS site requires a paid subscription.
- Upload the modified GPO file to an S3 bucket in an AWS account.
- Create a custom Image Builder component by referencing the GPO file uploaded to the S3 bucket.
- Create an IAM Instance Profile that the
- Launch the EC2 Image Builder pipeline for publishing CIS L1 hardened Windows 2019 AMIs.
Make sure to have these prerequisites checked before getting started:
- An AWS account for hosting the S3 bucket and the EC2 Image Builder Pipeline. We use the S3 bucket named image-builder-assets for demonstration purposes in this blog post. Refer to the create an S3 bucket page for more details on creating an S3 buckets.
- Download the windows Local Group Policy Object (LGPO) utility to your local Windows workstation.
- Download the latest CIS Benchmark for Windows Server 2019 Build Kit from the CIS site.
Implementation
Now that you have the prerequisites met, let’s begin with modifying the downloaded GPO file.
Creating the GPO File
This step involves modifying two files, registry.pol and GptTmpl.inf
- On your workstation, create a folder of your choice, lets say C:Utils
- Move both the CIS Benchmark build kit and the LGPO utility to C:Utils
- Unzip the benchmark file to C:UtilsServer2019v1.1.0. You should find the following folder structure in the benchmark build kit.
- To make the GPO file work with AWS EC2 instances, you need to change the GPO file to prevent it from applying the following CIS recommendations mentioned in the below table and execute the commands mentioned below the table for getting there:
Benchmark rule # | Recommendation | Value to be configured | Reason |
2.2.21 (L1) | Configure ‘Deny Access to this computer from the network’ | Guests | Does not include ‘Local account and member of Administrators group’ to allow for remote login. |
2.2.26 (L1) | Ensure ‘Deny log on through Remote Desktop Services’ is set to include ‘Guests, Local account’ | Guests | Does not include ‘Local account’ to allow for RDP login. |
2.3.1.1 (L1) | Ensure ‘Accounts: Administrator account status’ is set to ‘Disabled’ | Not Configured | Administrator account remains enabled in support of allowing login to the instance after launch. |
2.3.1.5 (L1) | Ensure ‘Accounts: Rename administrator account’ is configured | Not Configured | We have retained “Administrator” as the default administrative account for the sake of provisioning scripts that may not have knowledge of “CISAdmin” as defined in the CIS remediation kit. |
2.3.1.6 (L1) | Configure ‘Accounts: Rename guest account’ | Not Configured | Sysprep process renames this account to default of ‘Guest’. |
2.3.7.4 | Interactive logon: Message text for users attempting to log on | Not Configured | This recommendation is not configured as it causes issues with AWS Scanner. |
2.3.7.5 | Interactive logon: Message title for users attempting to log on | Not Configured | This recommendation is not configured as it causes issues with AWS Scanner. |
9.3.5 (L1) | Ensure ‘Windows Firewall: Public: Settings: Apply local firewall rules’ is set to ‘No’ | Not Configured | This recommendation is not configured as it causes issues with RDP. |
9.3.6 (L1) | Ensure ‘Windows Firewall: Public: Settings: Apply local connection security rules’ | Not Configured | This recommendation is not configured as it causes issues with RDP. |
18.2.1 (L1) | Ensure LAPS AdmPwd GPO Extension / CSE is installed (MS only) | Not Configured | LAPS is not configured by default in the AWS environment. |
18.9.58.3.9.1 (L1) | Ensure ‘Always prompt for password upon connection’ is set to ‘Enabled’ | Not Configured | This recommendation is not configured as it causes issues with RDP. |
- Parse the policy file located inside MS-L1{6B8FB17A-45D6-456D-9099-EB04F0100DE2}DomainSysvolGPOMachineregistry.pol into a text file using the command:
C:UtilsLGPO.exe /parse /m C:UtilsServer2019v1.1.0MS-L1DomainSysvolGPOMachineregistry.pol >> C:UtilsMS-L1.txt
- Open the generated MS-L1.txt file and delete the following sections:
Computer
SoftwarePoliciesMicrosoftWindows NTTerminal Services
fPromptForPassword
DWORD:1
Computer
SoftwarePoliciesMicrosoftWindowsFirewallPublicProfile
AllowLocalPolicyMerge
DWORD:0
Computer
SoftwarePoliciesMicrosoftWindowsFirewallPublicProfile
AllowLocalIPsecPolicyMerge
DWORD:0
- Save the file and convert it back to policy file using command:
C:UtilsLGPO.exe /r C:UtilsMS-L1.txt /w C:Utilsregistry.pol
- Copy the newly generated registry.pol file from C:Utils to C:UtilsServer2019v1.1.0MS-L1DomainSysvolGPOMachine. Note:This will replace the existing registry.pol file.
- Next, open C:UtilsServer2019v1.1.0MS-L1DomainSysvolGPOMachinemicrosoftwindows ntSecEditGptTmpl.inf using Notepad.
- Under the [System Access] section, delete the following lines:
NewAdministratorName = "CISADMIN"
NewGuestName = "CISGUEST"
EnableAdminAccount = 0
- Under the section [Privilege Rights], modify the values as given below:
SeDenyNetworkLogonRight = *S-1-5-32-546
SeDenyRemoteInteractiveLogonRight = *S-1-5-32-546
- Under the section [Registry Values], remove the following two lines:
MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemLegalNoticeCaption=1,"ADD TEXT HERE"
MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystemLegalNoticeText=7,ADD TEXT HERE
- Save the C:UtilsServer2019v1.1.0MS-L1DomainSysvolGPOMachinemicrosoftwindows ntSecEditGptTmpl.inf file.
- Rename the root folder C:UtilsServer2019v1.1.0 to a simpler name like C:Utilisgpos
- Compress both the C:Utilisgpos folder along with the C:UtilsLGPO.exe file and name it as C:Utiliscisbuild.zip and upload it to the image-builder-assets S3 bucket.
Create Build Component
Next step for us is to develop the build component file that details what gets to be installed on the AMI that will be created at the end of the process. For example, you can use the component definition for installing external tools like Python. To build a component, you must provide a YAML-based document, which represents the phases and steps to create the component. Create the CISL1Component following the below steps:
- Login to the AWS Console and open the EC2 Image Builder dashboard.
- Click on Components in the left pane.
- Click on Create Component.
- Choose Windows for Image Operating System (OS).
- Type a name for the Component, in this case, we will name it as CIS-Windows-2019-Build-Component.
- Type in a component version. Since it is the first version, we will choose 1.0.0
- Optionally, under KMS keys, if you have a custom KMS key to encrypt the image, you can choose that or leave as default.
- Type in a meaningful description.
- Under Definition Document, choose “Define document content” and paste the following YAML code:
name: CISLevel1Build
description: Build Component to build a CIS Level 1 Image along with additional libraries
schemaVersion: 1.0
phases:
- name: build
steps:
- name: DownloadUtilities
action: ExecutePowerShell
inputs:
commands:
- New-Item -ItemType directory -Path C:Utils
- Invoke-WebRequest -Uri "https://www.python.org/ftp/python/3.8.2/python-3.8.2-amd64.exe" -OutFile "C:Utilspython.exe"
- name: BuildKitDownload
action: S3Download
inputs:
- source: s3://image-builder-assets/cisbuild.zip
destination: C:UtilsBuildKit.zip
- name: InstallPython
action: ExecuteBinary
onFailure: Continue
inputs:
path: 'C:Utilspython.exe'
arguments:
- '/quiet'
- name: InstallGPO
action: ExecutePowerShell
inputs:
commands:
- Expand-Archive -LiteralPath C:UtilsBuildKit.Zip -DestinationPath C:Utils
- "$GPOPath=Get-ChildItem -Path C:\Utils\gpos\USER-L1 -Exclude "*.xml""
- "&"C:\Utils\LGPO.exe" /g "$GPOPath""
- "$GPOPath=Get-ChildItem -Path C:\Utils\gpos\MS-L1 -Exclude "*.xml""
- "&"C:\Utils\LGPO.exe" /g "$GPOPath""
- New-NetFirewallRule -DisplayName "WinRM Inbound for AWS Scanner" -Direction Inbound -Action Allow -EdgeTraversalPolicy Block -Protocol TCP -LocalPort 5985
- name: RebootStep
action: Reboot
onFailure: Abort
maxAttempts: 2
inputs:
delaySeconds: 60
The above template has a build phase with the following steps:
- DownloadUtilities – Executes a command to create a directory (C:Utils) and another command to download Python from the internet and save it in the created directory as python.exe. Both are executed in PowerShell.
- BuildKitDownload – Downloads the GPO archive created in the previous section from the bucket we stored it in.
- InstallPython – Installs Python in the system using the executable downloaded in the first step.
- InstallGPO – Installs the GPO files we prepared from the previous section to apply the CIS security policies. In this example, we are creating a Level 1 CIS hardened AMI.
- Note: In order to create a Level 2 CIS hardened AMIs, you need to apply User-L1, User-L2, MS-L1, MS-L2 GPOs.
- To apply the policy, we use the LGPO.exe tool and run the following command:
LGPO.exe /g "PathofGPOdirectory"
- As an example, to apply the MS-L1 GPO, the command would be as follows:
LGPO.exe /g "C:UtilsgposMS-L1DomainSysvol"
- The last command opens the 5985 port in the firewall to allow AWS Scanner inbound connection. This is a CIS recommendation.
- RebootStep – Reboots the instance after applying the security policies. A reboot is necessary to apply the policies.
Note: If you need to run any tests/validation you need to include another phase to run the test scripts. Guidelines on that can be found here.
Create an instance profile role for the Image Pipeline
Image Builder launches Amazon EC2 instances in your account to customize images and run validation tests. The Infrastructure configuration settings specify infrastructure details for the instances that will run in your AWS account during the build process. In this step, you will create an IAM Role to attach to the instance that the Image Pipeline will use to create an image. Create the IAM Instance Profile following the below steps:
- Open the AWS Identity and Access Management (AWS IAM) console and click on Roles on the left pane.
- Click on Create Role.
- Choose AWS service for trusted entity and choose EC2 and click Next.
- Attach the following policies: AmazonEC2RoleforSSM, AmazonS3ReadOnlyAccess, EC2InstanceProfileForImageBuilder and click Next.
- Optionally, add tags and click Next
- Give the role a name and description and review if all the required policies are attached. In this case, we will name the IAM Instance Profile as CIS-Windows-2019-Instance-Profile
- Click Create role.
Create Image Builder Pipeline
In this step, you create the image pipeline which will produce the desired AMI as an output. Image Builder image pipelines provide an automation framework for creating and maintaining custom AMIs and container images. Pipelines deliver the following functionality:
- Assemble the source image, components for building and testing, infrastructure configuration, and distribution settings.
- Facilitate scheduling for automated maintenance processes using the Schedule builder in the console wizard, or entering cron expressions for recurring updates to your images.
- Enable change detection for the source image and components, to automatically skip scheduled builds when there are no changes.
To create an Image Builder pipeline, perform the following steps:
- Open the EC2 Image Builder console and choose create Image Pipeline.
- Select Windows for the Image Operating System.
- Under Select Image, choose Select Managed Images and browse for the latest Windows Server 2019 English Full Base x86 image.
- Under Build components, choose the Build component CIS-Windows-2019-Build-Component created in the previous section.
- Optionally, under Tests, if you have a test component created, you can select that.
- Click Next.
- Under Pipeline details, give the pipeline a name and a description. For IAM role, select the role CIS-Windows-2019-Instance-Profile that was created in the previous section.
- Under Build Schedule, you can choose how frequently you want to create an image through this pipeline based on an update schedule. You can select Manual for now.
- (Optional) Under Infrastructure Settings, select an instance type to customize your image for that type, an Amazon SNS topic to get alerts from as well as Amazon VPC settings. If you would like to troubleshoot in case the pipeline faces any errors, you can uncheck “Terminate Instance on failure” and choose an EC2 Key Pair to access the instance via Remote Desktop Protocol (RDP). You may wish to store the Logs in an S3 bucket as well. Note: Make sure the chosen VPC has outbound access to the internet in case you are downloading anything from the web as part of the custom component definition.
- Click Next.
- Under Configure additional settings, you can optionally choose to attach any licenses that you own through AWS License Manager to the AMI.
- Under Output AMI, give a name and optional tags.
- Under AMI distribution settings, choose the regions or AWS accounts you want to distribute the image to. By default, your current region is included. Click on Review.
- Review the details and click Create Pipeline.
- Since we have chosen Manual under the Build Schedule, manually trigger the Image Builder pipeline for kicking off the AMI creation process. On successful run, Image Builder pipeline will create the image and the output image can be found under Images on the left pane of the EC2 Image Builder console.
- To troubleshoot any issues, the reasons for failure can be found by clicking on the Image Pipeline you created and view the corresponding output image with the Status as Failed.
Cleanup
Following the above detailed step-by-step process creates EC2 Image Builder Pipeline, Custom Component and an IAM Instance Profile. While none of these resources have any costs associated with them, you are charged for the runtime of the EC2 instance used during the AMI built process and the EBS volume costs associated with the size of the AMI. Make sure to clear the AMIs when not needed for avoiding any unwanted costs.
Conclusion
This blog post demonstrated how you can use EC2 Image Builder to create a CIS L1 hardened Windows 2019 Image in an automated fashion. Additionally, this post also demonstrated on how you can use build components to install any dependencies or executables from different sources like the internet or from an Amazon S3 bucket. Feel free to test this solution in your AWS accounts and provide feedback.