Skip to Content
Cloud Engineering Academy
2. AWS Networking & Infrastructure

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#.

intermediate⏱ 1 h 30 min🟑 Low costSAA-C03SOA-C03SCS-C03

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

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 endpointInterface endpoint (powered by AWS PrivateLink)
ServicesOnly S3 and DynamoDBMost AWS services (Secrets Manager, KMS, SQS, SNS, STS, ECR, CloudWatch Logs, S3, DynamoDB…), partner SaaS, and your own services
How it worksA 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
PriceFreeUSD 0.01 per hour per AZ + USD 0.01 per GB (first PB) in us-east-1
Security groupNo (use the endpoint policy)Yes β€” on the endpoint's ENIs
Reachable from on-premises, peered VPCs, Transit GatewayNo β€” only from subnets in this VPC whose route tables have the routeYes β€” it is just an IP address in your VPC
Endpoint policyYesYes (for services that support it)
RegionSame Region onlySame 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:

s3-endpoint-policy.json
{
  "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:

statements-bucket-policy.json
{
  "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.

PrivateLink is the technology behind interface endpoints, and you can use it for your own services:

  1. 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-…).
  2. The provider lists allowed principals (accounts, roles or an organization) and usually turns on acceptance required.
  3. The consumer creates an interface endpoint for that service name in its own VPC; the provider accepts.
  4. 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):

QuotaDefault
Interface + Gateway Load Balancer endpoints per VPC50 (adjustable)
Gateway endpoints per Region20 (adjustable); up to 255 per VPC
Endpoint policy size20,480 characters (not adjustable)
Interface endpoint bandwidth10 Gbps per AZ, scaling automatically to 100 Gbps
MTU8,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.dkr and 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 equivalentWhat'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 policiesGateway endpoint policiesAWS endpoint policies are full IAM-style policies with conditions
Private Endpoint (NIC with private IP)Interface endpointBoth are NICs/ENIs with private IPs; AWS bills per AZ per hour plus per GB
Private DNS zone privatelink.blob.core.windows.netPrivate 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:SourceVpcAWS 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; search s3 and pick com.amazonaws.us-east-1.s3 with Type = Gateway; VPC hl-m02-vpc; route tables: tick hl-m02-app-rt only; Policy: Custom β†’ paste the endpoint policy (with your account ID) β†’ Create. Repeat for com.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 20

Infrastructure as Code

EndpointsStack.cs
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.

EndpointAudit.csproj
<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>
Program.cs
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:

SecretsClientFactory.cs
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

  1. ec2.Paginators.DescribeVpcEndpoints(...) filtered by vpc-id β€” returns gateway, interface, Gateway Load Balancer and newer endpoint types.
  2. ep.VpcEndpointType == VpcEndpointType.Gateway β€” SDK v4 "enum" classes compare with ==. Gateway endpoints report RouteTableIds; interface endpoints report SubnetIds (one per AZ) and Groups.
  3. 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.
  4. ep.PrivateDnsEnabled != true for com.amazonaws.* services β€” without private DNS, SDK calls go to the public service endpoint (through NAT, or fail in an isolated subnet).
  5. IsFullAccess(ep.PolicyDocument) β€” parses the policy with System.Text.Json. Statement, Action, Resource and Principal can each be a single value or an array; the helpers handle both shapes.
  6. !s.TryGetProperty("Condition", out _) β€” a wildcard statement with a condition (like aws:ResourceAccount) is a restriction, not full access, so it is not flagged.
  7. In the factory, ServiceURL sends requests to the endpoint-specific DNS name, and AuthenticationRegion keeps 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) or aws: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 vpcEndpointId field 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:SourceVpce deployed 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

SymptomLikely causeFix
SDK call times out in an isolated subnetNo endpoint for that service, or the app SG has no egress to the endpoint SG on 443Add the endpoint; allow app-sg β†’ endpoints-sg 443 both ways
AccessDenied only from inside the VPCEndpoint policy doesn't allow the action/resourceCheck the endpoint policy; CloudTrail shows vpcEndpointId for the call
AccessDenied from everywhere except the VPCBucket policy with aws:SourceVpce working as designedUse the endpoint path or the break-glass role
Service name resolves to public IPs inside the VPCPrivate DNS off, or enableDnsHostnames/enableDnsSupport offEnable private DNS and both VPC attributes
create-vpc-endpoint with private DNS fails: conflicting DNS domainAnother endpoint or a private hosted zone already claims that name in the VPCRemove the duplicate, or turn off private DNS on one of them
ECR pull fails with layer download errorsS3 gateway endpoint missing or its policy blocks ECR's bucketsAdd the S3 gateway endpoint; allow the ECR layer buckets ⚠ VERIFY the bucket ARN pattern in ECR docs
Partner's endpoint stuck in pendingAcceptanceEndpoint service requires acceptanceProvider 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 named hl-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 calling sts.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

Knowledge check

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

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:SourceVpce restrict 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

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.

On this page