<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by RAFAEL SERAPILHA DURELLI on Medium]]></title>
        <description><![CDATA[Stories by RAFAEL SERAPILHA DURELLI on Medium]]></description>
        <link>https://medium.com/@rafael.durelli?source=rss-8f17b9435e5d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*MvlODRhD8383YvkR</url>
            <title>Stories by RAFAEL SERAPILHA DURELLI on Medium</title>
            <link>https://medium.com/@rafael.durelli?source=rss-8f17b9435e5d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 08:42:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rafael.durelli/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[A corporate VPN with no shared password: AWS Client VPN + Keycloak (SAML), 100% in Terraform]]></title>
            <link>https://medium.com/@rafael.durelli/a-corporate-vpn-with-no-shared-password-aws-client-vpn-keycloak-saml-100-in-terraform-e837db51de56?source=rss-8f17b9435e5d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e837db51de56</guid>
            <category><![CDATA[vpn]]></category>
            <category><![CDATA[keycloak]]></category>
            <category><![CDATA[aws-vpc]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[RAFAEL SERAPILHA DURELLI]]></dc:creator>
            <pubDate>Tue, 21 Jul 2026 12:02:05 GMT</pubDate>
            <atom:updated>2026-07-21T12:02:05.732Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nvlmJGcwyFe4028yiMsveQ.png" /></figure><h3>The problem</h3><p>I needed to give my team access to a private VPC network — databases, EC2, internal services. The classic options age badly:</p><ul><li><strong>Mutual-cert VPN:</strong> you end up distributing .ovpn files with an embedded key. Someone leaves? Hope you remember to revoke their cert.</li><li><strong>VPN with a local username/password:</strong> yet another identity store to maintain, separate from your IdP.</li></ul><p>This tutorial takes a different route: <strong>AWS Client VPN with federated SAML authentication</strong>, using the <strong>Keycloak</strong> you probably already run as your IdP. The user clicks <em>Connect</em>, the browser opens the Keycloak login, done. No VPN password, no client certificate. Disable the account in Keycloak and access dies on the next connection.</p><p>Best part: <strong>it’s all Terraform</strong> — the realm, the SAML client, the groups, the VPN endpoint and the authorization rules. enable_vpn = false tears it all down; true rebuilds it.</p><p>Let’s start from scratch.</p><h3>How it works (the flow)</h3><ol><li>The user clicks <strong>Connect</strong> in the AWS VPN Client.</li><li>The endpoint redirects to the <strong>IdP</strong> — a browser opens.</li><li>They log in to <strong>Keycloak</strong>.</li><li>Keycloak returns a <strong>SAML assertion</strong> (with the NameID and the memberOf attribute), which AWS validates against an <strong>IAM SAML Provider</strong>.</li><li>The endpoint associates the connection to a <strong>private subnet</strong> and applies <strong>per-group authorization rules</strong>.</li></ol><p>Split-tunnel: only VPC-bound traffic enters the tunnel; the user’s internet stays local.</p><h3>Prerequisites</h3><ul><li>A <strong>VPC with at least one private subnet</strong>.</li><li>A <strong>Keycloak reachable over public HTTPS</strong> (AWS must download the realm’s SAML metadata; an internal-only Keycloak won’t complete the flow).</li><li><strong>Terraform</strong> and the providers below.</li></ul><p>An important Keycloak-provider compatibility note:</p><pre># versions.tf<br>terraform {<br>  required_providers {<br>    aws = {<br>      source  = &quot;hashicorp/aws&quot;<br>      version = &quot;&lt; 6.0.0&quot;<br>    }<br>    tls   = { source = &quot;hashicorp/tls&quot;,   version = &quot;~&gt; 4.0&quot; }<br>    local = { source = &quot;hashicorp/local&quot;, version = &quot;~&gt; 2.4&quot; }<br>    http  = { source = &quot;hashicorp/http&quot;,  version = &quot;~&gt; 3.4&quot; }<br><br>    # ⚠️ The keycloak/keycloak ~&gt; 5.0 provider targets Keycloak 25/26+.<br>    # On Keycloak 22 it sends fields (e.g. organizations_enabled) that the API<br>    # rejects with HTTP 500 when creating the realm. Use mrparkers ~&gt; 4.3.<br>    keycloak = {<br>      source  = &quot;mrparkers/keycloak&quot;<br>      version = &quot;~&gt; 4.3&quot;<br>    }<br>  }<br>}</pre><pre># Provider — it does NOT authenticate at init, only when there are keycloak<br># resources to manage. So teammates applying other parts without the Keycloak<br># credentials won&#39;t break.<br>provider &quot;keycloak&quot; {<br>  client_id     = &quot;admin-cli&quot;<br>  username      = var.keycloak_admin_user<br>  password      = var.keycloak_admin_password   # via TF_VAR_keycloak_admin_password<br>  url           = &quot;https://keycloak.example.com&quot;<br>  initial_login = false<br>}</pre><h3>Step 1 — Keycloak as the IdP (in Terraform)</h3><p>We create the realm, the SAML client that represents AWS, the groups that will segment access, and the <em>mappers</em> that inject attributes into the assertion.</p><pre># --- Realm ---<br>resource &quot;keycloak_realm&quot; &quot;aws_vpn&quot; {<br>  realm   = &quot;aws-vpn&quot;<br>  enabled = true<br>}<br><br># --- Groups used to segment access ---<br>resource &quot;keycloak_group&quot; &quot;vpn&quot; {<br>  for_each = toset([&quot;DBA&quot;, &quot;REDSHIFT&quot;, &quot;EC2&quot;, &quot;ADMIN&quot;])<br>  realm_id = keycloak_realm.aws_vpn.id<br>  name     = each.value<br>}<br><br># --- SAML client: represents the AWS Client VPN ---<br>resource &quot;keycloak_saml_client&quot; &quot;clientvpn&quot; {<br>  realm_id  = keycloak_realm.aws_vpn.id<br>  client_id = &quot;urn:amazon:webservices:clientvpn&quot;<br>  name      = &quot;AWS Client VPN&quot;<br><br>  # The AWS VPN Client listens on 127.0.0.1:35001 to receive the assertion (ACS).<br>  valid_redirect_uris         = [&quot;http://127.0.0.1:35001&quot;, &quot;http://127.0.0.1:35001/&quot;]<br>  assertion_consumer_post_url = &quot;http://127.0.0.1:35001&quot;<br><br>  sign_documents            = true<br>  sign_assertions           = true<br>  client_signature_required = false<br>  force_post_binding        = true<br>  force_name_id_format      = true<br>  name_id_format            = &quot;username&quot;<br>}</pre><p>Now two details that <strong>make all the difference</strong>:</p><pre># (A) AWS rejects assertions with repeated SAML attribute names. The default<br># `role_list` scope injects several &lt;Attribute Name=&quot;Role&quot;&gt;, which breaks login<br># with &quot;The credentials received were incorrect&quot;. Zero out the scopes.<br>resource &quot;keycloak_saml_client_default_scopes&quot; &quot;clientvpn&quot; {<br>  realm_id       = keycloak_realm.aws_vpn.id<br>  client_id      = keycloak_saml_client.clientvpn.id<br>  default_scopes = []<br>}<br><br># (B) NameID = username (AWS uses this as the connected user&#39;s identity)<br>resource &quot;keycloak_saml_user_property_protocol_mapper&quot; &quot;username&quot; {<br>  realm_id  = keycloak_realm.aws_vpn.id<br>  client_id = keycloak_saml_client.clientvpn.id<br>  name      = &quot;username&quot;<br><br>  user_property              = &quot;username&quot;<br>  saml_attribute_name        = &quot;NameID&quot;<br>  saml_attribute_name_format = &quot;Unspecified&quot;<br>}<br><br># (C) memberOf = the user&#39;s groups → this is what AWS matches in authorization rules<br>resource &quot;keycloak_generic_protocol_mapper&quot; &quot;member_of&quot; {<br>  realm_id        = keycloak_realm.aws_vpn.id<br>  client_id       = keycloak_saml_client.clientvpn.id<br>  name            = &quot;memberOf&quot;<br>  protocol        = &quot;saml&quot;<br>  protocol_mapper = &quot;saml-group-membership-mapper&quot;<br><br>  config = {<br>    &quot;attribute.name&quot;       = &quot;memberOf&quot;<br>    &quot;attribute.nameformat&quot; = &quot;Unspecified&quot;  # ⚠️ do NOT use &quot;Basic&quot; — see &quot;Gotchas&quot;<br>    &quot;single&quot;               = &quot;true&quot;<br>    &quot;full.path&quot;            = &quot;false&quot;<br>  }<br>}</pre><h3>Step 2 — The IAM SAML Provider</h3><p>AWS needs to trust your Keycloak. That’s an <strong>IAM SAML Provider</strong> fed by the realm’s <em>metadata</em>. Two tricks:</p><pre># Fetch the realm metadata (depends on the realm already existing).<br>data &quot;http&quot; &quot;keycloak_saml_metadata&quot; {<br>  url        = &quot;https://keycloak.example.com/realms/aws-vpn/protocol/saml/descriptor&quot;<br>  depends_on = [keycloak_realm.aws_vpn]<br>}<br><br>locals {<br>  # AWS does not sign AuthnRequests; the metadata must reflect that, otherwise<br>  # Keycloak waits for a signature that never arrives.<br>  saml_metadata = replace(<br>    data.http.keycloak_saml_metadata.response_body,<br>    &quot;WantAuthnRequestsSigned=\&quot;true\&quot;&quot;,<br>    &quot;WantAuthnRequestsSigned=\&quot;false\&quot;&quot;,<br>  )<br>}<br><br>resource &quot;aws_iam_saml_provider&quot; &quot;clientvpn&quot; {<br>  name                   = &quot;clientvpn-keycloak&quot;<br>  saml_metadata_document = local.saml_metadata<br>}</pre><h3>Step 3 — The Client VPN endpoint (reusable module)</h3><p>A federated endpoint needs a <strong>server certificate</strong> in ACM (no client cert — auth is via the IdP). We generate a CA and the cert with the tls provider.</p><pre># --- CA + server certificate ---<br>resource &quot;tls_private_key&quot; &quot;ca&quot; {<br>  algorithm = &quot;RSA&quot;<br>  rsa_bits  = 2048<br>}<br><br>resource &quot;tls_self_signed_cert&quot; &quot;ca&quot; {<br>  private_key_pem       = tls_private_key.ca.private_key_pem<br>  is_ca_certificate     = true<br>  validity_period_hours = 87600<br>  allowed_uses          = [&quot;cert_signing&quot;, &quot;crl_signing&quot;]<br>  subject {<br>    common_name  = &quot;clientvpn-ca&quot;<br>    organization = &quot;MyOrg&quot;<br>  }<br>}<br><br>resource &quot;tls_private_key&quot; &quot;server&quot; {<br>  algorithm = &quot;RSA&quot;<br>  rsa_bits  = 2048<br>}<br><br>resource &quot;tls_cert_request&quot; &quot;server&quot; {<br>  private_key_pem = tls_private_key.server.private_key_pem<br>  # AWS requires a domain-format CN/SAN (with a dot).<br>  dns_names = [&quot;server.clientvpn.vpn&quot;]<br>  subject {<br>    common_name  = &quot;server.clientvpn.vpn&quot;<br>    organization = &quot;MyOrg&quot;<br>  }<br>}<br><br>resource &quot;tls_locally_signed_cert&quot; &quot;server&quot; {<br>  cert_request_pem      = tls_cert_request.server.cert_request_pem<br>  ca_private_key_pem    = tls_private_key.ca.private_key_pem<br>  ca_cert_pem           = tls_self_signed_cert.ca.cert_pem<br>  validity_period_hours = 87600<br>  allowed_uses          = [&quot;key_encipherment&quot;, &quot;digital_signature&quot;, &quot;server_auth&quot;]<br>}<br><br>resource &quot;aws_acm_certificate&quot; &quot;server&quot; {<br>  private_key       = tls_private_key.server.private_key_pem<br>  certificate_body  = tls_locally_signed_cert.server.cert_pem<br>  certificate_chain = tls_self_signed_cert.ca.cert_pem<br>}</pre><pre>The endpoint itself, federated and split-tunnel:</pre><pre>resource &quot;aws_security_group&quot; &quot;vpn&quot; {<br>  name        = &quot;clientvpn-sg&quot;<br>  description = &quot;Client VPN endpoint - egress to the VPC&quot;<br>  vpc_id      = var.vpc_id<br><br>  ingress {<br>    description = &quot;OpenVPN (UDP 443)&quot;<br>    from_port   = 443<br>    to_port     = 443<br>    protocol    = &quot;udp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br>  egress {<br>    from_port   = 0<br>    to_port     = 0<br>    protocol    = &quot;-1&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br>}<br><br>resource &quot;aws_ec2_client_vpn_endpoint&quot; &quot;this&quot; {<br>  description            = &quot;clientvpn&quot;<br>  server_certificate_arn = aws_acm_certificate.server.arn<br>  client_cidr_block      = &quot;10.100.0.0/22&quot;   # must not overlap the VPC or peers<br>  split_tunnel           = true<br>  transport_protocol     = &quot;udp&quot;<br>  vpn_port               = 443<br>  dns_servers            = [&quot;10.0.0.2&quot;]       # VPC resolver (private DNS)<br>  vpc_id                 = var.vpc_id<br>  security_group_ids     = [aws_security_group.vpn.id]<br><br>  authentication_options {<br>    type              = &quot;federated-authentication&quot;<br>    saml_provider_arn = var.saml_provider_arn<br>  }<br><br>  connection_log_options {<br>    enabled = false<br>  }<br>}<br><br># Associate ONE private subnet. The association automatically creates the route<br># for the entire VPC CIDR in the endpoint&#39;s own route table.<br>resource &quot;aws_ec2_client_vpn_network_association&quot; &quot;this&quot; {<br>  client_vpn_endpoint_id = aws_ec2_client_vpn_endpoint.this.id<br>  subnet_id              = var.subnet_id<br>}</pre><pre>  connection_log_options {<br>    enabled = false<br>  }<br>}</pre><pre># Associate ONE private subnet. The association automatically creates the route<br># for the entire VPC CIDR in the endpoint&#39;s own route table.<br>resource &quot;aws_ec2_client_vpn_network_association&quot; &quot;this&quot; {<br>  client_vpn_endpoint_id = aws_ec2_client_vpn_endpoint.this.id<br>  subnet_id              = var.subnet_id<br>}</pre><p>And the <strong>per-group authorization rules</strong> — the heart of segmentation. Each rule opens a CIDR to a Keycloak group (via access_group_id), or to everyone (via authorize_all_groups):</p><pre>variable &quot;authorization_rules&quot; {<br>  type = list(object({<br>    target_cidr     = string<br>    access_group_id = optional(string)  # null = all groups<br>    description     = optional(string, &quot;&quot;)<br>  }))<br>}</pre><pre>resource &quot;aws_ec2_client_vpn_authorization_rule&quot; &quot;this&quot; {<br>  for_each = {<br>    for r in var.authorization_rules :<br>    &quot;${r.target_cidr}-${coalesce(r.access_group_id, &quot;all&quot;)}&quot; =&gt; r<br>  }</pre><pre>  client_vpn_endpoint_id = aws_ec2_client_vpn_endpoint.this.id<br>  target_network_cidr    = each.value.target_cidr</pre><pre>  # Only ONE of the two may be set; the other stays null.<br>  authorize_all_groups = each.value.access_group_id == null ? true : null<br>  access_group_id      = each.value.access_group_id<br>  description          = each.value.description<br>}</pre><p>Example rule map (at the root):</p><pre>locals {<br>  vpn_authorization_rules = concat(<br>    # DNS resolver — open to everyone (otherwise client DNS breaks with the VPN up).<br>    [{ target_cidr = &quot;10.0.0.2/32&quot;, access_group_id = null }],<br>    # ADMIN reaches the whole VPC; DBA the databases; REDSHIFT the cluster; EC2 its range.<br>    [{ target_cidr = &quot;10.0.0.0/16&quot;,   access_group_id = &quot;ADMIN&quot; }],<br>    [{ target_cidr = &quot;10.0.1.0/24&quot;,   access_group_id = &quot;DBA&quot; }],<br>    [{ target_cidr = &quot;10.0.108.0/24&quot;, access_group_id = &quot;REDSHIFT&quot; }],<br>    [{ target_cidr = &quot;10.0.101.0/24&quot;, access_group_id = &quot;EC2&quot; }],<br>  )<br>}</pre><h3>Step 4 — The client .ovpn file</h3><p>Because auth is federated, the .ovpn has <strong>no client key or cert</strong> — just the endpoint address, the CA cert, and the auth-federate directive. It&#39;s the same file for everyone.</p><pre># client-config.ovpn.tftpl<br>client<br>dev tun<br>proto udp<br>remote ${endpoint} 443<br>remote-cert-tls server<br>cipher AES-256-GCM<br>verb 3</pre><pre>&lt;ca&gt;<br>${ca_cert}<br>&lt;/ca&gt;</pre><pre># Federated authentication (SAML): the AWS VPN Client opens the browser at the IdP.<br>auth-federate<br>auth-retry interact<br>reneg-sec 0</pre><pre>resource &quot;local_file&quot; &quot;ovpn&quot; {<br>  filename        = &quot;${path.root}/clientvpn.ovpn&quot;<br>  file_permission = &quot;0600&quot;<br>  content = templatefile(&quot;${path.module}/client-config.ovpn.tftpl&quot;, {<br>    endpoint = replace(aws_ec2_client_vpn_endpoint.this.dns_name, &quot;*&quot;, &quot;clientvpn&quot;)<br>    ca_cert  = tls_self_signed_cert.ca.cert_pem<br>  })<br>}</pre><h3>Step 5 — Wire it up and the toggle</h3><pre>module &quot;clientvpn&quot; {<br>  source = &quot;./modules/clientvpn&quot;</pre><pre>  vpc_id              = var.vpc_id<br>  subnet_id           = var.private_subnet_id<br>  saml_provider_arn   = aws_iam_saml_provider.clientvpn.arn<br>  authorization_rules = local.vpn_authorization_rules<br>}</pre><p>&gt; <strong>Operational tip:</strong> a count = var.enable_vpn ? 1 : 0 on each resource lets you flip the whole thing on and off with one flag. But beware: if your pipeline runs terraform apply <strong>without </strong><strong>-var</strong>, the effective value is always the <em>default</em>. Make the default reflect the desired state — if the VPN is permanent, default = true. A false default with an automated pipeline = a destroy plan on every run.</p><h3>Onboarding: granting someone access</h3><ol><li>In Keycloak, realm aws-vpn → <strong>Users → Add user</strong>.</li><li><strong>Credentials → Set password</strong>, with <strong>Temporary: OFF</strong> (see Gotchas).</li><li>Optionally, add the user to a group (DBA, EC2, …).</li><li>Hand over the .ovpn (via an internal channel — it has no secret, but avoid email).</li><li>The user installs the <strong>official AWS VPN Client</strong>, imports the profile, clicks <strong>Connect</strong>, logs in to Keycloak. Done.</li></ol><p>To test (no ping — the security groups don&#39;t allow ICMP):</p><pre>nc -vz your-database.example 5432   # should print &quot;succeeded!&quot;</pre><h3>Gotchas worth their weight in gold 🪙</h3><p>These cost hours if you don’t know them upfront:</p><ul><li><strong>memberOf with NameFormat </strong><strong>Basic → AWS silently ignores the group.</strong> AWS reads SAML attributes in Unspecified format (same as the NameID). With Basic, login works and the user connects, but <strong>no group is recognized</strong> — only authorize_all_groups rules pass, and every per-group access times out, looking like a network problem. Use <strong>Unspecified</strong>.</li><li><strong>The </strong><strong>role_list scope breaks the assertion.</strong> It injects multiple &lt;Attribute Name=&quot;Role&quot;&gt;; AWS rejects repeated attributes with <em>&quot;The credentials received were incorrect&quot;</em>. Zero out the default scopes.</li><li><strong>WantAuthnRequestsSigned must be </strong><strong>false</strong> in the metadata — AWS doesn&#39;t sign AuthnRequests.</li><li><strong>Authorize the DNS resolver</strong> (10.0.0.2/32) for all groups. Otherwise the machine&#39;s DNS breaks with the VPN up.</li><li><strong>A temporary password kills the SAML flow.</strong> The “change password on first login” step doesn’t work inside the VPN client — and the error shown is the misleading <em>“The credentials received were incorrect”</em>. Always <strong>Temporary: OFF</strong>.</li><li><strong>Changing an authorization rule drops active connections.</strong> If you’re testing a rule change, know the tunnel goes down — create the rule, reconnect, then test.</li></ul><h3>The result</h3><p>A VPN where:</p><ul><li>Nobody holds a VPN password or a client certificate.</li><li>Access follows corporate identity — disabled in Keycloak, gone.</li><li>All provisioning is code, reviewable in a pull request.</li><li>It costs about <strong>US$ 0.10/hour</strong> per subnet association, plus fractions of a cent per connection. enable_vpn = false zeroes it out.</li></ul><p>If this walkthrough saved you a few hours of debugging, drop a comment — and tell me which gotcha <strong>you</strong> hit. 🙂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e837db51de56" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>