More from Ian's Blog
This post is a living diary of all the times I messed up something with my website in a funny way. I value those who have the confidence to own their mistakes and share the learning with others, and so this is me doing just that! That Time I Accidentally Made a Tarpit That Time I Accidentally Made Really Large Headers That Time I Accidentally Made a Tarpit Back to Top A "tarpit" is an unofficial term used in computing to describe an intentionally slow response to a request. In these modern times many people are using tarpits as a way to combat the relentless theft of data by AI companies, although there's little to no evidence of that actually being in any way effective. I don't use tarpits, at least not intentionally, but there was that one time when I accidentally created a tarpit and trapped all visitors in it. As I've shared previously, I refuse connections from IP addresses that are blocked or belong to a blocked subnet, and I enforce this firewall during the TCP handshake. The logic here is straightforward: there's no reason to waste resources doing a TLS handshake, accepting an HTTP request, and then rejecting the connection if I already know I'm going to reject it at the earliest step. At the time, the code worked like this: the HTTP server would repeatedly call the Accept() function below expecting a new connection. I've added some comments to help explain the logic. func (l *firewallListener) Accept() (net.Conn, error) { // Accept the connection from the TCP listener. This blocks until there is a connection to accept or the listner was closed. conn, err := l.l.AcceptTCP() if err != nil { return conn, err } // Separate the IP address out from the remote address (which includes the port) ip := utils.SocketStringToIPAddress(conn.RemoteAddr().String()) if ip == nil { return nil, nil } // Check if it's blocked, if so close the connection and return a refuseError if IsBlocked(ip, true) { conn.Close() return nil, &refuseError{} } // Otherwise return the connection on to the HTTP server return conn, nil } If the incoming connection was from a blocked IP then I'd return a refuseError. I need to use a specific error interface because the HTTP server will halt if it encounters a non-temporary error from the call to Accept(), so I need to return an error that satisfies the definition of a temporary error. I defined refuseError like this: type refuseError struct{} func (e *refuseError) Error() string { return "." } func (e *refuseError) Timeout() bool { return true } func (e *refuseError) Temporary() bool { return true } func (e *refuseError) Is(err error) bool { return err == context.DeadlineExceeded } This did accomplish the goal of rejecting connections before the TLS handshake for blocked addresses, but it had one really unintended and difficult to track down side-effect. Accepting connections is done serially, after which servers typically then process that request on a dedicated thread (or in Go's case a goroutine). This means that any delays during the accept loop will block all incoming connection. What I had missed while reviewing the code for Go's HTTP server is that when it receives a temporary error from Accept() is that while it doesn't abort, it does sleep for up to a maximum of 1 second. This sleep blocks the entire server for all incoming connections. You can see a trimmed copy of the code that does this below, with some marks I've added which I will explain. // src/net/http/server.go // Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. for { // (1) rw, err := l.Accept() if err != nil { if s.shuttingDown() { return ErrServerClosed } // (2) if ne, ok := err.(net.Error); ok && ne.Temporary() { if tempDelay == 0 { tempDelay = 5 * time.Millisecond } else { tempDelay *= 2 } if max := 1 * time.Second; tempDelay > max { tempDelay = max } s.logf("http: Accept error: %v; retrying in %v", err, tempDelay) // (3) time.Sleep(tempDelay) continue } return err } connCtx := ctx if cc := s.ConnContext; cc != nil { connCtx = cc(connCtx, rw) if connCtx == nil { panic("ConnContext returned nil") } } tempDelay = 0 c := s.newConn(rw) c.setState(c.rwc, StateNew, runHooks) // before Serve can return // (4) go c.serve(connCtx) } At mark 1 the server calls the Accept() function, this is the exact function that I defined above where I might return a temporary error. At mark 2 it checks if an error was returned, and if so if that error is temporary. If there was a temporary error, at mark 3 it sleeps for an increasing amount of time up-to 1 second, otherwise, at mark 4 it processes the connection on a dedicated goroutine, which allows the server to accept the next connection. I'm not entirely sure why the Go developers added this sleep delay and the change when it was introduced doesn't provide any meaningful insight. Regardless, it caused significant latency connecting to my website when a flood of rejected requests was coming in. It just goes to show how important it is to write meaningful commit messages, because you never know when somebody might come back years later wondering "why was this done?". I sure home I don't come to eat those words later. Coincidentally, you can actually see this happening if you look carefully at one of the metric graphs I shared in my first post about my server's security model: Securing My Web Infrastructure. This is the graph I shared in that blog post and while I didn't know it at the time, the fact that these request spikes all cap-out at around 60 requests per minute was not a coincidence. These requests were not being made with a limit in mind, attackers rarely ever care about things like that, instead it the accidental tarpit I had created. The downside to this was that while the malicious requests were being rate-limited, all requests were being rate-limited, up to a point of taking so long they timed out. The Fix Fixing the issue was relatively straightforward enough. Instead of returning a temporary error to the HTTP server during the accept loop, just don't return anything at all and wait for the next valid connection. func (l *firewallListener) Accept() (net.Conn, error) { for { conn, err := l.l.AcceptTCP() if err != nil { return conn, err } ip := utils.SocketStringToIPAddress(conn.RemoteAddr().String()) if ip == nil { return nil, nil } if IsBlocked(ip, true) { conn.SetLinger(0) conn.Close() continue } return conn, nil } } Now, when the HTTP server calls Accept(), the only time it returns is with a connection from an IP that isn't blocked, or if there genuinely is an error. No more sleep delays, no more excessive timeouts. That Time I Accidentally Made Really Large Headers Back to Top For about 10 years now all major browsers have support for a security feature known as a Content Security Policy or CSP. A CSP is an HTTP header provided by the server that instructs the browser on where it can load assets from, this could be scripts, images, stylesheets, fonts, etc. The objective of using a CSP is to prevent against injected HTML that tries to load assets, such as a malicious Javascript file, from a remote source. With so much user-provided content being available online, it's very possible for this to happen without an attacker compromising the entire web server. CSP protects against that by saying "scripts can only be loaded from these domains". That's a really simplified way of looking at it, anyways. My web server supports injecting the CSP header automatically, but before I go on I need to explain a little bit about the structure of my web server. When an incoming HTTP request is accepted (having passed all firewall checks and assertions), we look at the destination host for the request. This can either be the value of the Host header or as specified during the TLS handshake. We then look at a map of hosts to apps. Apps are just an interface that accept a few methods: type App interface { Cleanup() ReloadConfig() ServeHTTP(rw http.ResponseWriter, r *http.Request) Setup(dataDir string) error Shutdown() } One of the apps is the Proxy app, which is a reverse proxy - it accepts the incoming HTTP request and then proxies it on to another host. This is a very common design, especially with increasingly complex TLS setups. Because each app is unique to a host, and different hosts have different requirements for CSP rules, the proxy app includes a CSP preset that we use to build the header value, or skip it entirely. When the proxy app was going to copy an HTTP request to the downstream host, it would build the CSP header, however there was a slight bug... func (a *App) ServeHTTP(rw http.ResponseWriter, inRequest *ht2.Request) { // --snip -- if a.CSP != nil { a.CSP.ConnectSrc += " " + inRequest.Origin } CopyHttpRequest(inRequest, outRequest, rw, CopyHttpRequestOptions{ Origin: inRequest.Origin, Csp: a.CSP, Cors: a.CORS, AddHeaders: !a.SkipHeaders, UseHTTP3: a.UseHTTP3, InsecureTLS: a.InsecureTLS, }) } I'm really unsure as to what I was doing with the line to append to the ConnectSrc, but the impact is that I'm appending to a variable that lives on the App, rather than a variable that is per-request. This meant that every time there was a request to the app, any request at all, the origin would be appended to the header value. This went on for quite a long time unnoticed and unresolved, largely because I am constantly tweaking and tinkering with my web server, after all, it's how I made having a website fun again. Each time I restarted the server process, the header value would be reset, but only for it to continue to grow and grow. Eventually, after a period of being busy with other matters, the server process stayed running for long enough that the header value grew too large and HTTP clients began to reject it. There is no defined maximum for an HTTP header value, however most HTTP clients use 100KiB, which is perfectly reasonable, and this header value would continue to grow well beyond that. Diagnosing this issue turned out to be difficult as tools like Curl would fail with errors relating to entities being too large, but stopped short of saying what specifically. I eventually used openssl s_client to send an HTTP request by hand and observed my terminal window being filled with a domain name repeated thousands of times. Looking at the commit history, it was really unclear why I added the culprit lines of code. The commit message just says "Improved CSP support". It just goes to show how important it is to write - hey look it's those words I'm now having to eat! The Fix The fix was to just delete those three lines of code. Yup, it really was that simple, and fixing this bug actually made a larger positive impact than I had expected, as it was immediately clear when I fixed the bug by looking at outbound network bytes: So much traffic was being wasted on excessive header sizes. You might look at these mistakes I've made and think "wow, Ian, these are some obvious mistakes, I never would have made them!" to which I say "good for you!" with the utmost sarcasm and disdain. I enjoy making and refining software, and making anything means making mistakes along the way. Each time I make mistakes such as the ones above, I improve my skills of investigation, diagnosing, and repair. Skills that, judging by my peers in the industry, seemingly everyone is quickly willing to throw away because a robot does it "better" than you. Header Image: "Car accident on the Ffestiniog to Bala road. Nobody was hurt" by Geoff Charles, CC BY-SA 4.0, via Wikimedia Commons.
On March 30th 2016 the first commit of TLS Inspector, back then called Certificate Inspector, was made - and just shy of two weeks later version 1.0 was released. Now, 10 years later, TLS Inspector celebrates its 10th year, and I've got some exciting changes to share with you all. A Not-So-Quick History The original idea for TLS Inspector came about when I was travelling on a passenger ferry between Vancouver Island and mainland Vancouver. The operator, BC Ferries, provided free WiFi at the time, which was useful as cell service is spotty out in the water. However, this free WiFi wasn't working right, as all TLS Connections were failing with untrusted certificates (even though no captive portal was being presented). I looked in the App Store for any app that could help see what was going on, and found nothing but a one, very limited app filled with in-app-purchases. "I could probably write something like this myself", I thought, and so began TLS Inspector. In 2017 the app caught the attention of cryptologist Kenn White, who reached out to me and provided invaluable feedback. After a short and intensive development cycle, TLS Inspector graduated from a small proof-of-concept into the tool it is today, with release 1.5 being the first where the app gained widespread use. Originally named "Certificate Inspector", the app was renamed to "TLS Inspector" after DigiCert issued a cease-and-desist over the use of the name. In many ways, I felt that this was a good thing in the end, as the new name better reflects what the app is truly about - inspecting the entire TLS connection - not just certificates. Modernization In August 2023 I began work on implementing support for DNS over HTTPS within the app, however this feature never came to realization. Instead, my attention shifted into focusing this new-found DNS energy towards a new app, DNS Inspector. Even though TLS Inspector never got this feature, I did gain one piece of valuable insight from the effort; the realization that TLS Inspector's codebase was quickly aging, and was at serious risk of being left behind. When TLS Inspector was first released, Swift was still a very new language, and those familiar with Swift's early days will recount the growing pains it had, where every year there were major breaking changes to the language and APIs. In addition, Swift did not offer functional interoperability with C for many years - this made using Swift in TLS Inspector anywhere from impossible to incredibly difficult. As a result, Objective-C was used. However by 2019 Swift has significantly matured, and so I was comfortable splitting the app into two components - a Swift-based UI and an Objective-C based backend. Despite its maturity, its C interoperability was still very new and, frankly, very bad, so this design made sense. Apple has been investing an immense amount of time and effort into evolving and growing Swift, and they could not be more clear that the future of Apple Development is exclusively on Swift - SwiftUI is a great example of this. DNS Inspector was my first official SwiftUI app, and served as a validation test for both me and the platform, to answer the question of "do I feel it's ready?", and the answer was yes. Today we finally mark the completion of our transition to Swift, as TLS Inspector 3.0 written 100% in Swift, including all interaction with C libraries. Three-Point-O Let's get one thing clear right away: the experience you've come to expect from TLS Inspector is not changing. This effort to completely rewrite the app was also done with a strong desire to not change how the app worked. I, like many of you, dislike when a tool you may rely on suddenly changes how it works. Tradespeople don't just wake up one morning to suddenly find that their hammer had a software update and now it works entirely differently, why should TLS Inspector? I'm making a point of stressing this because I'm being quite serious when I say that this update is a total rewrite of the application. Nearly every component you see below has been substantially to entirely rewritten. And no, before you ask, the phrase "biting off more than you can chew" means nothing to me. TLSUI Before I get into talking about what changes I made, I want to clarify what I mean when I talk about things like SwiftUI or a "Swift-based user interface", because those sound like the same thing. So, buckle up, because it's time to learn about UIKit. Ask anyone who'd developed a native desktop application for macOS (no, not Electron) and they will absolutely gush about how much they love AppKit, and you can count me among one of those people! When Apple was building iPhoneOS (which later became iOS), they naturally wanted to reuse what they could from OS X, AppKit being no exception. However, as countless designers will tell you, user interfaces designed for touch screens absolutely do not work for traditional keyboard-and-mouse PCs. Apple knew this, and forked AppKit over to UIKit so the two could diverge cleanly. UIKit was, and I suppose still technically is, how you make native user interfaces on iOS apps. Apple provides you with three ways to work with UIKit: Do it entirely in code by yourself Use Xcode Interface Builder (.nib and .xib) Use Storyboards Storyboards are just a fancy way of joining together xibs, so realistically 2 and 3 are the same thing. When referring to the "Swift-based User Interface" of TLS Inspector before version 3.0, I'm referring to option #3 above. TLS Inspector previously used storyboards with UIKit for the entire UI. Initially being written in Objective-C and later ported over to use Swift. SwiftUI, however, takes a different approach. SwiftUI is Apple's attempt at modernizing the user interface tooling provided to developers by dropping interface builders and storyboards, and going all-in on declarative interfaces. As mentioned earlier, DNS Inspector was a test for me to see if I felt that SwiftUI was ready for da big leagues (as we say in the biz). The answer was a confident mostly sorta kinda yes. It's very clear that Apple is pouring a lot of resources into building out SwiftUI, and with every iOS release it gets better! The problem is that with every iOS release Apple changes things, and I hate when they do that! Unlike when Apple releases a new version of The Swift Language, SwiftUI is a runtime framework, which makes supporting old iOS versions quite annoying. Although, to be fair, I'm sure people found AppKit annoying during its early years. I only hopped on the UIKit train after it had almost 10 years to mature. SwiftUI has a lot of extremes. On one hand, it makes creating List-based interfaces (which used UITableView before) such a breeze, but at the same exact time there's bizarre limitations where your best bet is to just abandon SwiftUI and fall back to UIKit elements. Anyways, enough history and preamble, let's finally talk about the new user interface: As I said about 8 billion words ago, the goal here was not to dramatically change TLS Inspector - just to give it a gussy up, at most. The Main View The main view of the app has been tidied up, primarily by removing the Tip section. Let's be real, you don't need to be reminded that you can inspect websites from other apps every single time you use TLS Inspector. The advanced inspection parameters can be accessed by tapping on the gear (or cog, if you speak metric). Response View The response views are largely unchanged aside from adding more information. The app now highlights the root certificate in the chain as well as performs a reverse DNS lookup on the remote address. The trust details view has been tidied up to provide more direct information about the trust situation. Additionally, specific trust failures will also have what I call "Safety Warnings", which highlight when common indicators-of-compromise have been detected, directing users to engage with Apple support or a trusted friend. A "quick exit" button will immediately exit the app. Certificate Information The certificate information screen has been somewhat reorganized, moving the alternate names right to the top, and improving support for new "subject-less" certificates such as those issued by Let's Encrypt. In addition, there's several new datapoints provided: The results from CRL or OCSP checks are now displayed The source of the certificate is displayed (if the certificate was sent by the server or found on the device) All X.509 extensions are displayed, even those not understood by the app TLSKit TLSKit is the name of the "Backend" of the app - this is a Swift Package that performs all of the inspection tasks, collects and presents the results. Previously TLS Inspector used CertificateKit, which was a classic Objective-C based framework for accomplishing the same goals. However, CertificateKit contained some of the oldest and (in my opinion) worst code of the app. It was a frequent source of crashes and locked me out from enjoying new features with Swift Packages since it used legacy code and legacy tools. TLSKit is more than just a Swfit-rewrite of CertificateKit, however, because I took this as a perfect oppertunity to go back to the drawing board and rethink how the backend should work given how the app works today. Remember, CertificateKit contained some of the oldest code, back from before I really knew what I was doing or what I wanted TLS Inspector to be. External Dependencies A major hurdle that proved as a total "Go/No Go" test for this rewrite was the ability to use external dependencies in a Swift package, namely Curl and OpenSSL. After doing some initial research it appeared as if Apple had finally added proper Foreign function interface (FFI) support in Swift. This means one could directly invoke C function calls in these libraries within Swift without the need for an Objective-C bridge. However, in my effort to utilize Swift Packages, I needed to find a way to link to precompiled static libraries. To solve this puzzle, I reached out on the Apple Support forums, and with help from the fine folks there we were able to untangle this mess and get things working. An exciting prospect I plan to work on after 3.0 has stablized is moving away from OpenSSL towards using WolfSSL. This will also unlock the ability to inspect QUIC connections, something not currently possible in the app. It Takes A Village To say this was a massive undertaking for just one guy who does this part time is an understatement, and it's clear that I never could have done this alone. I cannot wrap things up here without giving my sincerest of thank you to the following: David (aka Catfish_Man), for their incredible patience and guidance helping me with the Swift 6 transition. Quinn (aka "The Eskimo"), for repeatedly helping me get through difficult tooling challenges on the Apple developer forums. All of the people who helped test the app. You helped me catch some real nasty bugs early and provided such great feedback. ChatGP- nah just kidding. could you imagine though? lol.
Turns out buying Air Pods from eBay is risky, who knew? Well, clearly I didn't because I totally fell for one. I was looking to pick up some used AirPods Pro 2 to use while out on walks or whenever my usual over-ears wouldn't be comfortable. I found a decent-enough looking listing that was selling a "opened and used once, but otherwise new" set for only 30% off what Apple is asking. Seems fair, right? Wrong. What arrived in my postbox were counterfeits, and I'm left out of pocket (at least, until eBay processes my refund request). In the meantime, I went and did what I should've done from the start and just bought a genuine pair from a retailer, partly because I still actually want a pair, but now also because I want to compare the two side-by-side and show you all the differences. The Packaging The front of the counterfeit box is actually very well done. The printing is close enough to the real one that without a genuine to compare against you'd have a really hard time telling if its fake. The box is even embossed correctly. Remember that these were sold to me as having been opened, so the fact the box is a little smushed doesn't really mean anything. The rear of the boxes is where we start to begin to see differences, although nothing immediately telling of a fake without a genuine box to compare against. It's interesting that the fake box does not show the USB-C cable like the genuine one does. Note: I had already unsealed the fake box. The box arrived sealed and in plastic shrink-wrap. The genuine box did not come in plastic wrap. The bottoms of the boxes begin to show some of the key differences between a real and fake box. On the real box, Apple has printed all information to the box itself, including the serial number. The fake box uses stickers for everything. The contents of the box don't give away too many clues. I had unwrapped the included charging cable myself for reasons you'll see later, it was wrapped when I first opened it. The bud bits additional tips contain a few clues, notably the worse printing the size labels and the lack of the indentions in the packaging. The Charging Case The exterior of the case reveals no clues. The only visual difference is the difference in assembly location (which I wouldn't be comfortable saying identifies it as a fake), and the different typeface used for the labels. This is very hard to identify without a known-good comparison. However, while impossible to demonstrate with pictures, the feel of the fake case is notably worse than the real one. The fake case rattles when you shake it and sounds hollow when you tap it. The real one feels dense with no rattles. Inside the case looking at the serials we start to see some more key differences. While my phone's camera is doing no favours to the image, the printing quality on the fake pods is notably worse. In addition, note the lack of input and output power requirements The Individual Pods This is where the counterfeits really begin to standout. Whoever made this case did a really good job, but whoever did the pods did not. Genuine AirPods have vents on and around the body. These aren't just for style, and are actual grills. Fake AirPods, like mine, just use styled plastic fillers. In addition, the pre-installed tip should include its size embossed into the rubber Lastly, a very important thing to check, the serial number of each individual pod should be unique - it should not match the serial of the charging case. These are three individual products each with their own serials. Apple should label all 3 on the box, instead the only label the charging case. The Hard Evidence Taking the serial number of the charging case, M6WYX2HJKR, and putting it into Apple's warranty check tool, I am presented with irrefutable evidence of the forgery: USB-C, you say?
Securing My Web Infrastructure A few months ago, I very briefly mentioned that I've migrated all my web infrastructure off Cloudflare, as well as having built a custom web service to host it all. I call this new web service WebCentral and I'd like to talk about some of the steps I've taken and lessons I've learned about how I secure my infrastructure. Building a Threat Model Before you can work to secure any service, you need to understand what your threat model is. This sounds more complicated than it really is; all you must do is consider what your risks how, how likely those risks are to be realized, and what the potential damage or impact those risks could have. My websites don't store or process any user data, so I'm not terribly concerned about exfiltration, instead my primary risks are unauthorized access to the server, exploitation of my code, and denial of service. Although the risks of denial of service are self-explanatory, the primary risk I see needing to protect against is malicious code running on the machine. Malicious actors are always looking for places to run their cryptocurrency miners or spam botnets, and falling victim to that is simply out of the question. While I can do my best to try and ensure I'm writing secure code, there's always going to be the possibility that I or someone else makes a mistake that turns into an exploitable weakness. Therefore, my focus is on minimizing the potential impact should this occur. VPS Security The server that powers the very blog you're reading is a VPS, virtual private server, hosted by Azure. A VPS is just a fancy way to say a virtual machine that you have mostly total control over. A secure web service must start with a secure server hosting it, so let's go into detail about all the steps I take to keep the server safe. Network Security Minimizing the internet-facing exposure is critical for any VPS and can be one of the most effective ways to keep a machine safe. My rule is simple, no open ports other than what is required for user traffic. In effect this only means one thing: I cannot expose SSH to the internet. Doing so protects me against a wide range of threats and also reduces the impact from scanners (more on them later). While Azure itself offers several of ways to interact with a running VPS, I've chosen to disable most of those features and instead rely on my own. I personally need to be able to access the machine over SSH, however, so how do I do that if SSH is blocked? I use a VPN. On my home network is a WireGuard VPN server as well as a Dynamic DNS setup to work-around my rotating residential IP address. The VM will try to connect to the WireGuard VPN on my home network and establish a private tunnel between them. Since the VM is the one initiating the connection (acting as a client) no port must be exposed. With this configuration I can effortlessly access and manage the machine without needing to expose SSH to the internet. I'm also experimenting with, but have not yet fully rolled out, an outbound firewall. Outbound firewalls are far, far more difficult to set up than inbound because you must first have a very good understanding of what and where your machine talks to. OS-Level Security Although the internet footprint of my VPS is restricted to only HTTP and HTTPS, I still must face the risk of someone exploiting a vulnerability in my code. I've taken a few steps to help minimize the impact from a compromise to my web application's security. Automatic Updates First is some of the most basic things everyone should be doing, automatic updates & reboots. Every day I download and install any updates and restart the VPS if needed. All of this is trivially easy with a cron job and built-in tooling. I use this script that runs using a cron job: #!/bin/bash # Check for updates dnf check-update > /dev/null if [[ $? == 0 ]]; then # Nothing to update exit 0 fi # Install updates dnf -y update # Check if need to reboot dnf needs-restarting -r if [[ $? == 1 ]]; then reboot fi Low-Privileged Accounts Second, the actual process serving traffic does not run as root, instead it runs as a dedicated service user without a shell and without sudo permission. Doing this limits the abilities of what an attacker might be able to do, should they somehow have the ability to execute shell code on the machine. A challenge with using non-root users for web services is a specific security restriction enforced by Linux: only the root user can bind to port at or below 1024. Thankfully, however, SystemD services can be granted additional capabilities, one of which is the capability to bind to privileged ports. A single line in the service file is all it takes to overcome this challenge. Filesystem Isolation Lastly, the process also uses a virtualized root filesystem, a process known as chroot(). Chrooting is a method where the Linux kernel effectively lies to the process about where the root of the filesystem is by prepending a path to every call to access the filesystem. To chroot a process, you provide a directory that will act as the filesystem root for that process, meaning if the process were to try and list of contents of the root (/), they'd instead be listing the contents of the directory you specified. When configured properly, this has the effect of an filesystem allowlist - the process is only allowed to access data in the filesystem that you have specifically granted for it, and all of this without complicated permissions. It's important to note, however, that chrooting is often misunderstood as a more involved security control, because it's often incorrectly called a "jail" - referring to BSD's jails. Chrooting a process only isolates the filesystem from the process, but nothing else. In my specific use case it serves as an added layer of protection to guard against simple path transversal bugs. If an attacker were somehow able to trick the server into serving a sensitive file like /etc/passwd, it would fail because that file doesn't exist as far as the process knows. For those wondering, my SystemD service file looks like this: [Unit] Description=webcentral After=syslog.target After=network.target [Service] # I utilize systemd's heartbeat feature, sd-notify Type=notify NotifyAccess=main WatchdogSec=5 # This is the directory that serves as the virtual root for the process RootDirectory=/opt/webcentral/root # The working directory for the process, this is automatically mapped to the # virtual root so while the process sees this path, in actuality it would be # /opt/webcentral/root/opt/webcentral WorkingDirectory=/opt/webcentral # Additional directories to pass through to the process BindReadOnlyPaths=/etc/letsencrypt # Remember all of the paths here are being mapped to the virtual root ExecStart=/opt/webcentral/live/webcentral -d /opt/webcentral/data --production ExecReload=/bin/kill -USR2 "$MAINPID" TimeoutSec=5000 Restart=on-failure # The low-privilege service user to run the process as User=webcentral Group=webcentral # The additional capability to allow this process to bind to privileged ports CapabilityBoundingSet=CAP_NET_BIND_SERVICE [Install] WantedBy=default.target To quickly summarize: Remote Access (SSH) is blocked from the internet, a VPN must be used to access the VM, updates are automatically installed on the VM, the web process itself runs as a low-privileged service account, and the same process is chroot()-ed to shield the VMs filesystem. Service Availability Now it's time to shift focus away from the VPS to the application itself. One of, if not the, biggest benefits of running my own entire web server means that I can deeply integrate security controls how I best see fit. For this, I focus on detection and rejection of malicious clients. Being on the internet means you will be constantly exposed to malicious traffic - it's just a fact of life. The overwhelming majority of this traffic is just scanners, people going over every available IP address and looking widely known and exploitable vulnerabilities, things like leaving credentials out in the open or web shells. Generally, these scanners are one and done - you'll see a small handful of requests from a single address and then never again. I find that trying to block or prevent these scanners is a bit of a fool's errand, however by tracking these scanners over time I can begin to identify patterns to proactively block them early, saving resources. Why this matters is not because of the one-and-done scanners, but instead the malicious ones, the ones that don't just send a handful of requests - they send hundreds, if not thousands, all at once. These scanners risk degrading the service for others by occupying server resources that would better be used for legitimate visitors. To detect malicious hosts, I employ some basic heuristic by focusing on the headers sent by the client, and the paths they're trying to access. Banned Paths Having collected months of data from the traffic I served, I was able to identify some of the most common paths these scanners are looking for. One of the more common treds I see if scanning for weak and vulnerable WordPress configurations. WordPress is an incredibly common content management platform, which also makes it a prime target for attackers. Since I don't use WordPress (and perhaps you shouldn't either...) this made it a good candidate for scanner tracking. Therefore, any request where the path contains any of: "wp-admin", "wp-content", "wp-includes", or "xmlrpc.php" are flagged as malicious and recorded. User Agents The User Agent header is data sent by your web browser to the server that provides a vague description of the browser and the device it's running on. For example, my user agent when I wrote this post is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:128.0) Gecko/20100101 Firefox/128.0 All this really tells the server is that I'm on a Mac running macOS 15 and using Firefox 128. One of the most effective measures I've found to block malicious traffic early is to do some very basic filtering by user agent. The simplest and most effective measure thus far has been to block requests that have no user agent header. I also have a growing list of bogus user agent values, where the header looks valid - but if you check the version numbers of the system or browser, nothing lines up. IP Firewall When clients start getting a bit too rowdy, they get put into the naughty corner temporarily blocked from connecting. Blocked connections happen during the TCP handshake, saving resources as we skip the TLS negotiation. Addresses are blocked 24 hours, and I found this time to be perfectly adequate as most clients quickly give up and move on. ASN Blocks In some extreme situations, it's necessary to block entire services and all of their addresses from accessing my server. This happens when a network provider, such as an ISP, VPN, or cloud provider, fails to do their job in preventing abuse of their services and malicious find home there. Cloud providers have a responsibility to ensure that if a malicious customer is using their service, they would terminate their accounts and stop providing their services. For the most part, these cloud providers do a decent enough job at that. Some providers, however, don't care - at all - and quickly become popular amongst malicious actors. Cloudflare and Alibaba are two great examples. Because of the sheer volume of malicious traffic and total lack of valid user traffic, I block all of Cloudflare and Alibaba's address space. Specifically, I block AS13335 and AS45102. Putting It All Together Summarized, this is the path a request takes when connecting to my server: Upon recieving a TCP connection, the IP address of the client is checked if it's either in a blocked ASN or is individually blocked. If so, the request is quickly rejected. Otherwise, TLS is negotiated, allowing the server to see the details of the actual HTTP request. We then check if the request is for a banned path, or has a banned user agent, if so the IP is blocked for 24 hours and the request is rejected, otherwise the request is served as normal. The Result I feel this graph speaks for itself: This graph shows the number of requests that were blocked per minute. These bursts are the malicious scanners that I'm working to block, and all of these were successful defences against them. This will be a never-ending fight, but that's part of the fun, innit?
According to the Wayback Machine, I launched my website over a decade ago, in 2013. Just that thought alone makes me feel old, but going back through the old snapshots of my websites made me feel a profound feeling of longing for a time when having a website used to be a novel and enjoyable experience. The Start Although I no longer have the original invoice, I believe I purchased the ianspence.com domain in 2012 when I was studying web design at The Art Institute of Vancouver. Yes, you read that right, I went to art school. Not just any, mind you, but one that was so catastrophically corrupt and profit-focused that it imploded as I was studying there. But thats a story for another time. I obviously didn't have any real plan for what I wanted my website to be, or what I would use it for. I simply wanted a web property where I could play around with what I was learning in school and expand my knowledge of PHP. I hosted my earliest sites from a very used Dell Optiplex GX280 tower in my house on my residential internet. Although the early 2010's were a rough period of my life, having my very own website was something that I was proud of and deeply enjoyed. Somewhere along the way, all that enjoyment was lost. And you don't have to take my own word for it. Just compare my site from 2013 to the site from when I wrote this post in 2024. Graphic Design was Never My Passion 2013's website has an animated carousel of my photography, bright colours, and way too many accordions. Everything was at 100% because I didn't really care about so much about the final product more as I was just screwing around and having fun. 2024's website is, save for the single sample of my photography work, a resume. Boring, professional, sterile of anything resembling personality. Even though the style of my site became more and more muted over the years, I continued to work and build on my site, but what I worked on changed as what I was interested in grew. In the very early 2010s I thought I wanted to go into web design, but after having suffered 4 months of the most dysfunctional Art school there is, I realized that maybe it was web development that interested me. That, eventually, grew into the networking and infrastructure training I went through, and the career I've built for myself. Changing Interests As my interests changed, my focus on the site became less about the design and appearance and more towards what was serving the site itself. My site literally moved out from the basement suite I was living in to a VPS, running custom builds of PHP and Apache HTTPD. At one point, I even played around with load-balancing between my VPS and my home server, which had graduated into something much better than that Dell. Or, at least until my internet provider blocked inbound port 80. This is right around when things stopped being fun anymore. When Things Stopped Being Fun Upon reflection, there were two big mistakes I made that stole all of the enjoyment out of tinkering with my websites: Cloudflare and Scaling. Cloudflare A dear friend of mine (that one knows I'm referring to it) introduced me to Cloudflare sometime in 2014, which I believe was the poison pill that started my journey into taking the fun out of things for me. You see, Cloudflare is designed for big businesses or people with very high traffic websites. Neither of which apply to me. I was just some dweeb who liked PHP. Cloudflare works by sitting between your website's hosting server and your visitors. All traffic from your visitors flows through Cloudflare, where they can do their magic. When configured properly, the original web host is effectively hidden from the web, as people have to go through Cloudflare first. This was the crux of my issues, at least with the focus of this blog post, with Cloudflare. For example, before Lets Encrypt existed, Cloudflare did not allow for TLS at all on their free plans. This was right at the time when I was just starting to learn about TLS, but because I had convinced myself that I had to use Cloudflare, I could never actually use it on my website. This specific problem of TLS never went away, either, as even though Cloudflare now offers free TLS - they have total control over everything and they have the final say in what is and isn't allowed. The problems weren't just TLS, of course, because if you wanted to handle non-HTTP traffic then you couldn't use Cloudflare's proxy. Once again, I encountered the same misguided fear that exposing my web server to the internet was a recipe for disaster. Scaling (or lack thereof) The other, larger, mistake I made was an obsession with scaling and security. Thanks to my education I had learned a lot about enterprise networking and systems administration, and I deigned to apply those skills to my own site. Aggressive caching, using global CDNs, monitoring, automated deployments, telemetry, obsession over response times, and probably more I'm not remembering. All for a mostly static website for a dork that had maybe 5 page views a month. This is a mistake that I see people make all the time, not even just exclusive for websites - people think that they need to be concerned about scaling problems without first asking if those problems even or will ever apply to them. If I was able to host my website from an abused desktop tower with blown caps on cable internet just fine, then why in the world would I need to be obsessing over telemetry and response times. Sadly things only got even worse when I got into cybersecurity, because now on top of all the concerns with performance and scale, I was trying to protect myself from exceedingly unlikely threats. Up until embarrassingly recently I was using complicated file integrity checks using hardware-backed cryptographic keys to ensure that only I could make changes to the content of my site. For some reason, I had built this threat model in my head where I needed to protect against malicious changes on an already well-protected server. All of this created an environment where making any change at all was a cumbersome and time-consuming task. Is it any wonder why I ended up making my site look like a resume when doing any changes to it was so much work? The Lesson I Learned All of this retrospective started because of the death of Cohost, as many of the folks there (myself included) decided to move to posting on their own blogs. This gave me a great chance to see what some of my friends were doing with their sites, and unlocking fond memories of back in 2012 and 2013 when I too was just having fun with my silly little website. All of this led me down to the realization of the true root cause of my misery: In an attempt to try and mimic what enterprises do with their websites in terms of stability and security, I made it difficult to make any changes to my site. Realizing this, I began to unravel the design and decisions I had made, and come up with a much better, simpler, and most of all enjoyable design. How my Website Used to Work The last design of my website that existed before I came to the conclusions I discussed above was as follows: My website was a packaged Docker container image which ran nginx. All of the configuration and static files were included in the image, so theoretically it could run anywhere. That image was being run on Azure Container Instances, a managed container platform, with the image hosted on Azure Container Registries. Cloudflare sat in-front of my website and proxied all connections to it. They took care of the domain registration, DNS, and TLS. Whenever I wanted to make changes to my site, I would create a container image, sign it using a private key on my YubiKey, and push that to Github. A Github action would then deploy that image to Azure Container Registries and trigger the container to restart, pulling the new image. How my Website Works Now Now that you've seen the most ridiculous design for some dork's personal website, let me show you how it works now: Yes, it's really that simple. My websites are now powered by a virtual machine with a public IP address. When users visit my website, they talk directly to that virtual machine. When I want to make changes to my website, I just push them directly to that machine. TLS certificates are provided by Lets Encrypt. I still use Cloudflare as my domain registrar and DNS provider, but - crucially - nothing is proxied through Cloudflare. When you loaded this blog post, your browser talked directly to my server. It's almost virtually identical to the way I was doing things in 2013, and it's been almost invigorating to shed this excess weight and unnecessary complications. But there's actually a whole lot going on behind the scenes that I'm omitting from this graph. Static Websites Are Boring A huge problem with my previous design is that I had locked myself into only having a pure static website, and static websites are boring! Websites are more fun when they can, you know, do things, and doing things with static websites is usually dependent on Javascript and doing them in the users browser. That's lame. Let's take a really simple example: Sometimes I want to show a banner on the top of my website. In a static-only website, unless you hard-code that banner into the HTML, doing this from a static site would require that you use JavaScript to check some backend if a banner should be displayed, and if so - render it. But on a dynamic page? Where server-side rendering is used? This is trivially easy. A key change with my new website is switching away from using containers, which are ephemeral and immutable, over to using a virtual machine, which isn't, and to go back to server-side rendering. I realized that a lot of the fun I was having back then was because PHP is server-side, and you can do a lot of wacky things when you have total control over the server! I'm really burying the lede here, but my new site is powered not by nginx, or httpd, but instead my own web server. Entirely custom and designed for tinkering and hacking. Combined with no longer having to deal with Cloudflare, has given me total control to do whatever the hell I want. Maybe I'll do another post some day talking about this - but I've written enough about websites for one day. Wrapping Up That feeling of wanting to do whatever the hell I want really does sum up the sentiment I've come to over the past few weeks. This is my website. I should be able to do whatever I want with it, free from my self-imposed judgement or concern over non-issues. Kill the cop in your head that tells you to share the concerns that Google has. You're not Google. Websites should be fun. Enterprise tools like Cloudflare and managed containers aren't.
More in technology
There is a long history to chemical and biological warfare—one that, we at least hope, ended in 1993. The paucity of chemical and biological warfare today is a result of long-standing objections that culminated in the 1993 Chemical Weapons Convention. It is striking that this formal end to most chemical weapons programs came within a year of the last US test of a nuclear weapon: similar sentiments, and a similar 1990s "end of history" context, motivated both. The similarity makes the differences more striking. Nuclear weapons are still part of the pop culture today, the quintessential "weapon of mass destruction" and a symbol of the destructive potential of modern warfare. But what of that term? Why "weapons of mass destruction?" The history of the phrase WMD is complex, and while it does predate nuclear weapons our modern use emerged in response to them. Still, it's a broader category. In today's language, WMD refers to nuclear, biological, or chemical weapons. Some of its most prominent invocations, namely in the Iraq War, referred to chemical rather than nuclear warfare. Still, to most Americans, chemical weapons are out of sight and out of mind. There are a few reasons: chemical weapons have been more or less prohibited in warfare for over one hundred years, so we have little experience with or memory of them. In fact, today, in the United States, there are none. That was the modern chemical war: the safe management, recovery, and destruction of an enormous stockpile of chemical weapons. This effort spanned military reservations across the United States, dismantling and burning chemical and biological munitions as life went on as usual outside of the fence. Well, at least, "as usual" for the Cold War: one of the effects of the stockpile was to maintain a sort of localized Cold War climate in those towns that fell downwind of it. Today, with the discovery of a dangerously poorly managed stockpile of Lead Azide that will require an exceptionally risky emergency measure to destroy, we are all acutely aware of the direction that the wind blows. The upcoming plume of lead over Iowa is far from the first time that dangerous compounds have blown away from military custody. There have been dozens of such incidents, with varying degrees of intentionality and risk to the public. Many were, at the time, classified. Others were simply covered up. While not exactly the future we wanted, it is perhaps a sign of progress that the upcoming detonation has been announced at all. The public notifications seem, to me, to be the result of an attitude shift that happened at the tail end of the era of US chemical warfare. Windblown plume forecasting models, originally developed for the fallout of nuclear war, were reapplied to risk analysis of chemical weapon stockpiles. The news was bad, so bad that civilian towns were hardened against attack: not enemy attack, but an attack of bad luck, an accident upwind. But first, we should consider how we got there. There are accounts of chemical and biological warfare dating to antiquity, although as with most early history it can be hard to tell what was speculative and what was actually done. By the 18th century, there had certainly been multiple uses of poisons and noxious chemicals on the battlefield. Chemical weapons in particular took a revolutionary step forward with the development of a more formal science of chemistry, during the 19th century. Several important advancements in chemistry occurred in the pursuit of poisonous gases, and just about every other advance in chemistry was applied to them. Still, even in this early era, there was more of an appetite for the development of chemical weapons than for their actual use. A particularly memorable incident in this history comes from Lyon Playfair, the very same who popularized the "Playfair Cipher" that makes a standard appearance in cryptography classes. In his role as a key scientific official during the Crimean War of the mid-1850s, he proposed the use of shells that would disperse a very poisonous form of Cyanide. Objections to the plan came not from pacifist do-gooders but from the weapons-builders themselves, who considered the whole thing morally questionable. Playfair's words in response are almost haunting in consideration of what would follow, outcomes of which he was simultaneously prescient and shockingly short-sighted. War is destruction, and the more destructive it can be made with the least suffering the sooner will be ended that barbarous method of protecting national rights. No doubt in time chemistry will be used to lessen the suffering of combatants, and even of criminals condemned to death. One of the reasons for the lackluster popularity of chemical weapons is that this notion of "easing the suffering" of the enemy, even if accepted as something other than madness, never really materialized. Particularly in the 1990s, the ethics of capital punishment in the United States came to be seen as sort of a technical problem. Maybe homicide by the state wasn't so bad if it was "painless," or "quick," or at least clinical in its appearance. The same idea pervaded chemical warfare in the 19th century, and in the 20th century it fell short in the same way that lethal injection has now. Objection to chemical weapons generally preceded their use. The Hague Convention of 1899 prohibited the form of chemical weapon that was then most obvious, the gas shell. That this prohibition applied specifically to artillery shells is significant: one of the complexities of chemical warfare is its interaction with domestic use. Like hollow-point bullets, tear gas, for example, is widely used in many nations' interiors—but it has been prohibited in warfare for many decades. This situation was already apparent with the first large-scale use of chemical weapons, at the onset of the First World War. Tear gas, a broad category of irritants that are not generally fatal but induce painful and disabling effects, was first developed in France. Parisian police struggled with organized criminal groups who would barricade themselves into buildings and successfully repel attempts at arrest. A commission was formed to investigate the matter in 1912, and it recommended the adoption of ethyl bromoacetate. Delivered to a barricaded position, it caused uncontrollable tearing, difficulty breathing, and considerable pain—enough to drive gangsters out of cover. That development in policing might have been controversial in its own right, but it was quickly overshadowed by the outbreak of the Great War. Tear gas was adapted to hand grenades, directed against the Germans at Alsace in 1914. In practice, this early chemical attack proved ineffective, but it opened Pandora's box. The Germans developed their own irritant shells, both sides justifying their use by leaning on the term "asphyxiating gas" in the Hague convention. Tear gases are unpleasant, but they are not asphyxiating as the term is defined. It was a slippery slope, though, and once the gears of war were in motion they would not be stopped. German chemists improved both the chemical agents and the means of delivery, such that during 1915 a drifting cloud of Chlorine gas was used to scatter French soldiers holding a defensive line. As it happened, the reticence of the Germans to march into their own poisonous cloud meant that they gained little advantage, but it proved the concept. Once again, the legality of the measure was questioned, but this time, the Germans emphasized the Hague convention's specific use of the word "shells"—no artillery shells having been involved in this particular weapon. Faced with this new threat, both sides developed countermeasures, and faced with those countermeasures, both developed new weapons. By the end of 1915 Phosgene was in wide use, and in 1917, the Germans introduced Mustard Gas. Mustard is a terrifying weapon, causing severe blistering of any exposed skin and extensive bleeding. Mustard Gas was extensively used by both sides, becoming part of routine infantry strategy, and along the way dooming tens of thousands of soldiers to a torturous ordeal in the overwhelmed military hospitals. Ironically, despite the extreme response it induced, Mustard Has was not particularly fatal. Many of its victims survived, disfigured after a long period of extreme suffering. These were the stories that came to be associated with chemical warfare. Far from Playfair's vision of "the least suffering," Mustard Gas became one of the war's main sources of it. Mustard-exposed soldiers convalescing in rows, their skin covered in blisters, their eyes sealed closed... these were the images that defined chemical warfare for decades to follow. While some use of chemical weapons continued after the First World War, Mustard Gas inspired a level of outrage that hung over the 1925 Geneva Conference. The Hague convention's prohibition on shells with asphyxiating gas was narrow enough that Mustard Gas arguably did not apply, so negotiators at Geneva agreed to stronger language. The Geneva Protocol, entering into force in 1928, broadly prohibited the use of chemical or biological agents in warfare between states. That could have been the end of the story. The Geneva Protocol was not perfectly observed, but it did prevent almost all use of such weapons. Despite significant technological advances made in Germany, including the development of several nerve agents during the 1930s, World War II elapsed with only limited use of chemical or biological weapons in combat. Most chemical attacks were by the Japanese, perhaps less affected by the experience of the First World War, and even then were directed mostly against other combatants in Asia. On the European front, only a handful of chemical attacks took place. Here, we arrive at the strangest contradiction in the history of chemical weapons: the near end of the use of chemical weapons, the Geneva Protocol, came before the peak of their development and manufacturing. Despite the limited chemical attacks during WWII, chemical weapons programs became larger than ever before. One reason was the Geneva Protocol's differentiation between combat use by state actors and other uses. To say that the Nazis made little use of chemical weapons, while correct in a certain technical sense, becomes absurd in the face of the Holocaust. Domestic use of chemical weapons only escalated, a dichotomy that still resonates today. This potential for domestic use or use against non-state adversaries (such as putting down revolutionary movements) justified a decision by most WWI combatants to continue development and manufacturing of chemical weapons. That created an ongoing possibility of their use, despite prohibition, which itself justified even more development. Consider the case of Australia, a nation that did not have a domestic chemical weapons program but still built massive stockpiles of imported chemical munitions during WWII. Why? For defense, of course: Australia was relatively close to Japan, the main chemical combatant, and felt the need to have a credible retaliation capability if Japan did decide to initiate all-out chemical war. This kind of reasoning, foreshadowing the doctrine that would demand nuclear weapons programs to the modern day, echoed around the world. Australia was importing those weapons principally from the US and UK, two countries that committed not to use chemical weapons, indeed never used them, and nevertheless operated major research centers and manufacturing plants throughout the war. The Germans clearly had a chemical inventory, which they so saliently demonstrated against their own population, and what if they decided to cast the treaty aside? Ought we to remain defenseless? The fear was not unfounded; Germany was known to have violated the Geneva Protocol on several occasions and some historians take the view that their use of chemical weapons was limited by technical issues rather than a policy decision. Churchill favored a chemical "first strike," although the suggestion didn't get much traction. In the US, as well, a notional retaliation capability was grounds for extensive R&D on rocket-delivered chemical warheads. Ironically, most of the US casualties to chemical weapons were self-inflicted. During the war the military manufactured stockpiles of Mustard Gas, Hydrogen Cyanide, and Cyanogen Chloride. These compounds were packaged into weapons and, in at least some cases, staged at the front in preparation for use. This program was a closely held secret and little is known of it even today. One major detail could not escape discovery: a German air raid on US Navy ships in Italy, in 1943, struck a ship carrying Mustard Gas. The resulting leakage at least contributed to the deaths of 69 people, and sickened hundreds. Already, perhaps the most dangerous thing about chemical weapons was possessing them. Chemical warfare programs only accelerated after WWII. The newly developed German nerve agents, including Sarin1, made it to the US as spoils of war. The research programs that formed around these new agents are some of the most infamous of the period, including exposure of thousands of soldiers to small doses of poisons to observe the effects, a program that continued at Edgewood Arsenal in Maryland until the public became aware—and the program collapsed in scandal—in 1975. The involvement of LSD in these experiments often sees them lumped together with MKULTRA, but the vast majority of the research was on less exotic substances: VX, Sarin, Mustard Gas, Tear Gas. Edgewood was also the manufacturing center for Mustard and Phosgene. What Edgewood couldn't provide was storage; it didn't have room for the well-separated bunkers required for munitions. The Army built new installations for the stockpile: Redstone Arsenal in Alabama, Rocky Mountain Arsenal in Colorado, Pine Bluff Arsenal in Arkansas, and Tooele Ordnance Depot in Utah. At each of these sites, hundreds of acres of earth-covered concrete sheds stored weapons at a distance that wouldn't set off their neighbors. In the very early years of the Cold War, the US Army weaponized a new chemical agent called BZ. BZ gained notoriety because of its psychological effects, which included hallucinations, and because of various accusations that it was covertly used by the US during the 1960s. These allegations don't generally hold up, but they illustrate the atmosphere of paranoia that chemical weapons created, and in response to which more chemical weapons were developed. BZ was produced at Swannanoa, North Carolina, and assembled into weapons at Pine Bluff Arsenal, where binary (two parts that are mixed together) nerve agents were produced as well. Phosphate was manufactured at Muscle Shoals, Alabama, and VX at Newport, Indiana. The Aberdeen Proving Ground handled Mustard gas manufacturing and filling. The Rocky Mountain Arsenal, though, just outside of Denver, was the center of the post-war program: Sarin, Mustard, and Sulfur Mustard were all produced and stored there. The Vietnam War proved a pivotal conflict for chemical warfare, as with so many other aspects of military history. Defoliants, such as Agent Orange, were not considered to be chemical weapons and saw heavy use in Vietnam. While targeted at plants, they were not safe for humans either, and played a major role in creating a generation of disabled veterans. In the meantime, the accidental dangers became more apparent: in 1968, an accident at Dugway Proving Ground in Utah released the nerve gas VX and killed thousands of sheep. The Army denied involvement, and then later admitted involvement but denied fault, a position it maintained into the '90s. Despite attempts to maintain secrecy, the Dugway sheep incident brought public attention to the chemical weapons program—which had maintained such a low profile that many didn't realize it existed. Press investigations after Dugway revealed further problems: disposal practices that had released large quantities of chemical agents into the ocean, handling accidents in overseas military installations, and of course numerous human experiments that fell far short of the ethical standards of the time. In short, the Dugway incident reminded the public, and Congress, that the US Army Chemical Corps existed. It had thousands of soldiers, dozens of facilities, and maintained an inventory of chemical weapons that spanned a national network of ammunition igloos. Ongoing manufacturing operations in the 1960s included BZ cluster bombs, VX shells, Hydrogen Cyanide, and others. Once the press latched on to the program, though, it was the beginning of the end. In 1969, President Nixon announced a "no first use" policy for chemical weapons and the complete prohibition of biological weapons—a stronger policy than has been adopted for nuclear weapons even to this day. As part of the 1969 declaration, Nixon also ended the biological weapons program entirely. I have not spoken as much of biological weapons here, as the scale of the US effort was always smaller than that for chemical agents, but I shouldn't understate it. A half dozen viral and bacterial infections, including Anthrax and Botulism, were weaponized in research laboratories. In part because of moral and practical concerns in the military, most of these were never manufactured at scale and delivery systems (such as artillery shells or warheads) were rarely developed to maturity. When Nixon ordered the program ended, its small scale made it relatively straightforward to destroy stockpiled material. Much of the laboratory-scale work was retained, anyway, for its value in researching defensive measures. Chemical weapons were a different matter entirely, because of the scale of the stockpiles. Continuing expansion of the chemical weapons program saw new stockpiles at Umatilla, Oregon; Pueblo, Colorado; Hawthorne, Nevada; Anniston, Alabama; and Blue Grass, Kentucky. At the peak, the United States disclosed an inventory of 31,100 metric tons of nerve agents and Mustard, stored across a dozen sites. Nearly half was concentrated in Tooele, Utah. Due to the old age of many chemical munitions, there had already been efforts to dispose of aged-out stockpiles in the 1960s. This program took the crude form of missions like "Operation CHASE," or "Cut Holes and Sink 'Em," in which Liberty ships full of munitions were towed off of the coast of Florida and scuttled. Only some carried chemical weapons, but well-founded concerns over the environmental impacts of such a chemical assault on the ocean led to legislation prohibiting this means of disposal in 1972. Other smaller-scale disposal efforts had taken forms like loading Phosphorus into barrels, rolling them into a lake, and then shooting at them until they sank, but besides the generally crude nature of this approach there were only so many lakes that could be so used. Congress had intervened in other ways, as well. Starting in 1970, the Office of the Surgeon General was tasked with reviewing the way that chemical weapons were handled and destroyed. This responsibility shifted around several agencies, ultimately involving the Centers for Disease Control, and brought a level of visibility into chemical weapons management that forced the Department of Defense to take a far more systematic and cautious approach to the remaining stockpile. During the 1970s, the Army's Chemical Corps took on a new focus: safe handling and disposal. The most concerning—and contentious—part of the stockpile was weapons that had been "forward staged" in Europe and Asia. These were intended to allow a fast retaliation to any chemical attack on Europe, but by this point they had become unpopular with host nations like Germany and Japan. This set up the first wave of chemical demilitarization: a months-long Army/Navy effort moved the chemical inventory from Okinawa, thousands of tons of munitions with nerve agents and Mustard Gas, to Johnston Atoll. While better known for its role in the nuclear weapons program, Johnston also served as a base for satellite programs (both intelligence collection and anti-satellite weapons) and a test site for biological and chemical weapons. Starting in 1971, storage and destruction of chemical weapons was made the installation's main purpose. In reaction to the safety incidents of the late '60s, legislation passed in the early 1970s that prohibited transfer of most chemical weapons from overseas to the United States. Instead, over the following decades, nearly all US chemical weapons that had been stored outside of North America were consolidated to Johnston Atoll. The inventory there in the 1990s included even German-made chemical shells that had been captured by the Allies and stored in Germany for study. In 1972, an Army command was formally established to manage the destruction of chemical weapons. The first priority was made the M34 cluster bomb. Designed in the 1950s, the M34 was the first Cold War-era chemical weapon and already considered obsolete. M34s were among the weapons destroyed by ocean disposal during Operation CHASE, but that method had since been prohibited. The Army had to find another way to handle more than 20,000 M34 bombs still stored by Denver, and because of the location of the weapons that method would have to actually neutralize the agents. For the Sarin-laden M34s, a hole was carefully drilled to drain the Sarin from each of the "bomblets" that made up the cluster munition. That Sarin liquid was then mixed with a neutralizing caustic chemical in a sealed reaction chamber. The resulting salt brine was dried, and the precipitated solids (no longer a nerve agent but still an environmental toxin) were buried in nearly 20,000 steel drums. In the meantime, Rocky Mountain Arsenal burned tens of thousands of tons of Mustard gas projectiles in an on-site incinerator, and began chemical neutralization of outdated VX munitions that had been relocated to the site for storage. These early disposal operations at Rocky Mountain Arsenal took place in part because of its proximity to a major city, and a political factor that had made it the top priority for site closure. That was also a liability: disposal operations added to existing environmental contamination, exacerbating a groundwater plume that killed nearby crops and creating a new set of toxic landfills. The weapons that were destroyed there in the '60s and '70s were the easy cases, intact weapons with chemical agents that had known neutralization techniques or were easily incinerated. The Army realized that many other chemical weapons, including older weapons that were already in poor condition and beginning to leak, would require a more complex approach with greater risk of exposure. To develop these techniques, the Chemical Corps established the Chemical Agent Munitions Disposal System (CAMDS) at the Deseret Chemical Depot, a new purpose-built installation adjacent to the Tooele Army Depot on the south side of the Great Salt Lake. CAMDS became the primary R&D site for disposal, and pioneered techniques that included robotic remote handling, semi-automated processing lines, and high-temperature incineration with extensive filtration and chemical treatment of the exhaust. Over the lifespan of CAMDS, more than 91 tons of chemical agents were treated, but most operations at CAMDS served as pilots for larger-scale facilities at other installations. In 1981, an ambitious construction program started at Johnston Atoll: the Johnston Atoll Chemical Agent Disposal System (JACADS). Based on techniques in use at CAMDS and built over five years, JACADS then went through four years of testing and validation before the first full-scale chemical weapons disposal line started operation in 1990. Nerve gas shells were carefully unloaded from storage pallets and set up on a belt. That carried them through a sort of de-production line, where the shells were opened, drained, and washed. The explosives and chemicals they contained were burned in a high-temperature incinerator, while the metal casings of the shells and other components were treated in a high-temperature kiln to ensure they were safe to handle. Simultaneously, a set of "auxiliary" incinerators and kilns processed packaging materials and handling waste. Monitoring systems continuously sampled emissions for any escaping chemical weapons, and periodically such leaks were discovered. This period of chemical weapons history is an odd one, because the political tide had turned against chemical weapons but the Army's inertia continued in the direction of chemical warfare. As JACADS was under construction, the Army built a set of new manufacturing plants at Pine Bluff Arsenal. This would specifically produce binary chemical weapons, which use two separate agents that are relatively safe until they are mixed to produce a nerve agent. Binary weapons can be much safer to handle, since the mixing doesn't occur until an in-flight "arming" stage. They were also seen as an escalation in chemical warfare, especially in the context of the Cold War. As often happens with controversial weapons systems, the Army's work to productionize binary weapons was also their undoing. Controversy around the new weapon designs, and the facilities for manufacturing them, led to a renewal in negotiations with the Soviet Union for some type of chemical weapons treaty. Domestically, the issue made its way to Washington, where in 1986 legislation passed requiring that all non-binary (and thus less safe to handle) weapons be safely destroyed. Lack of congressional enthusiasm (resulting in limited funding), the intrinsic complexity of safely handling dangerous chemicals and explosives, and standard military acquisition problems meant that the new binary weapons programs were slow in coming. Despite the start of construction on several binary weapons plants in 1982, only one was operational by the 1990s, producing the M20 and M21 cartridges which produced Sarin upon mixing in an artillery shell. Barely after M20/M21 production started, ongoing talks with the Soviet Union led to an early agreement to end chemical weapons production—a somewhat informal memorandum, but one that kickstarted negotiations for a formal treaty, complete with timelines and verification requirements. In 1991, Congress ordered the destruction of all material related to the chemical weapons program. This included binary materials, as well as waste, experimental samples, and chemical weapons waste buried in landfills. The United States had, at that point, officially ended its chemical weapons program—a position that would be reinforced by the 1997 ratification of the Chemical Weapons Convention, a complete demilitarization treaty with nearly every nation of the world, and most critically key opponent Russia, as signatories. In a certain strategic sense, the US was no longer a "chemical power," the entire stockpile considered retired. In a practical sense, there were still thousands of tons of chemical agents, packaged into hundreds of thousands of tons of munitions, stored in concrete bunkers from Alabama to Oregon. Throughout the last decade of that century, every chemical weapon storage site became a disposal operation. Congressional restrictions and political realities meant that chemical weapons could not generally be transported between sites. During the 1980s, Sarin-carrying Mk 116 "Weteye" bombs stored at Rocky Mountain Arsenal were dismantled there until safety concerns forced a decision to discontinue demilitarization operations at the edge of a major city. The remaining stockpile at Denver was small, but still included almost a thousand Weteye bombs, particularly the "difficult cases" that had begun to leak. The decision was made to ship these bombs to Tooele for safer storage and disposal at the planned CAMDS. The move did happen, but not without inspiring one of the largest political battles of the chemical weapons era, a media circus that considerably frayed relations between the Army and the state of Utah. Congress followed up by restricting domestic transportation, and by the time disarmament was fully underway it was clear that it would all need to be done "as is, where is." I put a lot of time into writing this, and I hope that you enjoy reading it. If you can spare a few dollars, consider supporting me on ko-fi. You'll receive an occasional extra, subscribers-only post, and defray the costs of providing artisanal, hand-built world wide web directly from Albuquerque, New Mexico. The US Army Chemical Demilitarization and Remediation Activity built the Tooele Chemical Agent Disposal Facility (scaled up from CAMDS), Anniston CADF, Umatilla CADF, and Newport CADF. Failures of several pilot programs to develop a practical alternative to high-temperature incineration led to the construction of the Aberdeen and Pine Bluff CADFs shortly after. Manufacturing facilities were converted, sometimes hastily, to dismantling facilities. The Chemical Weapons Convention's verification scheme started a comprehensive audit of military stockpiles, with storage sites physically searched for chemical inventory. A dream that seems so remote for nuclear weapons had been achieved: it was now military policy, and a major military objective, to find and destroy every last chemical weapon. At the turn of the millennium, JACADS completed its mission, having incinerated nearly half a million weapons—6% of the total US stockpile—stored at Johnston Atoll. Disposal facilities were operating at nearly every stockpile site, almost exclusively by incineration, although some neutralization operations continued at smaller scale. While most of the chemical inventory took the form of large quantities of finished weapons at depots, there was also a sort of "miscellaneous" category. Smaller supplies of weapons that had been moved for testing or R&D, stored agents that were never assembled into weapons, laboratory samples and waste, and other "etcetera" cases made up the category of "non-stockpile" chemical materials. For example, the military had manufactured over a hundred thousand "chemical agent identification sets," sort of portable laboratories and field guides for soldiers that might encounter chemical weapons in the field. These contained small samples of several chemical weapons, and were stored at several sites. They met their end via the Rapid Response System, a three-semi-trailer portable agent disposal facility that could perform a range of neutralization processes at small scale. After qualification testing at Tooele, the Rapid Response System made a sort of nationwide tour of each facility. A particularly hard case were those weapons that had begun to leak, or where the explosives had become unstable. These were dangerous to handle or transport, even over short distances. In response, Sandia National Laboratories developed the Explosive Destruction System. The EDS was a single semi trailer, but one that traveled with about a dozen supporting trucks. It was typically set up under a tent with a negative pressure air filtration system and an airlock for entry. Chemical munitions were set up in a tray, and shaped explosive charges placed across the top. This nightmare casserole is then loaded into a huge steel chamber, where the explosives are detonated to both "open" the weapons and thermally neutralize some of the contents. The rest of the chemical agent is destroyed by neutralizing chemicals injected into the chamber post-detonation, and the steel vessel is heated and rotated to mix everything up and complete the operation. During the '90s and '00s, multiple EDS units were used to handle small inventories of "discovered" chemical weapons, leaking and damaged weapons, and non-stockpile materials. After the Chemical Weapons Convention, the EDS convoy included a "treaty trailer" where staff from the international treaty enforcement body Organization for the Prohibition of Chemical Weapons (OPCW) independently observed the work. Major storage sites required industrial-scale facilities. At Umatilla, 1,000 concrete bunkers held artillery shells, rockets, bombs, landmines, sprayers, and storage containers. These weapons contained nerve agents Sarin and VX, as well as Mustard Gas and blister agents. 1980s upgrades to the facility included better sealing the igloos, fitting them with drains that would contain water from the bunkers for sampling, and adding air filtration on the bunker vents. These reduced the risk from leaking weapons, but as the stockpile aged, leakage was a more and more serious problem. Starting in 1998 the Army carefully recorded each leak; prior to that year most went unnoticed. Environmental personnel interviewed former employees and found multiple stories of leaks, cracks, and other incidents. In at least one case, a leaking munition described by a former worker was found, still stored, right in the bunker where he said it had sprayed its contents across the wall. Contracted to Raytheon, construction of the Umatilla Chemical Agent Disposal Facility (UMCDF) began in 1997. The plant went in to operation in 2004. With 819 miles of wire, 25,000 cubic yards of concrete, and 2,655 tons of steel, the Army boasted that it was "among the most advanced industrial facilities in the world." Destroying the full inventory at Umatilla would take years. A risk-prioritized approach was used in which large-quantity nerve agent weapons were destroyed first, and the relatively less dangerous munitions (such as those with only Mustard Gas or those with very small quantities of nerve agent) were left for later. Operated by contractor URS, the UMCDF consisted of a Container Handling Building where airtight, double-walled steel containers that had been packed and sealed in the bunkers were inspected and transferred to conveyors. From that point, they moved into the Munitions Demilitarization Building where the containers were opened, munitions were disassembled and drained, and the chemical agents and components were delivered to various incinerators. While a few workers with extensive protective equipment performed the most complex disassembly tasks, most operations within the Demilitarization Building were performed by a system of conveyors, hoists, and robots under remote control. Different components went into different incinerators. Liquid from washing weapons and containers went to the Liquid Incinerators, where it was mixed with air and natural gas and fed into a two-stage vortex burner system operating between 2,500 and 2,700 degrees Fahrenheit (1,370-1,480 C). Explosives and propellants, usually contaminated by residual chemical agents, went to the Deactivation Furnace System. A 32 foot long rotating drum kiln treated the waste at a minimum of 1,100 degrees Fahrenheit (590 C) for 7-10 minutes, followed by a discharge conveyor that kept them nearly as hot for another 15 minutes. Most of the material burned during this process, leaving ash (packaged for disposal in a chemical landfill) and flue gas that passed through a final stage of incineration in an afterburner chamber. Just about everything else, mostly the metal casings and components of weapons, went to the Metal Parts Furnace (MPF). The MPF was a three-stage incinerator, with a system of belts and airlocks to move material through it in an almost continuous stream. The three stages held materials for various time periods (depending on the type of waste) at temperatures from 1,450 F to 1,800 F (790 C to 980 C), until the materials arrive in the out-feed airlock where they are cooled. The air blown in for cooling was sampled on the way out and tested to ensure that it was free of chemical agents. All gases from the MPF were processed by a multi-stage afterburner incinerator. The UMCDF required an array of support facilities, like the Pollution Abatement System that received the exhaust gases from all of the incinerators. This exhaust, clean of chemical agents but still bearing a variety of interesting and toxic chemicals, was cooled in a quench tower and then put through a series of chemical scrubbers and filters before a final incinerator stage for good measure. Liquid brines, collected from the scrubber towers and parts of the Demilitarization Building process, went to a treatment plant where the water was evaporated off (and the vapors scrubbed) to leave dry crystallized salts. These were packaged for disposal at a hazardous waste landfill. Laboratory, utility, and office buildings made up the rest of the complex. Congressional scrutiny of chemical weapons also led to the Chemical Stockpile Emergency Preparedness Program. This legislation responded to accidents that had occurred at storage and demilitarization sites by requiring that the Army and FEMA take measures to protect nearby communities. The highest population concentration around a major depot, after the relatively early end of operations at Rocky Mountain Arsenal, was found in Oregon and Washington towns around Umatilla. In that region, FEMA funded the construction of a new emergency operations center, installation of sirens, and positive-pressure chemical filtration systems on schools. It was projected that residents of Umatilla would have to move into sealed shelter in less than an hour, were there to be an accident at the depot. A FEMA-funded computer modeling system, at the Emergency Operations Center, would project plume travel to inform evacuation and shelter decisions. The counties stockpiled protective suits and other equipment, and arranged military training on surviving chemical attack for firefighters. By 2000, residents of the area were provided with "tone alert" radios to sound an alarm in their home. Counties distributed "shelter in place kits," with tape and plastic sheeting, to offer residents something to do if the radios ever did sound. The East Oregonian described a county official saying that the kits wouldn't really seal a room, but "may buy more time for a family inside." Pressurization systems were made standard in new schools in the area, and added to the hospital and a nursing home in Umatilla. Working with the CDC, the State of Oregon trained medical personnel on chemical weapons response and distributed the nerve agent antidote Atropine to hospitals. FEMA funds were directed to school districts to buy more buses—a local transportation capability that could be conscripted for an evacuation. In 2008, the last nerve gas weapon, a VX land mine, passed through the plant. The last Mustard Gas weapon was processed in 2011, and evacuation sirens sounded their last Tuesday test. In 2013, the Army published a plan to remediate contamination at Umatilla, demolish the plant, and return the land to other use. Even this process was complex: many of the bunkers were contaminated and had to be carefully cleaned. Much of the demolition debris from the incinerator plant had to be handled as hazardous waste. Each and every bunker was swabbed for testing, soil samples were taken, buildings were knocked over and covered. At the building where workers changed into their protective equipment, septic leachate and dryer lint were collected as chemical waste. In 2023, the Army transferred the 9,511 acres that made up the installation to a coalition of local governments. Much of it will be used by the Oregon National Guard as a training site, other areas are slated to become industrial parks, and the tribal government of the Cayuse, Umatilla, and Walla Walla peoples will operate a large area as an environmental preserve—some of which will require an ongoing program of monitoring and institutional controls. The last chemical weapons in the US stockpile were located at Blue Grass Army Depot, where the Blue Grass Chemical Agent Disposal Facility processed the final Sarin-filled M55 rocket on July 7th, 2023—just ahead of the September 30th deadline set by the Chemical Weapons Convention. Measured from Congress's 1986 legislative mandate, the complete destruction of the US inventory of chemical and biological weapons took 37 years. Closure of the later disposal facilities is still ongoing, and the small-scale portable disposal systems will be retained for use on any chemical or biological weapons that might turn up in the future. An Assistant Secretary of Defense, Deborah Rosenblum, said that "this achievement demonstrates our credibility to the international community and has helped move the US government toward closing this particular chapter of US military history." There are few chapters of military history that ever close. The arc of the chemical weapons program, developed under wartime pressures but accelerated during the curious pressure of the Cold War, largely rejected by both the military and the public, and then wrapped up under international agreement at great expense... it is impossible not to compare it to that of the nuclear weapons program. Negotiations with the Soviet Union leading to a bilateral agreement, followed by an international convention, to completely disarm: the dream of generations of nuclear weapons protestors. It seems so far away, so impossible, for nuclear weapons that it's hard to remember that we've done it once before. So why can't we do it again? Well, the comparison isn't entirely fair. For one, the strategic significance of chemical weapons has never been on par with that of their nuclear peers. The story of World War I shows that chemical weapons are hard to use effectively outside of a few very specific situations, and that never really changed. They have a small area of effect, making them useful mostly to clear the way to advance, but they poison the land such that they can prevent that advance actually happening. Chemical disarmament was achieved, in good part, because the chemical weapons just weren't that important to begin with. One also wonders if the history of use is a factor: chemical weapons were widely used in the First World War, which both spread awareness of their horrific effects and made them more approachable, more understandable, as a part of combat. Nuclear weapons have seen such limited use that they remain more of a symbol than a real weapon, surrounded by such a mystique that their power seems both unlimited and unlikely to actually matter. During the 1899 Hague Convention, which banned the use of "shells containing asphyxiating gas," there was a sole vote against. That vote came from the United States, through its representative, Captain Alfred Mahan of the Navy. He explained his vote thus: The inventiveness of Americans should not be restricted in the development of new weapons. We do consider ourselves to be a powerful culture. The development and manufacturing of chemical weapons was a massive program, involving tens of thousands of workers across the military and private industry. The dismantling of those same weapons happened on the same scale, and often faced even more formidable technical challenges. Perhaps our inventiveness could be less restricted in the destruction of weapons, as well. German researchers gave nerve agents names such as Sarin and Tabun, while the US and NATO used two-letter codes like GB and GA. In fact, these are the same: Sarin is GB and Tabun is GA. I find the acronyms difficult to remember, and the German names are generally the ones used in popular media, so I use the German names when applicable. The problem is that nerve agents developed within NATO countries, such as VX, have no such names. The result will unfortunately be a mix of both conventions.↩
Between Microsoft's two-day outage and the FAA ground stop yesterday, there's plenty of ink spilled about who's responsible, why these things happened, etc. But it made me think back to some of the infrastructure and ops teams I've worked on, and similar (though much smaller scale) outages we encountered. Having an ops mindset is fundamentally different from a development or project management mindset. And it took me over a decade of software development to understand why.
I’ve been getting back into the politics fandom this past month.
A few weeks ago I was up late in my kitchen. I've always been a bad sleeper, starting from when I was 10 and would spend whole nights reading books and watching the clock slowly wind it way to when I had to get up and go to