AWS Builder Center
Building zero trust on AWS in five hands-on parts

Building zero trust on AWS in five hands-on parts

The AWS resources and CLI commands for a zero trust setup: workload identity, service-to-service auth, data paths, user access, and detection.

Cloud Engineer

What this guide covers

Zero trust drops the assumption that a request is safe because it comes from inside the network. Every request has to prove who is calling and whether that caller may do the thing it asks for.
This guide skips the theory and lists what you create on AWS: which service, which resource, and which CLI command. The setup is split into five parts.
  • Part 1 verifies servers outside AWS with certificates
  • Part 2 authorizes every service-to-service call
  • Part 3 narrows the network path to data
The last two cover people and the record of everything.
  • Part 4 checks user access to an application without a VPN
  • Part 5 records activity and detects misuse
One caveat before the commands. The AWS CLI syntax in this guide was checked against the official documentation and the built-in help of AWS CLI 2.38.4. The commands were not run against a live account. The only steps that were executed are the openssl commands in part 1. Each "What to check" list describes the behavior the documentation says you should see.

The overall layout

Each part answers a different question about a request.
  • Part 1 asks which server is calling, using AWS IAM Roles Anywhere
  • Part 2 asks whether this service may call that service, using Amazon VPC Lattice and Amazon Verified Permissions
  • Part 3 asks which network path the request took, using a VPC endpoint and an Amazon S3 bucket policy
  • Part 4 asks which person is calling, using AWS Verified Access and AWS IAM Identity Center
  • Part 5 keeps the record, using AWS CloudTrail, Amazon GuardDuty, and AWS Security Hub CSPM
The parts are mostly independent, so you can build only the ones you need. The one exception is that the checks in part 3 use the role zt-client-role from part 2. Resources that take a name start with zt-. Resources that only have an ID are kept in shell variables and used again during cleanup.




Prerequisites

  • A terminal with AWS CLI v2, jq, and openssl
  • A VPC in the Tokyo Region (ap-northeast-1) with a private subnet and an Amazon EC2 instance in it
  • An IAM role with administrator-level permissions
The commands use these variables.
export AWS_REGION=ap-northeast-1
ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
VPC_ID=vpc-xxxxxxxx # replace with your VPC ID

Resources that cost money

Some resources are billed by the hour. The rates below come from the US East pricing pages. Tokyo rates are not confirmed here.
  • Amazon VPC Lattice costs $0.025 per service per hour
  • AWS Verified Access costs $0.27 per application per hour, rounded up to the full hour
  • Amazon Verified Permissions costs $0.000005 per authorization request
Amazon VPC Lattice and AWS Verified Access also charge for data processed and, for VPC Lattice, for requests.
AWS Verified Access is the expensive one. Delete part 4 as soon as you finish checking it.

Part 1: verify servers outside AWS with certificates

An access key on an on-premises server has no expiry. If it leaks, it keeps working. With AWS IAM Roles Anywhere, the server presents an X.509 certificate and receives temporary credentials.
You create four things.
  • A private certificate authority, built with openssl
  • A trust anchor named zt-anchor, which registers the CA you trust
  • An IAM role named zt-workload-role
  • A profile named zt-profile, which lists the roles a workload may assume



Create the CA and the server certificate

AWS Private Certificate Authority also works here, but it has a monthly fee, so this guide uses openssl.
# Certificate authority
openssl genrsa -out ca.key 4096
openssl req -new -key ca.key -subj "/CN=zt-root-ca" -out ca.csr
printf "basicConstraints=critical,CA:TRUE\nkeyUsage=critical,keyCertSign,cRLSign\n" > ca.ext
openssl x509 -req -in ca.csr -signkey ca.key -sha256 -days 365 -extfile ca.ext -out ca.pem

# Server certificate (common name server01)
openssl genrsa -out server01.key 2048
openssl req -new -key server01.key -subj "/CN=server01" -out server01.csr
printf "basicConstraints=CA:FALSE\nkeyUsage=critical,digitalSignature\n" > server01.ext
openssl x509 -req -in server01.csr -CA ca.pem -CAkey ca.key -CAcreateserial \
-sha256 -days 30 -extfile server01.ext -out server01.pem
The extensions are there for a reason. AWS IAM Roles Anywhere requires the following.
  • The CA certificate has basic constraints CA:TRUE and a key usage that includes certificate signing
  • The server certificate is X.509v3 and its key usage includes digital signature
  • The signing algorithm is SHA256 or stronger, and MD5 and SHA1 are rejected
These commands were run with OpenSSL 4.0.3 and produce certificates that meet those conditions.

Create the trust anchor

Register the CA certificate. Passing a PEM as a command-line argument gets messy because of the line breaks, so build a JSON file with jq.
jq -n --rawfile cert ca.pem \
'{sourceType:"CERTIFICATE_BUNDLE",sourceData:{x509CertificateData:$cert}}' > anchor-source.json

TA_ARN=$(aws rolesanywhere create-trust-anchor --name zt-anchor --enabled \
--source file://anchor-source.json \
--query trustAnchor.trustAnchorArn --output text)

Create the role

The trust policy checks both the certificate's common name and the trust anchor.
cat > trust-policy.json <<EOF
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": {"Service": "rolesanywhere.amazonaws.com"},
"Action": ["sts:AssumeRole", "sts:TagSession", "sts:SetSourceIdentity"],
"Condition": {
"StringEquals": {"aws:PrincipalTag/x509Subject/CN": "server01"},
"ArnEquals": {"aws:SourceArn": "$TA_ARN"}
}
}]
}
EOF

aws iam create-role --role-name zt-workload-role \
--assume-role-policy-document file://trust-policy.json
aws iam attach-role-policy --role-name zt-workload-role \
--policy-arn arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess
The two conditions do different jobs. The aws:SourceArn condition limits the role to certificates from the CA registered in zt-anchor. The trust boundary of AWS IAM Roles Anywhere is the account, so without that condition a certificate from any trust anchor in the account can assume this role. The common name condition excludes other certificates issued by the same CA.

Create the profile

PROFILE_ARN=$(aws rolesanywhere create-profile --name zt-profile --enabled \
--role-arns arn:aws:iam::$ACCOUNT_ID:role/zt-workload-role \
--query profile.profileArn --output text)

Configure the server

Put the credential helper (aws_signing_helper) on the server. The download links are on the documentation page "Get temporary security credentials from IAM Roles Anywhere".
Add a profile to the AWS CLI config file that calls the helper. Use absolute paths so the profile works from any directory. This example keeps the files in /opt/zt.
[profile zt-server01]
region = ap-northeast-1
credential_process = /opt/zt/aws_signing_helper credential-process --certificate /opt/zt/server01.pem --private-key /opt/zt/server01.key --trust-anchor-arn <value of TA_ARN> --profile-arn <value of PROFILE_ARN> --role-arn arn:aws:iam::<account ID>:role/zt-workload-role

What to check

aws sts get-caller-identity --profile zt-server01
  • The command returns the ARN of a session that assumed zt-workload-role
  • A certificate with the common name server02 is refused
  • The session duration can be set between 15 minutes and 12 hours
To revoke a certificate, import a certificate revocation list created by your CA (crl.pem here). How you generate the list depends on how you run the CA, so this guide does not cover it.
aws rolesanywhere import-crl --name zt-crl --enabled \
--crl-data fileb://crl.pem --trust-anchor-arn $TA_ARN
AWS IAM Roles Anywhere does not check the expiry date of an imported list, so import it again every time your CA publishes an update. There is also a setting that downloads the list from the distribution point written in the certificate.

Part 2: authorize every service-to-service call

Being in the same VPC should not be enough to call a service. Amazon VPC Lattice decides which role may call the service. Amazon Verified Permissions decides, inside the application, whether the requested operation is allowed.
You create four things.
  • A policy store, which holds the Cedar schema and policies
  • An AWS Lambda function named zt-orders-fn, the service being called
  • A service network named zt-network and a service named zt-orders
  • An IAM role named zt-client-role for the caller




Create the policy store and schema

Cedar is a language for writing authorization rules. Start by defining the types of callers, actions, and resources in a schema.
STORE_ID=$(aws verifiedpermissions create-policy-store \
--validation-settings mode=STRICT \
--query policyStoreId --output text)

cat > schema.json <<'EOF'
{
"ZeroTrust": {
"entityTypes": {"Caller": {}, "Order": {}},
"actions": {
"ReadOrder": {"appliesTo": {"principalTypes": ["Caller"], "resourceTypes": ["Order"]}},
"UpdateOrder": {"appliesTo": {"principalTypes": ["Caller"], "resourceTypes": ["Order"]}}
}
}
}
EOF

jq -n --rawfile s schema.json '{cedarJson:$s}' > schema-def.json
aws verifiedpermissions put-schema --policy-store-id $STORE_ID \
--definition file://schema-def.json

Create the Cedar policies

Create one permit and one forbid.
cat > permit.cedar <<'EOF'
permit(
principal == ZeroTrust::Caller::"zt-client-role",
action in [ZeroTrust::Action::"ReadOrder", ZeroTrust::Action::"UpdateOrder"],
resource
);
EOF

cat > forbid.cedar <<'EOF'
forbid(
principal,
action == ZeroTrust::Action::"UpdateOrder",
resource == ZeroTrust::Order::"1001"
);
EOF

for f in permit forbid; do
jq -n --rawfile p $f.cedar '{static:{statement:$p}}' > $f-def.json
aws verifiedpermissions create-policy --policy-store-id $STORE_ID \
--definition file://$f-def.json
done
You can already test decisions from the CLI.
aws verifiedpermissions is-authorized --policy-store-id $STORE_ID \
--principal entityType=ZeroTrust::Caller,entityId=zt-client-role \
--action actionType=ZeroTrust::Action,actionId=UpdateOrder \
--resource entityType=ZeroTrust::Order,entityId=1001
  • Updating order 1001 returns DENY, because forbid wins over permit
  • Updating order 1002 returns ALLOW
  • A caller that no policy mentions gets DENY, because deny is the default

Create the Lambda function

Amazon VPC Lattice puts the ARN of the authenticated caller into the event it sends to the function. The function extracts the role name and asks the policy store for a decision.
# app.py
import json, os, boto3

avp = boto3.client("verifiedpermissions")
STORE_ID = os.environ["POLICY_STORE_ID"]

def handler(event, context):
principal = event["requestContext"]["identity"].get("principal", "")
# Example: arn:aws:iam::123456789012:assumed-role/zt-client-role/i-0123...
caller = principal.split("/")[1] if "assumed-role/" in principal else "anonymous"
action = "ReadOrder" if event["method"] == "GET" else "UpdateOrder"
order_id = event["path"].split("?")[0].rstrip("/").split("/")[-1]

decision = avp.is_authorized(
policyStoreId=STORE_ID,
principal={"entityType": "ZeroTrust::Caller", "entityId": caller},
action={"actionType": "ZeroTrust::Action", "actionId": action},
resource={"entityType": "ZeroTrust::Order", "entityId": order_id},
)["decision"]

return {
"isBase64Encoded": False,
"statusCode": 200 if decision == "ALLOW" else 403,
"headers": {"Content-Type": "application/json"},
"body": json.dumps({"caller": caller, "action": action, "decision": decision}),
}
The execution role needs permission to write logs and to call the authorization API. A new role can take a few seconds to propagate, so if creating the function fails, wait and run it again.
cat > lambda-trust.json <<'EOF'
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Principal":{"Service":"lambda.amazonaws.com"},"Action":"sts:AssumeRole"}]}
EOF
aws iam create-role --role-name zt-orders-fn-role \
--assume-role-policy-document file://lambda-trust.json
aws iam attach-role-policy --role-name zt-orders-fn-role \
--policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole

cat > avp-policy.json <<EOF
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Action":"verifiedpermissions:IsAuthorized",
"Resource":"arn:aws:verifiedpermissions::$ACCOUNT_ID:policy-store/$STORE_ID"}]}
EOF
aws iam put-role-policy --role-name zt-orders-fn-role \
--policy-name zt-avp --policy-document file://avp-policy.json

zip fn.zip app.py
FN_ARN=$(aws lambda create-function --function-name zt-orders-fn \
--runtime python3.13 --handler app.handler \
--role arn:aws:iam::$ACCOUNT_ID:role/zt-orders-fn-role \
--zip-file fileb://fn.zip \
--environment "Variables={POLICY_STORE_ID=$STORE_ID}" \
--query FunctionArn --output text)

Create the service and the service network

Register the Lambda function in a target group and forward to it from the service listener. Use event structure V2, which includes the caller's identity.
TG_ID=$(aws vpc-lattice create-target-group --name zt-orders-tg --type LAMBDA \
--config lambdaEventStructureVersion=V2 --query id --output text)
aws vpc-lattice register-targets --target-group-identifier $TG_ID \
--targets id=$FN_ARN

SVC_ID=$(aws vpc-lattice create-service --name zt-orders --auth-type AWS_IAM \
--query id --output text)

cat > listener-config.json <<EOF
{"forward":{"targetGroups":[{"targetGroupIdentifier":"$TG_ID","weight":100}]}}
EOF
aws vpc-lattice create-listener --service-identifier $SVC_ID --name https-443 \
--protocol HTTPS --port 443 --default-action file://listener-config.json

SN_ID=$(aws vpc-lattice create-service-network --name zt-network --auth-type AWS_IAM \
--query id --output text)
aws vpc-lattice create-service-network-service-association \
--service-identifier $SVC_ID --service-network-identifier $SN_ID
aws vpc-lattice create-service-network-vpc-association \
--service-network-identifier $SN_ID --vpc-identifier $VPC_ID
According to the documentation, registering a Lambda function through the CLI adds the permission that lets Amazon VPC Lattice invoke it.

Create the caller's role

Create zt-client-role for the calling EC2 instance. According to the documentation, authorization succeeds only when both the auth policy in the next section and the caller's IAM policy have an explicit allow.
cat > ec2-trust.json <<'EOF'
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Principal":{"Service":"ec2.amazonaws.com"},"Action":"sts:AssumeRole"}]}
EOF
aws iam create-role --role-name zt-client-role \
--assume-role-policy-document file://ec2-trust.json

cat > client-policy.json <<'EOF'
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Action":"vpc-lattice-svcs:Invoke","Resource":"*"}]}
EOF
aws iam put-role-policy --role-name zt-client-role \
--policy-name zt-invoke --policy-document file://client-policy.json

aws iam create-instance-profile --instance-profile-name zt-client-profile
aws iam add-role-to-instance-profile --instance-profile-name zt-client-profile \
--role-name zt-client-role
aws ec2 associate-iam-instance-profile --instance-id i-xxxxxxxx \
--iam-instance-profile Name=zt-client-profile
Replace i-xxxxxxxx with the ID of the EC2 instance that makes the calls.

Set the auth policies

Auth policies go in two places. The one on the service network rejects every unsigned request.
cat > sn-auth.json <<'EOF'
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": "*",
"Action": "vpc-lattice-svcs:Invoke",
"Resource": "*",
"Condition": {"StringNotEquals": {"aws:PrincipalType": "Anonymous"}}
}]
}
EOF
aws vpc-lattice put-auth-policy --resource-identifier $SN_ID \
--policy "$(jq -c . sn-auth.json)"
The one on the service limits callers to zt-client-role.
SVC_ARN=$(aws vpc-lattice get-service --service-identifier $SVC_ID --query arn --output text)
cat > svc-auth.json <<EOF
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": {"AWS": "arn:aws:iam::$ACCOUNT_ID:role/zt-client-role"},
"Action": "vpc-lattice-svcs:Invoke",
"Resource": "$SVC_ARN/*"
}]
}
EOF
aws vpc-lattice put-auth-policy --resource-identifier $SVC_ID \
--policy "$(jq -c . svc-auth.json)"
Three things to watch.
  • Setting the auth type to AWS_IAM is not enough, because an auth policy can still allow unsigned requests unless it excludes anonymous principals
  • The policy JSON must not contain newlines, which is why the commands pass it through jq -c
  • The calling role also needs an IAM policy that allows vpc-lattice-svcs:Invoke, which the previous section added

What to check

Get the domain name of the service.
aws vpc-lattice get-service --service-identifier $SVC_ID \
--query dnsEntry.domainName --output text
From an EC2 instance in the VPC, sign the request with SigV4, the same signing scheme AWS APIs use. An instance in a private subnet needs a route such as a NAT gateway to install the packages. Amazon VPC Lattice does not support payload signing, so the header carries UNSIGNED-PAYLOAD.
# call.py (pip install botocore awscrt requests)
import sys, requests, botocore.session
from botocore import crt
from botocore.awsrequest import AWSRequest

url, method = sys.argv[1], sys.argv[2]
session = botocore.session.Session()
signer = crt.auth.CrtSigV4Auth(session.get_credentials(), "vpc-lattice-svcs", "ap-northeast-1")
headers = {"x-amz-content-sha256": "UNSIGNED-PAYLOAD"}
request = AWSRequest(method=method, url=url, headers=headers)
request.context["payload_signing_enabled"] = False
signer.add_auth(request)
prepped = request.prepare()
response = requests.request(method, prepped.url, headers=prepped.headers)
print(response.status_code, response.text)
python3 call.py https://<service domain name>/orders/1001 GET
python3 call.py https://<service domain name>/orders/1001 PUT
curl https://<service domain name>/orders/1001
  • The signed GET returns ALLOW
  • The signed PUT passes Amazon VPC Lattice and then returns DENY from the Cedar forbid
  • The unsigned curl is refused before it reaches the Lambda function
Those three results show two separate checks: one at the entrance and one inside the application.

Part 3: narrow the network path to data

A valid identity should still not reach data over an unexpected path. A VPC endpoint combined with a bucket policy makes Amazon S3 accept only requests that came through one endpoint in one VPC.
You create three things.
  • An Amazon S3 bucket named zt-data-<account ID>
  • A gateway VPC endpoint with an endpoint policy
  • A bucket policy




Create the VPC endpoint

The endpoint policy limits what this endpoint can reach to the one bucket.
BUCKET=zt-data-$ACCOUNT_ID
aws s3api create-bucket --bucket $BUCKET \
--create-bucket-configuration LocationConstraint=ap-northeast-1

cat > endpoint-policy.json <<EOF
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": "*",
"Action": ["s3:GetObject", "s3:PutObject", "s3:ListBucket"],
"Resource": ["arn:aws:s3:::$BUCKET", "arn:aws:s3:::$BUCKET/*"]
}]
}
EOF

VPCE_ID=$(aws ec2 create-vpc-endpoint --vpc-endpoint-type Gateway \
--vpc-id $VPC_ID --service-name com.amazonaws.ap-northeast-1.s3 \
--route-table-ids rtb-xxxxxxxx \
--policy-document file://endpoint-policy.json \
--query VpcEndpoint.VpcEndpointId --output text)
Replace rtb-xxxxxxxx with the ID of the route table used by the subnet of the EC2 instance.
Without an endpoint policy, the default policy allows every action. With a policy this narrow, instances that use this route table can no longer reach other buckets. If a workload needs another bucket, add it to the endpoint policy.

Add permissions to the instance role

Add permissions on this bucket to zt-client-role from part 2. If you skipped part 2, use the name of the role attached to your EC2 instance.
cat > s3-policy.json <<EOF
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Action":["s3:GetObject","s3:PutObject","s3:ListBucket"],
"Resource":["arn:aws:s3:::$BUCKET","arn:aws:s3:::$BUCKET/*"]}]}
EOF
aws iam put-role-policy --role-name zt-client-role \
--policy-name zt-s3 --policy-document file://s3-policy.json

Set the bucket policy

Deny requests that did not come through the endpoint. A wrong condition locks you out too, so exempt your admin role.
cat > bucket-policy.json <<EOF
{
"Version": "2012-10-17",
"Statement": [{
"Sid": "DenyUnlessFromVpce",
"Effect": "Deny",
"Principal": "*",
"Action": "s3:*",
"Resource": ["arn:aws:s3:::$BUCKET", "arn:aws:s3:::$BUCKET/*"],
"Condition": {
"StringNotEquals": {"aws:SourceVpce": "$VPCE_ID"},
"ArnNotLike": {"aws:PrincipalArn": "arn:aws:iam::$ACCOUNT_ID:role/<your admin role name>"}
}
}]
}
EOF
aws s3api put-bucket-policy --bucket $BUCKET --policy file://bucket-policy.json

What to check

  • The EC2 instance in the VPC can list, read, and write the bucket
  • The same credentials used outside the VPC, for example on your laptop, are denied
  • The EC2 instance cannot reach other buckets, because of the endpoint policy
Even if the role from part 1 has permissions on this bucket, the request is denied unless it comes through the endpoint. Identity and network path are checked in separate layers.

Part 4: check user access without a VPN

A VPN gives a connected device reach into the whole network. AWS Verified Access works per application and compares information about the user with a policy on every request.
You create four things.
  • A Verified Access instance, which evaluates requests
  • A trust provider, the source of information about the user
  • A group, which holds a policy for applications with the same requirements
  • An endpoint, the entrance to one application




Prerequisites for this part

  • An internal Application Load Balancer with an application behind it
  • A public domain name and a certificate in AWS Certificate Manager
  • An organization instance of AWS IAM Identity Center, enabled in the same Region
An account instance of AWS IAM Identity Center cannot be a trust provider. If you have no organization instance, use an OIDC-compatible identity provider.

Create the instance and the trust provider

VA_ID=$(aws ec2 create-verified-access-instance --description zt-va \
--query VerifiedAccessInstance.VerifiedAccessInstanceId --output text)

TP_ID=$(aws ec2 create-verified-access-trust-provider \
--trust-provider-type user \
--user-trust-provider-type iam-identity-center \
--policy-reference-name idc \
--query VerifiedAccessTrustProvider.VerifiedAccessTrustProviderId --output text)

aws ec2 attach-verified-access-trust-provider \
--verified-access-instance-id $VA_ID \
--verified-access-trust-provider-id $TP_ID
The policy reference name idc is the name the policy uses to read information about the user.

Create the group and the policy

Allow only users who belong to one AWS IAM Identity Center group and have a verified email address. Refer to the group by ID, not by name.
cat > va-policy.cedar <<'EOF'
permit(principal,action,resource)
when {
context.idc.groups has "<IAM Identity Center group ID>"
&& context.idc.user.email.verified == true
};
EOF

VAG_ID=$(aws ec2 create-verified-access-group \
--verified-access-instance-id $VA_ID \
--policy-document file://va-policy.cedar \
--query VerifiedAccessGroup.VerifiedAccessGroupId --output text)
Until you define a policy, every request is denied.

Create the endpoint

VAE_ID=$(aws ec2 create-verified-access-endpoint \
--verified-access-group-id $VAG_ID \
--endpoint-type load-balancer --attachment-type vpc \
--domain-certificate-arn <certificate ARN> \
--application-domain app.example.com \
--endpoint-domain-prefix zt-app \
--security-group-ids sg-xxxxxxxx \
--load-balancer-options Protocol=https,Port=443,LoadBalancerArn=<ALB ARN>,SubnetIds=subnet-aaaa,subnet-bbbb \
--query VerifiedAccessEndpoint.VerifiedAccessEndpointId --output text)
After the endpoint is created, point a CNAME record for the public domain (app.example.com) at the endpoint domain. The security group of the load balancer should allow traffic only from the security group of the endpoint.

What to check

  • Opening the public domain in a browser redirects to the AWS IAM Identity Center sign-in page
  • A user in the group sees the application
  • A user outside the group can sign in but does not reach the application
To add device posture, such as OS patch level or a risk score, attach CrowdStrike, Jamf, or JumpCloud as a device trust provider. One instance takes a single user trust provider and multiple device trust providers.

Part 5: record activity and detect misuse

Parts 1 to 4 make a decision at the moment of access. Zero trust also keeps checking after access is granted. The inputs are a record of API activity and detection of unusual use.
You create three things.
  • A trail named zt-trail, which stores API activity in Amazon S3
  • An Amazon GuardDuty detector
  • AWS Security Hub CSPM, which collects findings and runs configuration checks




Create the trail

The AWS CloudTrail event history shows only the last 90 days of management events. A trail keeps them longer. The destination bucket needs a bucket policy that lets AWS CloudTrail write to it. The policy follows the example in the documentation.
LOG_BUCKET=zt-trail-logs-$ACCOUNT_ID
TRAIL_ARN=arn:aws:cloudtrail:ap-northeast-1:$ACCOUNT_ID:trail/zt-trail
aws s3api create-bucket --bucket $LOG_BUCKET \
--create-bucket-configuration LocationConstraint=ap-northeast-1

cat > trail-bucket-policy.json <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AWSCloudTrailAclCheck20150319",
"Effect": "Allow",
"Principal": {"Service": "cloudtrail.amazonaws.com"},
"Action": "s3:GetBucketAcl",
"Resource": "arn:aws:s3:::$LOG_BUCKET",
"Condition": {"StringEquals": {"aws:SourceArn": "$TRAIL_ARN"}}
},
{
"Sid": "AWSCloudTrailWrite20150319",
"Effect": "Allow",
"Principal": {"Service": "cloudtrail.amazonaws.com"},
"Action": "s3:PutObject",
"Resource": "arn:aws:s3:::$LOG_BUCKET/AWSLogs/$ACCOUNT_ID/*",
"Condition": {"StringEquals": {
"s3:x-amz-acl": "bucket-owner-full-control",
"aws:SourceArn": "$TRAIL_ARN"
}}
}
]
}
EOF
aws s3api put-bucket-policy --bucket $LOG_BUCKET --policy file://trail-bucket-policy.json

aws cloudtrail create-trail --name zt-trail \
--s3-bucket-name $LOG_BUCKET \
--is-multi-region-trail --enable-log-file-validation
aws cloudtrail start-logging --name zt-trail
Data events, such as Amazon S3 object operations, are not recorded by default. To record reads and writes on the bucket from part 3, add them explicitly. Once selectors are set, an event that matches none of them is not recorded, so include a selector for management events too.
cat > selectors.json <<EOF
[
{
"Name": "management-events",
"FieldSelectors": [{"Field": "eventCategory", "Equals": ["Management"]}]
},
{
"Name": "zt-data-bucket",
"FieldSelectors": [
{"Field": "eventCategory", "Equals": ["Data"]},
{"Field": "resources.type", "Equals": ["AWS::S3::Object"]},
{"Field": "resources.ARN", "StartsWith": ["arn:aws:s3:::$BUCKET/"]}
]
}
]
EOF
aws cloudtrail put-event-selectors --trail-name zt-trail \
--advanced-event-selectors file://selectors.json

Turn on Amazon GuardDuty and AWS Security Hub CSPM

aws guardduty create-detector --enable
aws securityhub enable-security-hub --enable-default-standards
Skip these two commands if the account already has them enabled.
Once enabled, Amazon GuardDuty starts analyzing three data sources.
  • AWS CloudTrail management events
  • VPC Flow Logs
  • Amazon Route 53 Resolver DNS query logs
Amazon GuardDuty reads these through its own independent stream, even if you have not set up a trail or flow logs.

What to check

  • The operations from parts 1 to 4 appear in the AWS CloudTrail event history with the caller identity
  • Amazon GuardDuty findings show up in AWS Security Hub CSPM
  • The security standards in AWS Security Hub CSPM list configuration problems
Amazon GuardDuty has a finding type for temporary credentials of an EC2 instance being used from outside AWS (UnauthorizedAccess:IAMUser/InstanceCredentialExfiltration.OutsideAWS). The credentials are valid, yet the way they are used is treated as abnormal. That is the zero trust idea expressed as a detection.

Cleanup

Delete the hourly-billed resources first. The commands assume the shell variables from the earlier steps still exist. If a command fails because the previous deletion has not finished, wait and run it again.

Delete part 4

aws ec2 delete-verified-access-endpoint --verified-access-endpoint-id $VAE_ID
aws ec2 delete-verified-access-group --verified-access-group-id $VAG_ID
aws ec2 detach-verified-access-trust-provider \
--verified-access-instance-id $VA_ID --verified-access-trust-provider-id $TP_ID
aws ec2 delete-verified-access-trust-provider --verified-access-trust-provider-id $TP_ID
aws ec2 delete-verified-access-instance --verified-access-instance-id $VA_ID

Delete part 2

Remove the service network associations before deleting the service. Deleting the service also deletes its listeners and auth policy.
for id in $(aws vpc-lattice list-service-network-vpc-associations \
--service-network-identifier $SN_ID --query 'items[].id' --output text); do
aws vpc-lattice delete-service-network-vpc-association \
--service-network-vpc-association-identifier $id
done
for id in $(aws vpc-lattice list-service-network-service-associations \
--service-network-identifier $SN_ID --query 'items[].id' --output text); do
aws vpc-lattice delete-service-network-service-association \
--service-network-service-association-identifier $id
done
aws vpc-lattice delete-service --service-identifier $SVC_ID
aws vpc-lattice deregister-targets --target-group-identifier $TG_ID --targets id=$FN_ARN
aws vpc-lattice delete-target-group --target-group-identifier $TG_ID
aws vpc-lattice delete-service-network --service-network-identifier $SN_ID
aws lambda delete-function --function-name zt-orders-fn
aws verifiedpermissions delete-policy-store --policy-store-id $STORE_ID

Delete parts 1, 3, and 5

aws rolesanywhere delete-profile --profile-id ${PROFILE_ARN##*/}
aws rolesanywhere delete-trust-anchor --trust-anchor-id ${TA_ARN##*/}
aws s3api delete-bucket-policy --bucket $BUCKET
aws ec2 delete-vpc-endpoints --vpc-endpoint-ids $VPCE_ID
aws cloudtrail delete-trail --name zt-trail
aws guardduty delete-detector \
--detector-id $(aws guardduty list-detectors --query 'DetectorIds[0]' --output text)
aws securityhub disable-security-hub
Run the last two lines only if this guide was the first time you enabled those services. On an account that already used them, they remove existing findings and settings.
What remains:
  • The two buckets (names starting with zt-data- and zt-trail-logs-), which must be emptied before deletion
  • The three IAM roles (zt-workload-role, zt-orders-fn-role, zt-client-role), after detaching their policies
  • The instance profile zt-client-profile, after removing it from the EC2 instance

What the five parts add up to

The resources fall into four layers plus the record from part 5.
  • Identity is the certificate and IAM role in part 1, and the AWS IAM Identity Center users and groups in part 4
  • The entrance is the Amazon VPC Lattice auth policy in part 2 and the AWS Verified Access policy in part 4
  • Inside the application is the Cedar policy in Amazon Verified Permissions from part 2
  • The path to data is the endpoint policy and bucket policy in part 3
Every layer has the same shape: deny by default, then allow only what you name. Stacking that shape layer by layer is what a zero trust setup on AWS looks like.

References

For part 1:
For part 2:
For parts 3 and 4:
For part 5:
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article