VPC endpoints and PrivateLink
Reach S3, DynamoDB and other AWS APIs without the internet using gateway and interface endpoints, lock them down with endpoint and bucket policies, publish your own service privately with PrivateLink, and audit endpoint policies with C#.
Assumes: AWS CLI v2 Β· AWS SDK for .NET v4 (AWSSDK.EC2 4.1.4) Β· .NET 10 LTS Β· CDK v2 (Amazon.CDK.Lib 2.277.0) Β· Terraform AWS provider v6 Β· Region us-east-1. Verified against official sources on 2026-11-18.
Learning objectives
By the end of this lesson you can:
- Explain the difference between gateway endpoints and interface endpoints: how traffic reaches them, what they cost, and who can use them.
- Add S3 and DynamoDB gateway endpoints with restrictive endpoint policies, and an interface endpoint with private DNS and a security group.
- Write the matching resource-side controls (
aws:SourceVpce,aws:SourceVpc) so data can only be reached through your endpoints. - Describe how AWS PrivateLink lets you publish your own service (behind a Network Load Balancer) to other VPCs and accounts, even with overlapping CIDRs.
- Run a C# auditor that lists every endpoint in a VPC and flags full-access default policies and missing private DNS.
Prerequisites
- Route tables and the internet gateway β prefix-list routes.
- NAT gateway and egress β why AWS-service traffic through NAT is expensive and uncontrolled.
- Security groups vs network ACLs β interface endpoints have security groups.
- Tools: AWS CLI v2 (
learn-sandbox), .NET 10 SDK.
Why this matters in banking
Picture the data path of a statement-generation job: it reads transactions from DynamoDB, renders PDFs and writes them to S3. Without endpoints, those calls leave the private subnet through a NAT gateway towards public AWS service addresses. The traffic stays on AWS's network in practice, but your controls are weak: the NAT gateway will happily carry a request to any S3 bucket in the world β including an attacker's bucket in another account. That is the classic exfiltration path auditors ask about: "what stops a compromised workload copying customer data to a bucket you don't own?"
Endpoints answer that question with policy:
- An endpoint policy says "through this door, only our own buckets".
- A bucket policy says "this bucket only accepts requests that came through our doors".
Together they form a data perimeter: trusted identities, accessing trusted resources, from expected networks. Endpoints also cut NAT costs and let the data tier stay isolated. And when Harbourline has to expose an API to a partner whose network overlaps its own (the Northgate Payments story from CIDR planning), PrivateLink is the tool that makes it work without routing the two networks together.
The idea in plain language
A VPC endpoint is a private door from your VPC to a service, so traffic does not need an internet gateway, NAT gateway or public IP.
There are two main kinds (plus a few specialised ones):
| Gateway endpoint | Interface endpoint (powered by AWS PrivateLink) | |
|---|---|---|
| Services | Only S3 and DynamoDB | Most AWS services (Secrets Manager, KMS, SQS, SNS, STS, ECR, CloudWatch Logs, S3, DynamoDBβ¦), partner SaaS, and your own services |
| How it works | A route in your route tables: AWS-managed prefix list β vpce-β¦ | An ENI with a private IP in each subnet/AZ you choose; DNS resolves the service name to those IPs |
| Price | Free | USD 0.01 per hour per AZ + USD 0.01 per GB (first PB) in us-east-1 |
| Security group | No (use the endpoint policy) | Yes β on the endpoint's ENIs |
| Reachable from on-premises, peered VPCs, Transit Gateway | No β only from subnets in this VPC whose route tables have the route | Yes β it is just an IP address in your VPC |
| Endpoint policy | Yes | Yes (for services that support it) |
| Region | Same Region only | Same Region (cross-Region PrivateLink exists for some services and endpoint services β VERIFY current support) |
Analogy: a gateway endpoint is a pneumatic tube from the back office directly to the bank's own archive (S3) β you change the signposts (routes) so documents for the archive go down the tube. It is free, but only rooms with that signpost can use it, and visitors from other buildings cannot. An interface endpoint is a service counter opened inside your building for an outside supplier (Secrets Manager, say): it has a desk number (private IP), a door with a keycard reader (security group), and the phone book (DNS) is updated so everyone who asks for the supplier is sent to the counter. Anyone who can walk to the counter can use it β including staff arriving from other buildings over the private bridge (VPN, Direct Connect, peering).
Private DNS: why your .NET code doesn't change
When you create an interface endpoint with private DNS enabled, AWS adds a private hosted zone so that the service's normal name β for example secretsmanager.us-east-1.amazonaws.com β resolves to the endpoint's private IPs inside your VPC. The AWS SDK for .NET uses the normal name, so it uses the endpoint automatically. This needs the VPC's enableDnsSupport and enableDnsHostnames attributes on (VPC fundamentals).
Gateway endpoints don't use DNS at all: S3 still resolves to public addresses, but the prefix-list route sends those packets to the endpoint instead of the NAT gateway. Again, no code change.
Endpoint policies and resource policies
An endpoint policy is an IAM resource policy attached to the endpoint. It does not grant permissions; it limits what can pass through. The default policy allows everything ("Action": "*", "Resource": "*", "Principal": "*"). A restrictive one allows only specific actions on specific resources or accounts:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "OnlyHarbourlineBuckets",
"Effect": "Allow",
"Principal": "*",
"Action": ["s3:GetObject", "s3:PutObject", "s3:ListBucket"],
"Resource": "*",
"Condition": {
"StringEquals": { "aws:ResourceAccount": "111122223333" }
}
}
]
}Then on the bucket, require that requests arrive through your endpoint:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "DenyUnlessFromPaymentsEndpoint",
"Effect": "Deny",
"Principal": "*",
"Action": "s3:*",
"Resource": [
"arn:aws:s3:::hl-m02-statements-111122223333",
"arn:aws:s3:::hl-m02-statements-111122223333/*"
],
"Condition": {
"StringNotEquals": { "aws:SourceVpce": "vpce-0a1b2c3d4e5f67890" },
"BoolIfExists": { "aws:PrincipalIsAWSService": "false" }
}
}
]
}111122223333 is a placeholder account ID. The second condition stops the deny from breaking AWS services that write to the bucket on your behalf (for example log delivery). Be careful: a bucket policy like this also blocks you from the console, because your browser does not come through the endpoint. In real accounts, add an exception for a break-glass role, test in a sandbox first, and have the security team review it.
Publishing your own service: AWS PrivateLink
PrivateLink is the technology behind interface endpoints, and you can use it for your own services:
- The provider puts the service behind a Network Load Balancer (or Gateway Load Balancer) and creates a VPC endpoint service from it (
com.amazonaws.vpce.us-east-1.vpce-svc-β¦). - The provider lists allowed principals (accounts, roles or an organization) and usually turns on acceptance required.
- The consumer creates an interface endpoint for that service name in its own VPC; the provider accepts.
- The consumer reaches the service at the endpoint's private IPs. Traffic is one-way: consumers can open connections to the provider, never the reverse. The two VPCs are not routed together, so overlapping CIDRs don't matter.
AWS also offers resource endpoints and service-network endpoints (with Amazon VPC Lattice) that let consumers reach a specific resource, such as a database, without the provider deploying an NLB. They are newer; this lesson focuses on the classic patterns that SAA-C03 tests.
What problem endpoints solve
- Private access to AWS services from isolated subnets, with no internet path at all.
- Control over which resources and accounts can be reached (endpoint policies), and from where data can be accessed (resource policies with
aws:SourceVpce). - Lower cost than NAT for heavy S3/DynamoDB traffic (gateway endpoints are free).
- Service publishing across accounts and overlapping networks (PrivateLink).
Limits and sharp edges (checked 2026-11-18):
| Quota | Default |
|---|---|
| Interface + Gateway Load Balancer endpoints per VPC | 50 (adjustable) |
| Gateway endpoints per Region | 20 (adjustable); up to 255 per VPC |
| Endpoint policy size | 20,480 characters (not adjustable) |
| Interface endpoint bandwidth | 10 Gbps per AZ, scaling automatically to 100 Gbps |
| MTU | 8,500 bytes; Path MTU Discovery not supported |
- Interface endpoints bill per AZ per hour, whether used or not. Ten endpoints Γ three AZs β USD 219 a month before data. Banks therefore often centralise interface endpoints in a shared-services VPC and share them over Transit Gateway with Route 53 private hosted zones β covered later in this module.
- Gateway endpoints can't be used from outside the VPC. On-premises clients that need private S3 access need an S3 interface endpoint.
- Not every service supports endpoint policies, and a few services need more than one endpoint (ECR needs
ecr.api,ecr.dkrand the S3 gateway endpoint for image layers). - An endpoint policy restricts, it doesn't grant. Callers still need IAM permissions.
Microsoft / Azure comparison
| You know (Microsoft/Azure) | AWS equivalent | What's different |
|---|---|---|
| Service endpoints (VNet β Storage/SQL) | Gateway endpoints (S3, DynamoDB only) | Both keep public service addresses but take a private path; AWS uses a route-table entry, Azure a subnet setting |
| Service endpoint policies | Gateway endpoint policies | AWS endpoint policies are full IAM-style policies with conditions |
| Private Endpoint (NIC with private IP) | Interface endpoint | Both are NICs/ENIs with private IPs; AWS bills per AZ per hour plus per GB |
Private DNS zone privatelink.blob.core.windows.net | Private DNS on the interface endpoint (AWS-managed private zone) | AWS hides the zone; you just tick "Enable private DNS name" |
| Private Link Service (behind Standard Load Balancer) | VPC endpoint service (behind NLB or GWLB) | Same model: consumer endpoint, provider approval, overlapping IPs fine |
| Storage firewall "selected networks" | Bucket policy with aws:SourceVpce / aws:SourceVpc | AWS enforces it in the resource policy, so it also applies to IAM principals from other accounts |
Architecture
Security-boundary view: three controls meet at each endpoint. Network: the interface endpoint's security group admits only hl-m02-app-sg on 443; gateway endpoint routes exist only in the app route table. Endpoint policy: limits actions and resource accounts passing through. Resource policy: the bucket denies anything not arriving via the named endpoint. A compromised task can therefore reach only Harbourline-owned resources, and Harbourline data can only be read from Harbourline's network. For the partner, PrivateLink exposes exactly one NLB listener β nothing else in either VPC is reachable.
Step-by-step implementation
Add S3 and DynamoDB gateway endpoints (free)
Attach both to hl-m02-app-rt only. The data tier stays local-only. Use the restrictive "own account only" policy above, not the default.
Check the new routes
hl-m02-app-rt now has two prefix-list routes (pl-β¦ β vpce-β¦). Run the route explainer from the route-tables lesson against an S3 address to see the endpoint win over any 0.0.0.0/0 route.
Optional (credits): add a Secrets Manager interface endpoint
Create a security group hl-m02-endpoints-sg allowing TCP 443 from hl-m02-app-sg. Create the endpoint in both app subnets with private DNS on. Cost: about USD 0.02 per hour for two AZs β delete it within the hour.
Verify DNS from inside the VPC
From a task or instance in an app subnet, nslookup secretsmanager.us-east-1.amazonaws.com returns 10.20.64.x/10.20.80.x addresses. From your laptop it returns public addresses β private DNS only applies inside the VPC.
Audit
Run the C# endpoint auditor. Expect no "full access" findings for the gateway endpoints because you replaced the default policy.
AWS Console instructions
- VPC β Endpoints β Create endpoint. Name
hl-m02-s3-gateway; Type: AWS services; searchs3and pickcom.amazonaws.us-east-1.s3with Type = Gateway; VPChl-m02-vpc; route tables: tickhl-m02-app-rtonly; Policy: Custom β paste the endpoint policy (with your account ID) β Create. Repeat forcom.amazonaws.us-east-1.dynamodb, Gateway. - Interface endpoint: Create endpoint β service
com.amazonaws.us-east-1.secretsmanager(Type = Interface); VPC; Additional settings β Enable DNS name ticked; Subnets: the two app subnets; Security groups:hl-m02-endpoints-sg; policy Full access or custom β Create. - Endpoints β select β Details shows DNS names (regional and per-AZ) and Private DNS names enabled; the Subnets tab shows one ENI IP per AZ.
- Endpoint service (provider side): VPC β Endpoint services β Create endpoint service β choose an NLB β Require acceptance for endpoint ticked β Allow principals tab to add consumer account ARNs.
AWS CLI
$p = "--profile", "learn-sandbox", "--region", "us-east-1"
$tags = "{Key=Project,Value=cea-lab},{Key=Lab,Value=m02-secure-vpc},{Key=Environment,Value=learn},{Key=Owner,Value=alex}"
$vpcId = aws ec2 describe-vpcs --filters Name=tag:Name,Values=hl-m02-vpc @p --query "Vpcs[0].VpcId" --output text
$appRt = aws ec2 describe-route-tables @p --filters Name=vpc-id,Values=$vpcId Name=tag:Name,Values=hl-m02-app-rt --query "RouteTables[0].RouteTableId" --output text
$account = aws sts get-caller-identity @p --query Account --output text
# Restrictive endpoint policy: only resources owned by this account
$policy = @"
{"Version":"2012-10-17","Statement":[{"Sid":"OwnAccountOnly","Effect":"Allow","Principal":"*","Action":"*","Resource":"*","Condition":{"StringEquals":{"aws:ResourceAccount":"$account"}}}]}
"@
$policy | Out-File -Encoding ascii endpoint-policy.json
# Gateway endpoints for S3 and DynamoDB (free), app route table only
foreach ($svc in "s3", "dynamodb") {
aws ec2 create-vpc-endpoint --vpc-id $vpcId --vpc-endpoint-type Gateway `
--service-name "com.amazonaws.us-east-1.$svc" --route-table-ids $appRt `
--policy-document file://endpoint-policy.json @p `
--tag-specifications "ResourceType=vpc-endpoint,Tags=[{Key=Name,Value=hl-m02-$svc-gateway},$tags]" `
--query "VpcEndpoint.VpcEndpointId" --output text
}
# See the prefix-list routes the endpoints added
aws ec2 describe-route-tables --route-table-ids $appRt @p `
--query "RouteTables[0].Routes[?DestinationPrefixListId].[DestinationPrefixListId,GatewayId]" --output table
# Optional (about USD 0.02/hour for two AZs): Secrets Manager interface endpoint with private DNS
$appSg = aws ec2 describe-security-groups @p --filters Name=vpc-id,Values=$vpcId Name=group-name,Values=hl-m02-app-sg --query "SecurityGroups[0].GroupId" --output text
$epSg = aws ec2 create-security-group --group-name hl-m02-endpoints-sg --description "Interface endpoints: 443 from app tier" --vpc-id $vpcId @p --query GroupId --output text
aws ec2 authorize-security-group-ingress --group-id $epSg @p `
--ip-permissions "IpProtocol=tcp,FromPort=443,ToPort=443,UserIdGroupPairs=[{GroupId=$appSg,Description=HTTPS from app tier}]"
$appSubnets = (aws ec2 describe-subnets @p --filters Name=vpc-id,Values=$vpcId Name=tag:Tier,Values=app --query "Subnets[].SubnetId" --output text) -split "\s+"
$smEndpoint = aws ec2 create-vpc-endpoint --vpc-id $vpcId --vpc-endpoint-type Interface `
--service-name com.amazonaws.us-east-1.secretsmanager --subnet-ids $appSubnets --security-group-ids $epSg `
--private-dns-enabled @p `
--tag-specifications "ResourceType=vpc-endpoint,Tags=[{Key=Name,Value=hl-m02-secretsmanager},$tags]" `
--query "VpcEndpoint.VpcEndpointId" --output text
# Which AWS services offer endpoints in this Region (long list)
aws ec2 describe-vpc-endpoint-services @p --query "ServiceDetails[].[ServiceName,ServiceType[0].ServiceType]" --output text | Select-Object -First 20Infrastructure as Code
using Amazon.CDK;
using Amazon.CDK.AWS.EC2;
using Amazon.CDK.AWS.IAM;
using Constructs;
namespace Harbourline.Networking.Examples;
public sealed class EndpointsStack : Stack
{
public EndpointsStack(Construct scope, string id, IVpc vpc, ISecurityGroup appSg, IStackProps? props = null)
: base(scope, id, props)
{
var appSubnets = new SubnetSelection { SubnetGroupName = "app" };
// Free gateway endpoints, routed from the app tier only.
var s3 = vpc.AddGatewayEndpoint("S3", new GatewayVpcEndpointOptions
{
Service = GatewayVpcEndpointAwsService.S3,
Subnets = [appSubnets],
});
var dynamo = vpc.AddGatewayEndpoint("DynamoDb", new GatewayVpcEndpointOptions
{
Service = GatewayVpcEndpointAwsService.DYNAMODB,
Subnets = [appSubnets],
});
// Replace the default allow-all policy: only resources in this account.
foreach (var endpoint in new[] { s3, dynamo })
{
endpoint.AddToPolicy(new PolicyStatement(new PolicyStatementProps
{
Principals = [new AnyPrincipal()],
Actions = ["*"],
Resources = ["*"],
Conditions = new Dictionary<string, object>
{
["StringEquals"] = new Dictionary<string, object> { ["aws:ResourceAccount"] = Account },
},
}));
}
// Interface endpoint with private DNS; its SG admits HTTPS from the app tier only.
var endpointSg = new SecurityGroup(this, "EndpointsSg", new SecurityGroupProps
{
Vpc = vpc, Description = "Interface endpoints: 443 from app tier", AllowAllOutbound = false,
});
endpointSg.AddIngressRule(appSg, Port.Tcp(443), "HTTPS from app tier");
_ = vpc.AddInterfaceEndpoint("SecretsManager", new InterfaceVpcEndpointOptions
{
Service = InterfaceVpcEndpointAwsService.SECRETS_MANAGER,
Subnets = appSubnets,
SecurityGroups = [endpointSg],
PrivateDnsEnabled = true,
Open = false, // don't add an automatic "allow from VPC CIDR" rule
});
}
}AddToPolicy on a gateway endpoint replaces the implicit allow-all default with your statements. Open = false matters: by default CDK opens the interface endpoint's security group to the whole VPC CIDR, which is broader than "app tier only".
Complete code
1. Endpoint auditor
Lists every endpoint in a VPC with type, service, state and DNS, and flags the default full-access policy, interface endpoints without private DNS, and interface endpoints in only one AZ.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AWSSDK.EC2" Version="4.1.4" />
<PackageReference Include="AWSSDK.SSO" Version="4.1.0.2" />
<PackageReference Include="AWSSDK.SSOOIDC" Version="4.1.0.2" />
</ItemGroup>
</Project>using System.Text.Json;
using Amazon;
using Amazon.EC2;
using Amazon.EC2.Model;
// Usage: $env:AWS_PROFILE = "learn-sandbox"; dotnet run -- vpc-0123456789abcdef0
if (args.Length != 1)
{
Console.Error.WriteLine("Usage: EndpointAudit <vpc-id>");
return 2;
}
using var ec2 = new AmazonEC2Client(RegionEndpoint.USEast1);
var findings = 0;
await foreach (var ep in ec2.Paginators.DescribeVpcEndpoints(new DescribeVpcEndpointsRequest
{
Filters = [new Filter { Name = "vpc-id", Values = [args[0]] }],
}).VpcEndpoints)
{
var name = ep.Tags?.FirstOrDefault(t => t.Key == "Name")?.Value ?? "(no name)";
Console.WriteLine($"{ep.VpcEndpointId,-24} {ep.VpcEndpointType,-10} {ep.State,-10} {name,-26} {ep.ServiceName}");
var problems = new List<string>();
if (ep.VpcEndpointType == VpcEndpointType.Gateway)
{
Console.WriteLine($" route tables: {string.Join(", ", ep.RouteTableIds ?? [])}");
}
else if (ep.VpcEndpointType == VpcEndpointType.Interface)
{
var subnets = ep.SubnetIds ?? [];
Console.WriteLine($" subnets: {subnets.Count}, security groups: {string.Join(", ", (ep.Groups ?? []).Select(g => g.GroupId))}, private DNS: {ep.PrivateDnsEnabled}");
if (subnets.Count < 2) problems.Add("interface endpoint in fewer than two AZs β one AZ failure breaks access");
if (ep.PrivateDnsEnabled != true && ep.ServiceName.StartsWith("com.amazonaws.", StringComparison.Ordinal))
{
problems.Add("private DNS is off β SDK clients will keep using public endpoints unless configured with ServiceURL");
}
}
if (!string.IsNullOrEmpty(ep.PolicyDocument) && IsFullAccess(ep.PolicyDocument))
{
problems.Add("endpoint policy allows every action on every resource (default) β restrict by account or resource");
}
foreach (var p in problems)
{
Console.WriteLine($" WARNING: {p}");
}
findings += problems.Count;
}
Console.WriteLine(findings == 0 ? "No warnings." : $"{findings} warning(s).");
return findings == 0 ? 0 : 1;
// A statement is "full access" if it allows Action "*" on Resource "*" for Principal "*" with no Condition.
static bool IsFullAccess(string policyJson)
{
using var doc = JsonDocument.Parse(policyJson);
if (!doc.RootElement.TryGetProperty("Statement", out var statements))
{
return false;
}
var list = statements.ValueKind == JsonValueKind.Array ? statements.EnumerateArray().ToList() : [statements];
return list.Any(s =>
s.TryGetProperty("Effect", out var effect) && effect.GetString() == "Allow" &&
!s.TryGetProperty("Condition", out _) &&
IsWildcard(s, "Action") && IsWildcard(s, "Resource") && IsAnyPrincipal(s));
}
static bool IsWildcard(JsonElement statement, string property)
{
if (!statement.TryGetProperty(property, out var value)) return false;
return value.ValueKind switch
{
JsonValueKind.String => value.GetString() == "*",
JsonValueKind.Array => value.EnumerateArray().Any(v => v.GetString() == "*"),
_ => false,
};
}
static bool IsAnyPrincipal(JsonElement statement)
{
if (!statement.TryGetProperty("Principal", out var principal)) return false;
if (principal.ValueKind == JsonValueKind.String) return principal.GetString() == "*";
return principal.ValueKind == JsonValueKind.Object &&
principal.TryGetProperty("AWS", out var aws) &&
(aws.ValueKind == JsonValueKind.String ? aws.GetString() == "*" : aws.EnumerateArray().Any(v => v.GetString() == "*"));
}2. Using an endpoint from .NET
With private DNS on (or a gateway endpoint), nothing changes in your application β the standard client resolves to the private path. Only when private DNS is off (for example a centralised endpoint reached from another VPC without a shared private zone) do you point the client at the endpoint's DNS name:
using Amazon;
using Amazon.SecretsManager;
namespace Harbourline.Payments.Infrastructure;
public static class SecretsClientFactory
{
// endpointDnsName example: "vpce-0abc123def4567890-1a2b3c4d.secretsmanager.us-east-1.vpce.amazonaws.com"
public static IAmazonSecretsManager Create(string? endpointDnsName)
{
var config = new AmazonSecretsManagerConfig { RegionEndpoint = RegionEndpoint.USEast1 };
if (!string.IsNullOrWhiteSpace(endpointDnsName))
{
// Setting ServiceURL overrides the endpoint; SigV4 still signs for the secretsmanager service in us-east-1.
config.ServiceURL = $"https://{endpointDnsName}";
config.AuthenticationRegion = "us-east-1";
}
return new AmazonSecretsManagerClient(config);
}
}(Package: AWSSDK.SecretsManager. In ASP.NET Core you would register the client with AddAWSService<IAmazonSecretsManager>() and keep the endpoint name in configuration.)
Code explained line by line
ec2.Paginators.DescribeVpcEndpoints(...)filtered byvpc-idβ returns gateway, interface, Gateway Load Balancer and newer endpoint types.ep.VpcEndpointType == VpcEndpointType.Gatewayβ SDK v4 "enum" classes compare with==. Gateway endpoints reportRouteTableIds; interface endpoints reportSubnetIds(one per AZ) andGroups.subnets.Count < 2β an interface endpoint has an ENI only in the subnets you choose; with one subnet, an AZ failure breaks access from every AZ.ep.PrivateDnsEnabled != trueforcom.amazonaws.*services β without private DNS, SDK calls go to the public service endpoint (through NAT, or fail in an isolated subnet).IsFullAccess(ep.PolicyDocument)β parses the policy withSystem.Text.Json.Statement,Action,ResourceandPrincipalcan each be a single value or an array; the helpers handle both shapes.!s.TryGetProperty("Condition", out _)β a wildcard statement with a condition (likeaws:ResourceAccount) is a restriction, not full access, so it is not flagged.- In the factory,
ServiceURLsends requests to the endpoint-specific DNS name, andAuthenticationRegionkeeps SigV4 signing correct because the host name no longer looks like a standard Regional endpoint.
Security considerations
- Replace default endpoint policies. Allow-all endpoint policies give you the network path without the control. Start with "own account / own organization only" (
aws:ResourceAccount,aws:ResourceOrgID), then narrow actions. - Close the loop on the resource side. Bucket and key policies with
aws:SourceVpce(one endpoint) oraws:SourceVpc(any endpoint in a VPC) ensure data can't be read from elsewhere, even with valid stolen credentials. Test break-glass access before you deploy. - Interface endpoint SGs: allow 443 from the consuming tier's SG, not from the whole VPC CIDR.
- PrivateLink services: require acceptance, restrict allowed principals to named accounts, and add TLS (and ideally mTLS) on the NLB listener β PrivateLink is private, not authenticated.
- Logging: CloudTrail records the API calls (including the
vpcEndpointIdfield for supported services); Flow Logs on the endpoint ENIs show who connected.
β Learning shortcut β not for production
The lab creates endpoints per VPC and uses an account-level condition. At Harbourline, interface endpoints for common services (Secrets Manager, KMS, STS, SQS, ECR, CloudWatch Logs) are centralised in a shared-services VPC, shared through Transit Gateway and Route 53 private hosted zones to every workload VPC, and their policies use organization-level conditions (aws:PrincipalOrgID, aws:ResourceOrgID) as part of a data-perimeter design reviewed by the security architecture team. S3 bucket policies requiring endpoints are rolled out gradually with monitoring, because a mistake locks out legitimate users.
Banking use case
Statements pipeline. The statement-generation service runs in isolated subnets with no NAT. It reaches DynamoDB and S3 through gateway endpoints (free) whose policies allow only Harbourline-owned resources, and Secrets Manager and KMS through central interface endpoints. The hl-prod-statements bucket denies any request not arriving through the Payments VPC's S3 endpoint, except for a break-glass role used under a change ticket.
Partner API with overlapping addresses. Northgate Payments (fictional) uses 10.20.0.0/16 β the same range as a Harbourline VPC. Harbourline publishes its partner Open Banking API behind an internal NLB as a VPC endpoint service, with acceptance required and Northgate's account as the only allowed principal. Northgate creates an interface endpoint in its own VPC and calls the API at its own private IPs; the NLB listener uses TLS with Harbourline's certificate, and the API also requires mTLS client certificates (see certificates, TLS and mTLS). No peering, no Transit Gateway, no re-addressing β and Northgate can reach exactly one port of one service.
Common mistakes
- Leaving the default allow-all endpoint policy β no exfiltration control β restrict by account or organization.
- Expecting a gateway endpoint to work from on-premises or a peered VPC β it can't β use an S3 interface endpoint for those clients.
- Interface endpoint without private DNS (or with VPC DNS attributes off) β SDK still resolves public addresses β enable private DNS and both VPC DNS attributes.
- Bucket policy with
aws:SourceVpcedeployed without exceptions β admins and AWS services lose access β test in a sandbox, add break-glass and service exceptions. - Creating every interface endpoint in every VPC and AZ β hundreds of dollars a month β centralise and share.
- Forgetting the S3 gateway endpoint when using ECR endpoints β image pulls fail in isolated subnets because layers come from S3.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| SDK call times out in an isolated subnet | No endpoint for that service, or the app SG has no egress to the endpoint SG on 443 | Add the endpoint; allow app-sg β endpoints-sg 443 both ways |
AccessDenied only from inside the VPC | Endpoint policy doesn't allow the action/resource | Check the endpoint policy; CloudTrail shows vpcEndpointId for the call |
AccessDenied from everywhere except the VPC | Bucket policy with aws:SourceVpce working as designed | Use the endpoint path or the break-glass role |
| Service name resolves to public IPs inside the VPC | Private DNS off, or enableDnsHostnames/enableDnsSupport off | Enable private DNS and both VPC attributes |
create-vpc-endpoint with private DNS fails: conflicting DNS domain | Another endpoint or a private hosted zone already claims that name in the VPC | Remove the duplicate, or turn off private DNS on one of them |
| ECR pull fails with layer download errors | S3 gateway endpoint missing or its policy blocks ECR's buckets | Add the S3 gateway endpoint; allow the ECR layer buckets β VERIFY the bucket ARN pattern in ECR docs |
Partner's endpoint stuck in pendingAcceptance | Endpoint service requires acceptance | Provider accepts the connection request |
Cost and cleanup
Cost label: credits. Gateway endpoints: USD 0. A Secrets Manager interface endpoint in two AZs for one hour: 2 Γ USD 0.01 β USD 0.02 plus negligible data. Left running a month: β USD 14.60. Free alternative: do the gateway endpoints only (free) and design the interface endpoint on paper.
$p = "--profile", "learn-sandbox", "--region", "us-east-1"
# Delete all endpoints in the lab VPC (gateway endpoints also remove their routes)
$ids = aws ec2 describe-vpc-endpoints @p --filters Name=vpc-id,Values=$vpcId --query "VpcEndpoints[].VpcEndpointId" --output text
if ($ids) { aws ec2 delete-vpc-endpoints --vpc-endpoint-ids ($ids -split "\s+") @p }
# Delete the endpoint security group once the endpoint ENIs are gone (can take a minute)
aws ec2 delete-security-group --group-id $epSg @p
Remove-Item endpoint-policy.json -ErrorAction SilentlyContinue
aws resourcegroupstaggingapi get-resources --tag-filters Key=Project,Values=cea-lab @p --query "ResourceTagMappingList[].ResourceARN"Exercises
- π’ Guided: Create both gateway endpoints with the restrictive policy, list the prefix-list routes, and run the auditor (no policy warnings). Then create one with the default policy, re-run, and see the "allows every action" warning.
- π‘ Challenge: Write a bucket policy for
hl-m02-statements-<account>that allows reads only through your S3 gateway endpoint or by a role namedhl-breakglass, and denies non-TLS requests. Explain each condition. - π΄ Live problem: "We moved the reconciliation service to isolated subnets as security asked. Now it fails at startup:
Unable to get IAM security credentials from EC2 Instance Metadata Service... no, sorry, it's ECS β the error is a timeout callingsts.us-east-1.amazonaws.com, then CloudWatch Logs stops receiving logs." List every endpoint the service needs and why.
Assignment
Produce a data-perimeter one-pager for one Harbourline service: the endpoints it uses (type, AZs, cost per month), each endpoint policy, the resource policies that require those endpoints, and the break-glass path. Include the auditor's output.
Solutions
The route table shows two rows like pl-63a5400a vpce-β¦ (S3) and pl-02cd2c6b vpce-β¦ (DynamoDB) β prefix-list IDs vary by Region. With the restrictive policy, the auditor prints the endpoints with no warning; the default-policy endpoint shows endpoint policy allows every action on every resource. Why: the default statement has Principal "*", Action "*", Resource "*" and no condition β exactly what IsFullAccess detects.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "DenyNonTls",
"Effect": "Deny",
"Principal": "*",
"Action": "s3:*",
"Resource": ["arn:aws:s3:::hl-m02-statements-111122223333", "arn:aws:s3:::hl-m02-statements-111122223333/*"],
"Condition": { "Bool": { "aws:SecureTransport": "false" } }
},
{
"Sid": "DenyUnlessEndpointOrBreakGlass",
"Effect": "Deny",
"Principal": "*",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::hl-m02-statements-111122223333/*",
"Condition": {
"StringNotEquals": { "aws:SourceVpce": "vpce-0a1b2c3d4e5f67890" },
"ArnNotLike": { "aws:PrincipalArn": "arn:aws:iam::111122223333:role/hl-breakglass" }
}
}
]
}Why: multiple condition operators in one statement are ANDed, so the deny applies only when the request is both not from the endpoint and not from the break-glass role. The first statement rejects any plain-HTTP request. Deny statements don't grant anything β readers still need IAM permissions.
In isolated subnets every AWS API needs an endpoint. For an ECS Fargate service typically: ecr.api and ecr.dkr (image metadata and pulls), S3 gateway (image layers), logs (CloudWatch Logs for the awslogs driver), sts (the SDK and some credential flows β the timeout in the ticket), secretsmanager and/or ssm (secrets injected into the task), kms if the app decrypts, plus anything the app itself calls (SQS, DynamoDB gateway). Each interface endpoint needs private DNS and an SG allowing 443 from the task SG. Why it surfaced as two errors: STS failed first; log delivery also had no path, so evidence disappeared at the same time β add the logs endpoint before moving workloads.
Knowledge check
Answer: Amazon S3 and Amazon DynamoDB. Both also offer interface endpoints.
Answer: Gateway endpoints are route-table targets inside the VPC; traffic arriving from outside the VPC can't be routed to them. Use an S3 interface endpoint, which has private IPs reachable over Direct Connect or VPN.
Answer: No. It limits what may pass through the endpoint. The caller still needs IAM permissions, and resource policies still apply.
Answer: The VPCs are never routed together. The consumer talks to an interface endpoint with IPs from its own VPC; AWS carries the traffic to the provider's NLB.
Answer: They match requests that arrived through a specific VPC endpoint or through any endpoint in a specific VPC, so a Deny with StringNotEquals restricts access to those network paths.
Interview questions
- "Gateway or interface endpoint for S3?" β Gateway for workloads inside the VPC: free, no DNS change. Interface when clients come from on-premises, peered VPCs or Transit Gateway, or when you need a security group on the path.
- "How do you stop data exfiltration to someone else's S3 bucket?" β Restrictive endpoint policy (
aws:ResourceAccount/aws:ResourceOrgID), no NAT path to S3, and resource policies requiring my endpoints; organization-wide via SCPs and RCPs as part of a data perimeter. - "How would you expose an internal API to a partner whose network overlaps ours?" β An NLB-fronted VPC endpoint service with acceptance and allowed principals; the partner creates an interface endpoint; TLS/mTLS on top.
- "Why might interface endpoints be expensive, and how do you fix it?" β They bill per AZ per hour per endpoint; centralise them in a shared-services VPC and share via Transit Gateway with private hosted zones.
Certification practice
EC2 instances in private subnets with no internet access must upload files to one S3 bucket. The security team requires that the bucket can only be accessed from this VPC. Which combination meets the requirements? (Choose two.)
A. Create an S3 gateway endpoint and add it to the private subnets' route tables
B. Add a NAT gateway and restrict the bucket to the NAT gateway's Elastic IP
C. Add a bucket policy that denies requests where aws:SourceVpce is not the endpoint's ID
D. Enable S3 Block Public Access only
E. Create an internet gateway and use S3 Transfer Acceleration
Answer: A and C. The gateway endpoint provides the private path; the bucket policy restricts access to that path. B uses the internet path and IP conditions don't work for VPC-endpoint traffic. D blocks public access but not access by other authenticated principals from elsewhere. E adds internet exposure.
A bank's analytics provider runs its service in its own AWS account. The bank wants to consume it privately from a VPC whose CIDR overlaps with the provider's VPC, with no inbound access from the provider. What should be used?
A. VPC peering B. AWS Transit Gateway C. An interface endpoint to the provider's VPC endpoint service (AWS PrivateLink) D. A Site-to-Site VPN between the VPCs
Answer: C. PrivateLink works with overlapping CIDRs and is one-way (consumer β provider). A and B require non-overlapping ranges and open bidirectional routing. D also requires routable, non-overlapping ranges.
After an interface endpoint for Amazon SQS is created in a VPC, applications still connect to SQS's public IP addresses. The endpoint shows available. What should the CloudOps engineer check first?
A. Whether the endpoint's private DNS option is enabled and the VPC has enableDnsSupport and enableDnsHostnames on
B. Whether the SQS queue policy allows the VPC
C. Whether the NAT gateway is deleted
D. Whether the subnet's NACL allows port 53
Answer: A. Without private DNS (and the VPC DNS attributes), the default SQS hostname resolves to public addresses. B concerns authorization, not resolution. C would cause failures, not public connections. D β the Amazon DNS resolver isn't filtered by NACLs.
A workload in private subnets reaches S3 through a gateway endpoint with the default policy. A security engineer must prevent the workload from writing to S3 buckets owned by other AWS accounts, without changing application code. What should the engineer do?
A. Update the endpoint policy to allow S3 actions only when aws:ResourceAccount equals the company's account (or aws:ResourceOrgID equals its organization)
B. Remove the endpoint and add a NAT gateway
C. Add an outbound security group rule restricted to the S3 prefix list
D. Enable Amazon Macie
Answer: A. The endpoint policy is evaluated for every request through the endpoint; resource-account conditions block foreign buckets. B removes the control point entirely. C still allows every bucket, because all buckets share the S3 address ranges. D discovers sensitive data but doesn't block writes.
Completion checklist
- I can explain gateway vs interface endpoints in two sentences each
- I created S3 and DynamoDB gateway endpoints with a restrictive policy
- I created (and deleted) an interface endpoint with private DNS β or designed it on paper
- I can write a bucket policy that requires a VPC endpoint
- I ran the endpoint auditor and cleaned up
Key takeaways
- Gateway endpoints (S3, DynamoDB) are free route-table entries usable only from inside the VPC.
- Interface endpoints are ENIs with private IPs, security groups and private DNS; they bill per AZ per hour and per GB, and are reachable from anywhere routed to the VPC.
- Endpoint policies restrict traffic through the door; resource policies with
aws:SourceVpcerestrict where data can be reached from β together they form a data perimeter. - With private DNS, the AWS SDK for .NET uses endpoints with no code change.
- PrivateLink publishes your own NLB-fronted service one-way to other VPCs and accounts, even with overlapping CIDRs.
Further reading
- What is AWS PrivateLink?
- Gateway endpoints
- Control access to VPC endpoints using endpoint policies
- AWS PrivateLink quotas
- AWS PrivateLink pricing
Next: DNS and Route 53.
Independent learning resource β not affiliated with, endorsed or sponsored by Amazon Web Services. AWS and related marks are trademarks of Amazon.com, Inc. or its affiliates. All banking data in examples is fictional. Sample architectures are for learning and are not automatically compliant with GDPR, PCI DSS or any banking regulation.
Security groups vs network ACLs
Filter traffic in a VPC with stateful security groups that reference each other and stateless network ACLs as a subnet guardrail, know exactly which one to use when, and audit both with a C# tool.
DNS and Route 53
Run public and private DNS on AWS with Route 53: hosted zones, alias records, all eight routing policies, health checks and failover β and shift traffic between two versions of an API with a C# tool.