Building a Website for an Agentic Era

I’ve been building advancedmortgagecalculator.my lately – a simulation engine focused on Malaysian banks’ mortgages, predicting interest charges, payments, and savings over the life of the loan. It got me thinking about how people are going to find my service – social media, search engines, links in a catalogue – but increasingly, it’s going to be AI agents like ChatGPT perusing the web on a human’s behalf. So the question:

If I want an AI agent to discover my web app, understand what it does, operate correctly, and interpret the result – what do I need to do?

That sent me down a surprisingly deep rabbit hole: first making sure agents could crawl the site at all, then giving them cleaner context with llms.txt and Markdown, then exposing the calculator through MCP, figuring out how that MCP server could be discovered, and finally experimenting with WebMCP so an agent could operate the live page itself. Along the way I also ran into a less technical question: if an agent can do everything for the user, where does that leave the website — and the ad revenue keeping it alive?

I know I went really hard in the opposite direction of most people (the “ban AI from my content” camp), but I hope to assure you it makes sense after this.

First Blocker: Cloudflare’s Managed robots.txt

The first thing I realised when asking ChatGPT to visit my website is that it says it is blocked. This is really strange, as I had already set a very permissive robots.txt:

robots.txt
User-agent: *
Allow: /
Sitemap: https://advancedmortgagecalculator.my/sitemap.xml

That basically signals to bots: “here’s my website, go nuts”.

Then I actually went there and realised Cloudflare had its “fully managed robots.txt” enabled on my zone, modifying my robots.txt.

Fortunately, this is easy to turn off.

I can understand where they are coming from with all the fear that AI is going to mine all the world’s information and sell it at a markup, but it is still annoying.

Explaining the Site to Agents: llms.txt

llms.txt is a proposed convention for a HOWTO guide for AI agents. You help agents discover and understand the website, as well as show them how to operate it. Here’s a snippet of what I have for my website:

# Advanced Mortgage Calculator Malaysia
> Model how changing rates, extra payments, fees, disbursements and redraws affect a Malaysian home loan, using bank-specific schedules and EPF or fixed-deposit comparisons.
Canonical site: https://advancedmortgagecalculator.my/
## Main tools
- [Mortgage repayment calculator](https://advancedmortgagecalculator.my/)
- [Guides](https://advancedmortgagecalculator.my/guides) — usage, extra-payment, interest-rate, EPF, and statement-import guides
- [About](https://advancedmortgagecalculator.my/about) — calculation scope and limitations
Malay pages use `/ms/`; Simplified Chinese pages use `/zh/`. Calculator settings are shareable in the page query string.

If your website has an MCP server, this is where you could point it out to the agent as well; there are more proposed conventions as well (more on that when I talk about MCP discovery).

Perhaps you may be wondering: “MCP server?! Isn’t this a mortgage calculator?”. I will answer that later as well.

Markdown for Agents

I saw that this “Markdown for Agents” is a paid feature in Cloudflare. Basically, you request with the Accept: text/markdown HTTP header and your server returns markdown instead of HTML:

curl -H 'Accept: text/markdown' https://advancedmortgagecalculator.my/about

---
title: About Advanced Mortgage Calculator
description: Why this Malaysian mortgage calculator models bank-specific interest calculations, changing rates, fees, disbursements, extra payments and EPF comparisons.
image: https://advancedmortgagecalculator.my/assets/seo-social.png
---
Why this exists
# Fidelity
I built this calculator because a home loan should be modelled as the bank actually treats it, not reduced to a convenient monthly-payment formula.
...

When I saw this I thought:

My content is already written in markdown and compiled to HTML – why do I need you to compile it back to markdown for me? I’ll add support myself.

Then it turns out I just did exactly what Cloudflare did and compiled the compiled HTML back into Markdown.

And the reason is simply that some of my Markdown files have HTML inside to support jump links and custom styling:

<header>
<h1>Mortgage Calculator Guide</h1>
<p class="page-intro">Learn how to model your Malaysian home loan, interest-rate changes, extra payments, EPF and FD returns and bank statements.</p>
<nav class="guide-jump" aria-label="On this page"><a href="#getting-started">Getting started</a> · <a href="#opr-sbr-rate-change">Interest rates</a> · <a href="#bank-selection">Banks</a> · <a href="#import-bank-statement">Bank statements</a> · <a href="#extra-payments">Extra payments</a> · <a href="#epf-vs-home-loan">EPF</a> · <a href="#fd-vs-home-loan">Fixed deposit</a> · <a href="#ai-assistants">AI assistants</a> · <a href="#statement-differences">Statement differences</a></nav>
</header>
<h2 id="getting-started">How do I use the mortgage calculator?</h2>
Enter your loan amount, interest rate and loan term. That is enough to see a repayment schedule.

Well, not a big deal – and also not sure if it was even worth doing, since agents like VS Code Copilot’s Fetch tool already converts fetched webpages to Markdown by itself anyway. At that point, I just thought I’d already done it, so whatever.

MCP Server

Now to the more questionable part of my journey: I implemented an MCP server for advancedmortgagecalculator.my. MCP — Model Context Protocol — is an open protocol that lets AI applications connect to external tools and data.

“Sounds crazy! Why is that even necessary?” – perhaps you may think, I think.

Because filling in the inputs is not trivial.

The mortgage calculator is not called “advanced” without reason; it replicates (or tries its best to) the individual transactions down to the last cent. This means requiring users to know when their interest rate changed, what extra payments were made, when fire insurance is charged, withdrawals from the redraw account, disbursements – which may easily overwhelm the casual user.

I’ve tried to make it easier by allowing users to upload their bank statements and filling in for them, but that has been quite complicated to implement, requires a lot of trust, and easily breaks when banks change their statements.

But what if an agent can just fill in the cumbersome details for you?

Suppose a user is comparing a loan between two banks. Hypothetically, he can simply say:

Compare a RM500,000 Maybank home loan over 30 years with and without a RM500 monthly extra payment.

And the AI agent would respond something like:

Using the MCP server with a 3.8% annual rate, starting 1 September 2026:

ScenarioMonthly PaymentPayoff DateTotal Interest
No extra paymentRM2,329.79June 2056RM333,746.95
RM500 extra monthlyRM2,829.79 totalMarch 2048RM230,211.14

The RM500 extra payment pays off the loan about 8 years and 3 months earlier and saves approximately RM103,535.81 in interest.

I’m not making this up, by the way. That is an unedited response from GPT-5.6 Luna in VS Code Copilot (and it costs me 0.4 credits). 3.8% here is simply the default interest rate on my website – the real rate really depends on the bank.

It’s a little disappointing that it didn’t point the human back to my website despite my explicit prompt to do so (“after the numbers look right, give the user details.url so they can open the same scenario in the full calculator”) – but I guess that’s something I can tweak.

So as you can see, there is a conflict of interest here from putting out an MCP server when my website depends on ad revenue to survive: if I hand out all my cards, the AI agent can just walk away with everything it needs and the user never even sets foot on my website. Hand out too little, and the MCP isn’t very useful to begin with. So I set a balance: I hand out the summary details – just enough information that an agent can gauge whether the inputs are correct — and then always direct the user to the website.

MCP Server Discovery

Ok, my MCP server is there – how does the agent even know it is there?

For one, my llms.txt will point the agent to it:

## MCP server
- Endpoint: https://advancedmortgagecalculator.my/mcp — MCP over Streamable HTTP, POST, stateless, no authentication.
- Discovery: https://advancedmortgagecalculator.my/.well-known/mcp.json
- Tool: `calculate_mortgage_scenario` — returns the monthly instalment, projected payoff
date, total interest, and optionally the balance/interest as of a given date.
- Headline figures only. Every response carries `details.url`; send the user there for the
amortisation schedule, charts and EPF/fixed-deposit comparisons.

And I also use .well-known/mcp.json:

{
"name": "my.advancedmortgagecalculator/mortgage-calculator",
"title": "Advanced Mortgage Calculator Malaysia",
"description": "Calculate Malaysian home-loan repayments, payoff dates, total interest, and balances as of a given date.",
"version": "3e8e076",
"websiteUrl": "https://advancedmortgagecalculator.my/",
"endpoint": "https://advancedmortgagecalculator.my/mcp",
"remotes": [
{
"type": "streamable-http",
"url": "https://advancedmortgagecalculator.my/mcp"
}
]
}

MCP discovery is still very much a moving target: /.well-known/mcp.json has been discussed by the MCP project, while other proposals have used /.well-known/mcp, and Server Cards themselves are still experimental. So this isn’t something I would call a standard — I’m basically putting up an extra signpost in case an agent knows to look for it.

WebMCP

Ok – this is probably the point where it gets too cutting-edge, but it’s pretty cool nonetheless.

The idea is that your web app exposes structured tools directly through the browser. Instead of an agent scraping your web page trying to figure out which buttons to click and fields to fill, it can call a tool exposed by the page, with the page’s own JavaScript handling the actual interaction.

“Whoa – that sounds kinda dangerous, don’t you think? Why would you let an agent do that?” – you may ask (I think).

To which I say, “…yes.”

Well first of all, you are granting the agent access to do that; my website is just making it easier for them instead of having agents execute Playwright code. Surely you don’t want agents to be autonomously making banking transactions on your behalf, but filling calculator inputs is a harmless use case.

So, guess my surprise when I went through the whole effort to add support, just to realise only paid plans of ChatGPT and Claude support this (let’s not mention unofficial extensions). In Chrome, WebMCP is currently an experimental origin trial. That would severely limit the number of people who can use this! Tech influencers be talking like this is the bees knees, but this is the unfortunate reality of WebMCP now.

There’s a workaround using @mcp-b/webmcp-local-relay, which runs a local MCP/WebSocket relay on your computer. A small script running in the webpage connects to that relay, allowing a desktop MCP client to see and invoke the WebMCP tools exposed by the page.

This works, by the way. I was able to have my AI agent auto-magically fill in the calculator inputs directly on my web app, but at the end of the day I removed the local relay because it was frankly too sus to have this around.

Conclusion

There are other agent-friendly improvements that aren’t really agent-specific — semantic HTML, solid SEO, and accessible/ARIA markup all help too — but the above were the highlights.

So my answer to the question I started with is: make the site crawlable, make it easy for agents to understand, expose complex operations as structured tools, make those tools discoverable, and — if it actually helps — let agents operate the live interface. The tricky part is deciding how much to expose: enough for the agent to be genuinely useful, but not so much that the website itself becomes irrelevant.

A lot of this is still in flux — llms.txt is a convention, MCP discovery is evolving, and WebMCP is still experimental — but it already works well enough to make the agentic web feel very real.

I’ve learned a lot in the process, and I’m grateful for the journey. Hope you had a great read (agents included)!

IRSA without EKS over Tailscale

So I have a kubernetes cluster running from my home lab, and I want my services to access AWS resources. Most obviously I can just place IAM user access keys there – but that would present 2 problems:

  1. It’s too easy – where’s the fun in that? We gotta make it complicated… to flex during interviews.
  2. Access keys are long-term credentials that by right you should periodically rotate.

At work, we use IAM roles for service accounts (IRSA) to grant access to AWS resources across a fleet of EKS clusters – we have tons of these IAM roles. Access is declarative and version-controlled, with short-lived tokens procured on demand and automatically refreshed as needed. I have troubleshot so many misconfigurations and typos that I have perhaps developed a masochistic love for it. So I felt I needed to bring it to my home lab setup.

Then I learned the beautiful truth: you don’t need EKS to use IRSA! Your rinky-dinky consumer-grade Kubernetes cluster is also able to assume an IAM role with the same authentication mechanism, instead of ~US$73/month just for a blank EKS cluster. Now you can spend countless hours troubleshooting IRSA misconfigurations, free of charge!

Before we begin, I’d like to point out this is fairly advanced material. If you’re new to devops or in a bit of a pinch, this is probably not the way to go.

Overview

When you use access keys, it’s pretty much like username and password – key them in and Bob’s your uncle: you are authenticated as an IAM user.

When you use IRSA, this happens:

  1. Kubernetes API server mints a short-lived OIDC token for your service account for AWS STS
  2. Your service uses said token to request to assume an IAM role.
  3. AWS STS service verifies your token and IAM role trust policy, allowing your service to assume the target IAM role.

Tools

With that out of the way, I am using the following:

We are going full terminal mode for this article, so buckle up!

Setting Up IRSA

Tailscale Configuration

Tailscale has this thing called MagicDNS that hands you a dedicated *.ts.net domain (e.g. terrain-vulture.ts.net), and a web app in said network (e.g. sudoku.terrain-vulture.ts.net) would usually only be accessible within your private Tailscale network, but when you use Funnel, it makes said web app publicly accessible. For free.

Not to say it is a great idea for every scenario, but for exposing our Kubernetes public OIDC endpoint, it does a decent job.

The one thing you need to ensure is that your ACL JSON (https://console.tailscale.com/admin/acls/file) has this:

JSON-LD
{
"tagOwners": {
"tag:k8s-operator": [],
"tag:k8s": ["tag:k8s-operator"],
},
"nodeAttrs": [
{
// Funnel policy, which lets tailnet members control Funnel
// for their own devices.
// Learn more at https://tailscale.com/kb/1223/tailscale-funnel/
"target": ["tag:k8s"],
"attr": ["funnel"],
},
],
}

Provisioning a Kubernetes Cluster

k3s is probably the easiest and most lightweight means of getting a Kubernetes cluster up and running.

Suppose we decided to call our OIDC endpoint k3s-oidc.terrain-vulture.ts.net, to spin up a single node cluster, we run:

Shell
curl -sfL https://get.k3s.io | sh -s - \
--kube-apiserver-arg=anonymous-auth=true \
--kube-apiserver-arg=service-account-issuer=https://k3s-oidc.terrain-vulture.ts.net \
--kube-apiserver-arg=service-account-jwks-uri=https://k3s-oidc.terrain-vulture.ts.net/openid/v1/jwks

anonymous-auth=true is important here, since by default k3s does not allow the Kubernetes control plane API to be accessed anonymously. Note this is not enough to expose publicly as the API is still gated by RBAC – this will be addressed later with the appropriate ClusterRoleBinding.

Now you should be able to use kubectl, and if you’re too lazy to copy over the kubeconfig, just run every kubectl command as sudo (e.g. sudo kubectl get nodes).

Now install the Tailscale Kubernetes Operator (refer to “Install the Tailscale Kubernetes Operator” for how to get OAuth credentials):

helm repo add tailscale https://pkgs.tailscale.com/helmcharts
helm repo update
helm upgrade \
--install \
tailscale-operator \
tailscale/tailscale-operator \
--namespace=tailscale \
--create-namespace \
--set-string oauth.clientId="<OAuth client ID>" \
--set-string oauth.clientSecret="<OAuth client secret>" \
--wait

Exposing Kubernetes OIDC Endpoint

Now create a ClusterRole, ClusterRoleBinding, and Ingress to allow only the public OIDC endpoint to be accessible without authentication. Create allow-oidc-public.yaml:

allow-oidc-public.yaml
YAML
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: allow-oidc-discovery-and-jwks
rules:
- nonResourceURLs:
- "/.well-known/openid-configuration"
- "/openid/v1/jwks"
verbs:
- "get"
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: allow-oidc-discovery-and-jwks-to-anonymous
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: allow-oidc-discovery-and-jwks
subjects:
- kind: Group
name: system:unauthenticated
apiGroup: rbac.authorization.k8s.io
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: k3s-oidc
annotations:
tailscale.com/funnel: "true"
spec:
ingressClassName: tailscale
tls:
- hosts:
- k3s-oidc
rules:
- http:
paths:
- path: /.well-known/openid-configuration
pathType: Prefix
backend:
service:
name: kubernetes
port:
number: 443
- path: /openid/v1/jwks
pathType: Prefix
backend:
service:
name: kubernetes
port:
number: 443

Then apply:

Shell
kubectl apply -f allow-oidc-public.yaml

If everything works as expected, you should be able to access it publicly now. Run this outside of your Tailscale network to be sure:

Shell
curl https://k3s-oidc.terrain-vulture.ts.net/openid/v1/jwks | jq
{
"keys": [
{
"use": "sig",
"kty": "RSA",
"kid": "DlxlQTKcp1E2IBrhXaTEPXS0-TxIt0n3CfmV9C9Z-A0",
"alg": "RS256",
"n": "vPouHFc2DAfTUcp7xlLhor8uc9sHIpl4APleT4upa_Peg_u6pT0xgNQnA_Cj69vD1pvXLg7_yVNjQrWbQ4RVzri8DhAhIY9QYqhgJMLdUAIYHl5gs1Ijn9xMOUYBkDSpRGxvMVHyoOad7m-5HbNcdM_GsP1CQLzqHLsC2REZyidm9BS1m4fYa0NselH16_SDcz-2ADPvQE74WW6q0K4rR7q1oeRdxtdqxlFa64Ys_zVcIZy2ccGL2Kvok0Wa5cPWTT_W_F20MH6Tac-Gq5r65akMzwOQD7Dz1TbPv-yEY7OPfS-s0sIj0d4UsjiMnF618gO5UNjDNY9RXAR3KZb9EQ",
"e": "AQAB"
}
]
}

Behind the scenes, the Tailscale Operator provisions the TLS certs automagically for your service. Is this not love?

Have AWS Trust Your OIDC

For security purposes, only identity providers you configure in your AWS accounts can assume your IAM roles. To do so, run:

Shell
aws iam create-open-id-connect-provider \
--url https://k3s-oidc.terrain-vulture.ts.net \
--client-id-list sts.amazonaws.com
{
"OpenIDConnectProviderArn": "arn:aws:iam::123456789121:oidc-provider/k3s-oidc.terrain-vulture.ts.net"
}

The command outputs the OIDC provider ARN, which you will use for more commands later.

Note that for as long as you need this working, AWS expects the OIDC endpoint to be publicly reachable.

AWS IAM Role and Test Resource

To test this out, we create a parameter store /k8s/pink-jaguar/message that simply stores the phrase “hello from k3s”:

Shell
aws ssm put-parameter \
--name "/k8s/pink-jaguar/message" \
--type String \
--value "hello from k3s"
{
"Version": 1,
"Tier": "Standard"
}

And create an IAM role named pink-jaguar that has the following:

  1. Trust policy allowing a kubernetes service account pink-jaguar from the default namespace to assume it
  2. Inline policy that grants it read access to parameter store created earlier
Shell
aws iam create-role \
--role-name "pink-jaguar" \
--assume-role-policy-document "$(
cat <<EOF
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": {
"Federated": "arn:aws:iam::123456789121:oidc-provider/k3s-oidc.terrain-vulture.ts.net"
},
"Action": "sts:AssumeRoleWithWebIdentity",
"Condition": {
"StringEquals": {
"k3s-oidc.terrain-vulture.ts.net:aud": "sts.amazonaws.com",
"k3s-oidc.terrain-vulture.ts.net:sub": "system:serviceaccount:default:pink-jaguar"
}
}
}]
}
EOF
)"
aws iam put-role-policy \
--role-name pink-jaguar \
--policy-name ReadK3sTestMessage \
--policy-document "$(
cat <<EOF
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": "ssm:GetParameter",
"Resource": "arn:aws:ssm:us-east-1:123456789121:parameter/k8s/pink-jaguar/message"
}]
}
EOF
)"
{
"Role": {
"Path": "/",
"RoleName": "pink-jaguar",
"RoleId": "AROAYAAABBBCCCDDDEEEV",
"Arn": "arn:aws:iam::123456789121:role/pink-jaguar",
"CreateDate": "2026-08-15T11:15:07+00:00",
"AssumeRolePolicyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Federated": "arn:aws:iam::123456789121:oidc-provider/k3s-oidc.terrain-vulture.ts.net"
},
"Action": "sts:AssumeRoleWithWebIdentity",
"Condition": {
"StringEquals": {
"k3s-oidc.terrain-vulture.ts.net:aud": "sts.amazonaws.com",
"k3s-oidc.terrain-vulture.ts.net:sub": "system:serviceaccount:default:pink-jaguar"
}
}
}
]
}
}
}

AWS doesn’t charge anything for these resources by the way – in case you’re too lazy to delete them later.

Dummy Kubernetes Workload

Create pink-jaguar.yaml:

pink-jaguar.yaml
YAML
apiVersion: v1
kind: ServiceAccount
metadata:
name: pink-jaguar
namespace: default
---
apiVersion: v1
kind: Pod
metadata:
name: pink-jaguar
namespace: default
spec:
restartPolicy: Never
serviceAccountName: pink-jaguar
containers:
- name: aws-cli
image: public.ecr.aws/aws-cli/aws-cli:2.36.24
command:
- sh
- -c
- |
aws ssm get-parameter \
--name "/k8s/pink-jaguar/message" \
--query 'Parameter.Value' \
--output text
env:
- name: AWS_ROLE_ARN
value: arn:aws:iam::123456789121:role/pink-jaguar
- name: AWS_WEB_IDENTITY_TOKEN_FILE
value: /var/run/secrets/aws/token
- name: AWS_REGION
value: us-east-1
volumeMounts:
- name: aws-token
mountPath: /var/run/secrets/aws
readOnly: true
volumes:
- name: aws-token
projected:
sources:
- serviceAccountToken:
path: token
audience: sts.amazonaws.com
expirationSeconds: 3600

The astute among you will notice there’s no eks.amazonaws.com/role-arn: arn:aws:iam::123456789121:role/pink-jaguar annotation on the service account. This is because unlike in EKS, your home-grown cluster has no Amazon EKS Pod Identity Webhook that adds the AWS environment variables and token volume mounts for you; you gotta roll it yourself.

Shell
kubectl apply -f pink-jaguar.yaml

serviceaccount/pink-jaguar created
pod/pink-jaguar created
Shell
kubectl logs -f pink-jaguar

hello from k3s

Great success!

Cleanup

Shell
# WARNING: This destroys your k3s cluster!
# Please ensure you are actually not using it!!
/usr/local/bin/k3s-uninstall.sh
aws ssm delete-parameter \
--name "/k8s/pink-jaguar/message"
aws iam delete-role-policy \
--role-name "pink-jaguar" \
--policy-name ReadK3sTestMessage
aws iam delete-role \
--role-name "pink-jaguar"
aws iam delete-open-id-connect-provider \
--open-id-connect-provider-arn "arn:aws:iam::123456789121:oidc-provider/k3s-oidc.terrain-vulture.ts.net"

You may also want to remove the Tailscale OAuth client and revert the ACL changes if you created them specifically for this exercise.

Conclusion

In this article, we learned I like free stuff.

I have also run through a secure but likely overcomplicated way to access AWS resources from your self-managed Kubernetes cluster. It involves exposing the public OIDC endpoint of your cluster’s built-in OIDC provider using Tailscale Funnel, and then provisioning a test service that is able to assume an IAM role to read a parameter store.

Totally unnecessary for a home lab, but very interesting indeed.

Having said that, if what you want is to flex during an interview, a pro tip is that you could use Terraform and ArgoCD and git the whole thing. And then invite your engineer friends to send AI-generated pull requests so you can gain experience troubleshooting IAM issues like a real SRE!

References

How to Build a WireGuard VPN

Yet another “build a WireGuard VPN” guide! This setup here is mostly automated with scripts and Infrastructure as Code. It is meant to be quick temporary VPN setup; you spin it up in a few minutes, do whatever and destroy after use. There’s only about 50 lines of bash to put everything together.

This guide is a little technical; guardrails not included.

Infrastructure

My setup is simply an AWS t2.micro EC2 instance created using CloudFormation. You can get the stack YML here.

The stack pulls the latest Ubuntu image, sets a static public IP address, sets up session manager, whitelists UDP port 51820, then runs the following setup script:

#!/bin/bash
apt update
apt install -y wireguard qrencode
cd /etc/wireguard/
# Generate server keys
wg genkey | tee private.key | wg pubkey > public.key
# Write config
NET=`lshw -C network | grep -oP '(?<=logical name: )\w+'`
cat <<EOF > wg0.conf
[Interface]
Address = 10.10.0.1/24
Address = fd86:ea04:1111::1/64
ListenPort = 51820
PostUp = sysctl -q -w net.ipv4.ip_forward=1
PostUp = sysctl -q -w net.ipv6.conf.all.forwarding=1
PostDown = sysctl -q -w net.ipv4.ip_forward=0
PostDown = sysctl -q -w net.ipv6.conf.all.forwarding=0
PostUp = iptables -A FORWARD -i wg0 -j ACCEPT; iptables -t nat -A POSTROUTING -o $NET -j MASQUERADE
PostDown = iptables -D FORWARD -i wg0 -j ACCEPT; iptables -t nat -D POSTROUTING -o $NET -j MASQUERADE
PrivateKey = `cat private.key`
EOF
# Start Wireguard service on boot
systemctl enable wg-quick@wg0
systemctl start wg-quick@wg0
view raw wg-setup.sh hosted with ❤ by GitHub

Lastly, it adds a wg-addclient executable which we will get to later.

To connect to the instance, use session manager. The URL is under “SSMURL” under the “Outputs” tab:

Just click on the link and you get remote access to the instance via your browser window.

If you don’t use AWS, you just need to run wg-setup.sh as root user in a publicly accessible Ubuntu server. Make sure to white list UDP port 51820 from any firewall.

This setup will cost you 0.01 USD per hour (us-east-1 region), or 0.24 USD a day; you can explore lighter instances for more cost savings by changing the “InstanceType” parameter of the stack.

I’ve also gotten this running with an Amazon ARM server (since they are having a free trial now for t4g.small until Dec 2023) with the following parameters to the CloudFormation stack:

  • InstanceType: t4g.small
  • LatestAmiId: /aws/service/canonical/ubuntu/server/jammy/stable/current/arm64/hvm/ebs-gp2/ami-id

Adding Clients

In the VPN server, execute wg-addclient as root user:

sudo -iu root
wg-addclient

Here is wg-addclient for your perusal:

#!/bin/bash
# Note: Must run as root!
cd /etc/wireguard/
# Get next available internal IP address
IP=$((`tac wg0.conf | grep -m1 -oP "[0-9]+(?=/32)" || echo 1` + 1))
# Generate client key
CLIENT_PRIVATE=`wg genkey`
CLIENT_PUBLIC=`wg pubkey <<< $CLIENT_PRIVATE`
# Append to server config
cat <<EOF >> wg0.conf
[Peer]
PublicKey = $CLIENT_PUBLIC
AllowedIPs = 10.10.0.$IP/32, fd86:ea04:1111::$IP/128
EOF
# Output client config and render QR
CONF=`mktemp`
trap "rm $CONF" EXIT
cat <<EOF | tee $CONF
[Interface]
PrivateKey = $CLIENT_PRIVATE
Address = 10.10.0.$IP/32
DNS = 8.8.8.8
[Peer]
PublicKey = `cat public.key`
AllowedIPs = 0.0.0.0/0, ::/0
Endpoint = `curl -s ifconfig.me`:51820
EOF
cat $CONF | qrencode -t ansiutf8
# Reload the Wireguard service
systemctl reload wg-quick@wg0
view raw wg-addclient.sh hosted with ❤ by GitHub

You will get an output that looks like this:

To add more clients, simply rerun wg-addclient.

Adding Client in iOS

Download the official WireGuard iOS app. Tap the “+” icon and select “Create from QR code” then scan the QR code generated from wg-addclient.

Follow the instructions that follow.

Adding Client in Windows

Download the official WireGuard Windows app. Go to “Add Tunnel” > “Add empty tunnel…”:

Give the tunnel a name and copy-paste the text contents from wg-addclient and click “Save”

Monitor Clients

Use the wg command:

# wg
interface: wg0
  public key: XSYfQReJui9ZYaLykAifNCaA5dn6MIHJjckl/nRkV0Y=
  private key: (hidden)
  listening port: 51820

peer: YEMGteQuySmdXCvwBlqIBIvGX/p4D32LbfE21nYLkm8=
  endpoint: 93.184.216.34:54114
  allowed ips: 10.10.0.3/32, fd86:ea04:1111::3/128
  latest handshake: 14 seconds ago
  transfer: 106.50 KiB received, 660.57 KiB sent

peer: DvLpEHPP5cFoX4nlFg0Jehq2RLZ0dBua/tEtRpXQvTI=
  endpoint: 93.184.216.34:53107
  allowed ips: 10.10.0.2/32, fd86:ea04:1111::2/128
  latest handshake: 1 minute, 4 seconds ago
  transfer: 721.85 KiB received, 3.46 MiB sent

In the example above, I have 2 clients (my phone and my laptop) connected. Your devices can only be referenced by their public key – there’s no built-in way to put a name to these devices.

Removing Clients

Internally, all wg-addclient does is append to /etc/wireguard/wg0.conf something like:

[Peer]
PublicKey = DvLpEHPP5cFoX4nlFg0Jehq2RLZ0dBua/tEtRpXQvTI=
AllowedIPs = 10.10.0.2/32, fd86:ea04:1111::2/128

And so to remove a client you remove the corresponding entry from wg0.conf and reload the WireGuard service:

systemctl reload wg-quick@wg0

Destroying the VPN

As mentioned earlier, this is meant to be a temporary VPN setup. Leaving this running long-term will probably cost you more and you should consider just paying for a VPN service.

Destroying the VPN is as easy as deleting the CloudFormation stack. All the corresponding resources (EC2, security group, EIP, IAM etc) will be cleanly removed and no further charges will be incurred.

Closing Remarks

  • Though I haven’t tried it, you could get WireGuard running with a nice admin UI similar to OpenVPN. See “Web UIs for WireGuard That Make Configuration Easier” for some good picks, though they will likely conflict with the setup here.
  • There’s a fully featured Wireguard install script by Nyr that works for multiple Linux distributions; has like 10x the amount of bash code.
  • This is not meant for production use.
  • You can probably only add 200 clients (why would you need so many??)
  • I don’t think any of the IPv6 stuff here is really needed; the EC2 instance I spun up does not even have an IPv6 address.
  • None of the keys you see here are going to be usable once this post is up.
  • You should not share your generated keys or VPN QR codes on the internet.
  • You should thoroughly understand any script you execute from some random blogger on the internet 😉.

References:

Secure by Design: Cybersecurity is Important for Developers

So I was briefly involved in some project that was probably built back in the early days of the web – back when most developers wrote vanilla PHP scripts and thought JQuery was cool, before the enlightened era of batteries included web frameworks like Rails or Laravel. I was faced with security practices so ancient or nonexistent that it was arduous to hammer down all the loopholes – it was like a hopeless game of whack-a-mole.

This convinced me that the best way to secure a system is to start early: right from the systems design itself, bubbling up to its individual components; the system should be secure by design. This is only possible if architects and developers are cognizant of security vulnerabilities. At the very least, we can steer clear of obvious amateur mistakes. And so begins my journey to dig a bit deeper into the cybersecurity world.

Björn Kimminich’s Juice Shop

This is where I stumbled upon the benevolent OWASP initiative, which is on a noble mission to improve software security through open-source initiatives and community education (yes, I just copied that from their website). I spent a month or so fiddling with their Juice Shop project, which is a super advanced e-commerce app/pedagogical tool that is loaded with insecure code and bad practices. Most of the information here is distilled from what I learnt from trying out the challenges and reading their source code.

Screenshot of the Juice Shop web app

Even if what you intend to do career-wise is build cool stuff, and even if most web frameworks would already have best practices bootstrapped, I highly recommend the Juice Shop. I have really nothing more than praise for Björn Kimminich’s work and the community behind it. I love how hands-on it is in showing first-hand how perfectly fine written code can hide exploits when you don’t know what to be looking out for.

A General Guide for Secure Design

There are a lot of general guidelines out there, but if I sum things up to one piece of advice it is this: your system is only as secure as its weakest link. It only takes a silly bug or some innocent negligence to introduce an attack vector.

It is important to note that secure design is very hard. More than just memorizing a list of possible exploits, a developer needs solid fundamentals in operating systems, networking, databases, cryptography etc to understand how a hacker can exploit this knowledge in creative ways to hack a system. It is challenging enough for developers to track the plethora of knowledge just to build a usable system to get their million-dollar startup off the ground, and often times security becomes an afterthought in the process. As such, I do not imply from these general outlines that secure design is trivial, but that they are important nonetheless.

I can’t say I’m an expert; it’s obvious to me that what I learned is simply the tip of the iceberg. In fact, I take very little interest in actually becoming a security expert or pen tester. But I hope my points here will be of use to the dear reader.

#1: Never trust user-generated input.

Assume that any user input can come from a skilled hacker with an innate understanding of how your system works. Always question whether the data you are receiving can be tampered or forged. It does not matter whether it’s the date time, HTTP header, user agent: if it is from a client, it can be tampered. Do not depend on these values in any serious application logic. Assume the client application can be compromised. Assume the user will do absolutely everything but how you intended your service to be used. Use strict input validation (like JSON schema) to limit API requests to only what is necessary and sanitise anything that can be vulnerable to injection attacks. Pay close attention when any part of the user input will be sent to an interpreter (e.g. SQL query, javascript eval, template engines). Any time an application uses an interpreter of any type there is a danger of introducing an injection vulnerability (Case study: Node.js VM context is a weak sandbox)

#2: Anything exposed to the public will be exploited.

If an endpoint is meant for development purposes, don’t assume somebody will not find it just because it is not accessible from the main site or is not documented. Don’t assume that just because a secret public endpoint is only known to your engineering team, it is safe. On a related note, you must make sure you do not display debugging information like stack trace or database error messages in your production environment. It displays a lot of information to help in debugging, but it also displays a lot of information for a hacker to figure out how to exploit your system. If an endpoint is meant for internal use (like Prometheus‘s /metrics), make sure it cannot be accessed outside of the internal network. Assume hackers are clairvoyant! If it is out there, he will find it!

#3: Scrutinize your tech stack and application dependencies.

What complicates security is that vulnerabilities can be very specific to the OS, platform, library, tool, software package, and programming language you use. It is practically impossible to memorise all possible attack vectors specific to every stack, but at the very least, do a quick google search to see what are known vulnerabilities of every component of your tech stack. For example, if you are going to use XML to store data, be mindful of XXE exploits, or if you are going to process zip files from users, take note of zip slip. Known vulnerabilities are typically publicly documented in the main documentation itself, marked visibly for all to see. For example, in the PHP manual for the mysqli_real_query function:

In any case, as a developer, you should read the main documentation (instead of just copypasta from someone’s blog), cause hackers also read them!

In addition, just as important as the code you write is the code you didn’t write but depend on. For sensitive code that does authentication, you want to pay close attention (e.g. like your JWT library), but really any one of your dependencies can be a potential attack vector. If any one of your application dependencies is compromised, an attacker can gain access to your system. A good example of this is the eslint-scope incident, where an attacker gained access to a maintainer’s account and published a modified version of the eslint-scope NPM library that attempts to exfiltrate a victim’s npm account credentials. Check your dependencies for typosquatting, and ensure the library authors are trustworthy (you can use tools like Snyk to automate this process).

#4: Limit service access as much as possible.

In the industry, this practice is often referred to as the principle of least privilege. If your service does not need to access a database, do not make it accessible to that database. Consider the event in which an attacker can execute arbitrary commands (via remote code execution or RCE) to your compromised service, and what files or endpoints be exposed to the attacker. Be particularly careful when you use the same server to run multiple services or store data. In general, for production environments, it is a good idea to use a separate server or VM for the database.

Keep your network as heavily firewalled as possible and monitor any unusual ingress egress requests (you could use a service like CrowdSec). Traditionally you could compartmentalize services by segregating your internal network into their respective subnets, but in containerized environments like k8s, internal networks can be declaratively created by the container orchestrator. Never run your service as a root user. Consider creating a unique user for the service only; in the event an attacker can perform RCE, its access is limited. Containerised environments like Docker provide a good sandbox to prevent an attacker from accessing sensitive files (/etc/passwd, private keys etc) in the host server.

#5: Read up on development best practices related to security.

It is a good idea to be mindful of well-known attack vectors, and existing solutions to mitigate them. Be mindful of where you get your sources. Don’t just take any blogger’s word (like mine) as gospel. A good place to start is OWASP cheat sheet. If you are active on YouTube, I suggest checking out PwnFunction and Liveoverflow.

Epilogue

Now, though this post talks about software development, cybersecurity is more than that. My point is to emphasise the importance of cybersecurity in software development, which is often overlooked especially in the early stages of development. In truth, cybersecurity extends beyond the systems you design: often times people become the weak link, but this is not the focus of this post.

Cybersecurity is an ongoing process. It is never a one-off where your system is henceforth secure. Yes, a solid foundation and clean architecture go a long way, but vulnerabilities can easily be introduced by an innocuous change at a later date. Similarly, your education on cybersecurity (and really computer science in general) is never a one-off process. New vulnerabilities rear their ugly heads from time to time, and hackers always find ingenious exploits in ostensibly secure systems; it will truly surprise you how smart hackers are.

Naturally, it is difficult to keep up with all the news of current vulnerabilities, and even stringent code reviews may not suffice. In addition, it can be a conflict of interest to both push out new features on time and consider all the ways an attacker can mess with them. Thus, development with good security practices in mind is not a substitute for having periodic security audits, a security team, or bounty programmes.

Setting Up Phan in VSCode

Intro

You can skip straight to “Setting Up Phan VSCode Extension“.

True story – I was in a client’s development environment one day and realised that I was able to login to my account with literally any password I keyed in. I went to the source code (PHP) and found out that somebody added code that looked something like:

if ($password = "very-secret-passphrase") {
    // login without checking password…
}

But that means only if my password is “very-secret-passphrase” will I be able to login right? Wrong. This is because he placed an assignment operator (=) instead of an equality operator (==), so the condition is true always and therefore I can login as any user even if I skipped putting a password.

The fact that code like this is even possible blows my mind 🤯. I decided there has to be some tool out there that can spot this kind of silly mistake to begin with.

Phan: PHP static code analysis

Overlooking that this is bad practice and that there is no proper testing, enter phan – a tool for PHP static code analysis!

I first took note of Phan when Rasmus Lerdorf (the creator of PHP) introduced it in his talk (“25 Years of PHP”). I thought it would be great if it could pick up silly code like checking the condition of an expression that is always true.

And it did (see a live demo running straight from your browser at https://phan.github.io/demo/):

PhanRedundantConditionInGlobalScope Redundant attempt to cast $password of type 'very-secret-passphrase' to truthy in the global scope (likely a false positive)

Out of the box, VSCode doesn’t have this built-in, so I got lazy and see if PHPStorm had it. Turns out they have it in their issue tracker for 6 years now – the Jetbrains folks probably didn’t think it was important.

Setting Up Phan VSCode Extension

The current developer of phan (Tyson Andre) also has created a VSCode extension “PHP Phan (Analyzer)“.

In my setup, I’m using Windows 11, with PHP installed via XAMPP and the PHP bin directory (defaults to C:\xampp\php) placed in my environment PATH.

You can also refer to phan’s wiki for phan setup instructions.

Phan depends on php-ast so I had to install it first. The suggested method of using pecl did not work for me (Fatal error: Array and string offset access syntax with curly braces is no longer supported), so I need to install using the prebuilt windows DLL at https://github.com/nikic/php-ast#installation.

In their file server, I downloaded the latest DLL I can find (php_ast-1.0.16-8.1-ts-vs16-x64.zip) and extracted php_ast.dll to my PHP extension folder at C:\xampp\php\ext\.

I then added to C:\xampp\php\php.ini this line:

extension=php_ast.dll

With php-ast installed, I install phan (as of this writing v5.3.2) globally via composer:

composer global require phan/phan

The executable will then be available phan.

Now cd to your project directory to generate a config file for phan (level 1 is the strictest setting):

phan --init --init-level=1

The file will be at .phan/config.php. You will need to edit the file to set the PHP target version (mine is 7.4) and the directories it reads:

'target_php_version' => '7.4',
'directory_list' => [
    'src',
],

Then the extension needs to be configured. To do this you can edit VSCode’s settings.json (File > Preferences > Settings, enter “@ext:TysonAndre.php-phan” at the search bar):

"phan.analyzedProjectDirectory": "C:/PATH/TO/PROJECT/DIRECTORY/",
"phan.phanScriptPath": "C:/Users/bruce/AppData/Roaming/Composer/vendor/bin/phan"
"phan.allowPolyfillParser": false,
"phan.redundantConditionDetection": true,
"phan.unusedVariableDetection": true,

You can find your phanScriptPath by entering in the command prompt (if you’re in Windows, remember to change the back slashes to forward slashes!):

where phan

I didn’t need to pass in the phanScriptPath since the extension has phan built-in – however, the extension is out of date (current is 5.3.2, the extension is still using 5.1.0), and the warning I want to see is only in the newer version.

Now restart VSCode, and the extension should work:

Phan static code analysis can be viewed from the editor and the problems tab

Note that the extension only analyzes a file when you open it, so the results take a few seconds to show up.

Extension Limitations

My main gripe with this extension is that it is only limited to a single project directory. The author is cognizant of this and writes in the extension settings description: “In the future, this VS Code extension may support analyzing more than one project“.

I had tried substituting C:/PATH/TO/PROJECT/DIRECTORY/ with ${workspaceFolder} (ref: VSCode Variables Reference), but it doesn’t seem to be supported.

Sounds great – but considering this extension hasn’t been updated for almost a year, I wouldn’t place any bets on that.

Even so, you can consider me a big phan – cause phan is phantastic! 😉