<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en"><generator uri="https://jekyllrb.com/" version="4.4.1">Jekyll</generator><link href="https://securus.pages.dev/feed.xml" rel="self" type="application/atom+xml" /><link href="https://securus.pages.dev/" rel="alternate" type="text/html" hreflang="en" /><updated>2026-11-20T18:11:58-05:00</updated><id>https://securus.pages.dev/feed.xml</id><title type="html">Securus Journal</title><subtitle>Notes on Linux security, hardening, and home data center work.</subtitle><author><name>Securus</name></author><entry><title type="html">Reading TLS certificates with openssl</title><link href="https://securus.pages.dev/posts/reading-tls-certificates-with-openssl/" rel="alternate" type="text/html" title="Reading TLS certificates with openssl" /><published>2026-11-15T00:00:00-05:00</published><updated>2026-11-15T00:00:00-05:00</updated><id>https://securus.pages.dev/posts/reading-tls-certificates-with-openssl</id><content type="html" xml:base="https://securus.pages.dev/posts/reading-tls-certificates-with-openssl/"><![CDATA[<h2 id="why-certificates-exist"><a class="anchor" href="#why-certificates-exist">Why certificates exist</a></h2>

<p>Encryption alone says nothing about who is at the other end; a browser can set up a perfectly encrypted session with an attacker. Something has to prove that the server’s key belongs to the name in the address bar, and that something is the certificate.</p>

<p>Netscape designed SSL in 1994 so that people would type card numbers into a browser. Version 1.0 never shipped; SSL 2.0 went out with Netscape Navigator in 1995 and SSL 3.0 replaced it in 1996. The IETF then took the design over and renamed it: TLS 1.0 is RFC 2246, published in January 1999. TLS 1.1 and 1.2 followed in 2006 and 2008. TLS 1.3, RFC 8446 from August 2018, removed RSA key exchange and the weak ciphers and cut the handshake to one round trip. RFC 8996 formally retired TLS 1.0 and 1.1 in 2021.</p>

<p>The certificate format is older. X.509 was published by the CCITT (now the ITU-T) in 1988 for the X.500 directory, and TLS borrowed it. Version 3, from 1996, added the extensions where the useful parts now live. The internet’s profile of X.509 is RFC 5280.</p>

<p>Certificates are also getting shorter. In April 2025 the CA/Browser Forum passed ballot SC-081v3: the maximum lifetime of a public TLS certificate fell from 398 days to 200 days on 15 March 2026, drops to 100 days in March 2027 and to 47 days in March 2029. Renewal has to be automated, and the automation has to be checked.</p>

<h2 id="what-a-certificate-and-a-chain-are"><a class="anchor" href="#what-a-certificate-and-a-chain-are">What a certificate and a chain are</a></h2>

<p>A certificate is a signed statement: “this public key belongs to these names, from this date until that date”, signed by an issuer. The subject says who it is for; on a web server certificate that is usually only a common name (<code class="language-plaintext highlighter-rouge">CN</code>), which browsers ignore. The names clients actually check are in the Subject Alternative Name (SAN) extension, a list of DNS names. The issuer is whoever signed it. The validity period is two timestamps in UTC, <code class="language-plaintext highlighter-rouge">notBefore</code> and <code class="language-plaintext highlighter-rouge">notAfter</code>. Then come the public key and extensions such as <code class="language-plaintext highlighter-rouge">CA:TRUE</code>, which lets a certificate sign others.</p>

<p>A browser does not know the issuer of a server certificate directly. It knows a few hundred root certificates shipped with the operating system or browser. Roots sign intermediates, intermediates sign server certificates, and the server sends its own certificate plus the intermediates. The client builds a path from there up to a root it already trusts, checking each signature and date on the way. That path is the chain. The root itself is not sent: a root the client does not already have is worthless.</p>

<h2 id="fetching-a-servers-chain"><a class="anchor" href="#fetching-a-servers-chain">Fetching a server’s chain</a></h2>

<p><code class="language-plaintext highlighter-rouge">s_client</code> is a bare TLS client. This prints every certificate the server sent:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>openssl s_client <span class="nt">-connect</span> example.com:443 <span class="nt">-servername</span> example.com <span class="nt">-showcerts</span> &lt;/dev/null
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">-servername</code> sets SNI, the name the client asks for during the handshake. One IP address often serves hundreds of sites, and SNI is how the server picks which certificate to send. <code class="language-plaintext highlighter-rouge">&lt;/dev/null</code> is there because after the handshake <code class="language-plaintext highlighter-rouge">s_client</code> waits for input to send to the server, and without it the command sits there until you press Ctrl-D.</p>

<p>Trimmed output from OpenSSL 3.5 (the PEM blocks are cut):</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>...
Certificate chain
 0 s:CN=example.com
   i:C=US, O=SSL Corporation, CN=Cloudflare TLS Issuing ECC CA 3
   a:PKEY: EC, (prime256v1); sigalg: ecdsa-with-SHA256
   v:NotBefore: Sep 26 22:49:11 2026 GMT; NotAfter: Dec 25 22:56:35 2026 GMT
-----BEGIN CERTIFICATE-----
...
 1 s:C=US, O=SSL Corporation, CN=Cloudflare TLS Issuing ECC CA 3
   i:C=US, O=SSL Corporation, CN=SSL.com TLS Transit ECC CA R2
...
---
...
Protocol: TLSv1.3
...
Verify return code: 0 (ok)
</code></pre></div></div>

<p>Read the <code class="language-plaintext highlighter-rouge">s:</code> (subject) and <code class="language-plaintext highlighter-rouge">i:</code> (issuer) lines as pairs: each certificate’s issuer should be the subject of the next one down. Certificate 0 is the server’s own. <code class="language-plaintext highlighter-rouge">Verify return code: 0 (ok)</code> means openssl reached a trusted root, not that the name matched.</p>

<p>To save the server certificate, pipe it through <code class="language-plaintext highlighter-rouge">x509</code>, which keeps the first PEM block:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>openssl s_client <span class="nt">-connect</span> example.com:443 <span class="nt">-servername</span> example.com &lt;/dev/null 2&gt;/dev/null <span class="se">\</span>
  | openssl x509 <span class="o">&gt;</span> example.pem
</code></pre></div></div>

<h2 id="reading-a-certificate"><a class="anchor" href="#reading-a-certificate">Reading a certificate</a></h2>

<p><code class="language-plaintext highlighter-rouge">openssl x509 -in example.pem -noout -text</code> prints every field, decoded. Usually one or two fields are enough, and <code class="language-plaintext highlighter-rouge">x509</code> has a flag for each:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>openssl x509 <span class="nt">-in</span> example.pem <span class="nt">-noout</span> <span class="nt">-subject</span> <span class="nt">-issuer</span> <span class="nt">-dates</span>
openssl x509 <span class="nt">-in</span> example.pem <span class="nt">-noout</span> <span class="nt">-ext</span> subjectAltName
openssl x509 <span class="nt">-in</span> example.pem <span class="nt">-noout</span> <span class="nt">-fingerprint</span> <span class="nt">-sha256</span>
</code></pre></div></div>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>subject=CN=example.com
issuer=C=US, O=SSL Corporation, CN=Cloudflare TLS Issuing ECC CA 3
notBefore=Sep 26 22:49:11 2026 GMT
notAfter=Dec 25 22:56:35 2026 GMT
X509v3 Subject Alternative Name:
    DNS:example.com, DNS:*.example.com
sha256 Fingerprint=85:CA:6A:B0:68:E9:BC:CE:88:B6:C4:AA:3C:47:F7:D1:72:28:13:4A:45:7F:87:0D:38:00:E6:22:3A:0D:F0:7A
</code></pre></div></div>

<p>The fingerprint is a SHA-256 hash of the whole certificate in DER form, the value to compare when you pin a certificate or check one by hand. <code class="language-plaintext highlighter-rouge">-ext</code> arrived in OpenSSL 3.0; older versions and LibreSSL need <code class="language-plaintext highlighter-rouge">-text</code> and <code class="language-plaintext highlighter-rouge">grep</code>.</p>

<h2 id="checking-expiry-in-a-script"><a class="anchor" href="#checking-expiry-in-a-script">Checking expiry in a script</a></h2>

<p><code class="language-plaintext highlighter-rouge">-checkend N</code> asks whether the certificate will still be valid N seconds from now. It exits 0 if yes and 1 if no, which is all a script needs:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>openssl x509 <span class="nt">-in</span> example.pem <span class="nt">-noout</span> <span class="nt">-checkend</span> <span class="k">$((</span><span class="m">30</span><span class="o">*</span><span class="m">86400</span><span class="k">))</span>   <span class="c"># 30 days</span>
</code></pre></div></div>

<p>On 15 November that certificate has 40 days left, so 30 days passes and 45 days fails. OpenSSL also prints <code class="language-plaintext highlighter-rouge">Certificate will not expire</code> or <code class="language-plaintext highlighter-rouge">Certificate will expire</code>; LibreSSL prints nothing. Test the exit status, never the text.</p>

<p>The script below takes a number of days and a list of hosts, and reports each:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c">#!/usr/bin/env bash</span>
<span class="c"># certwatch.sh: warn when TLS certificates expire within N days.</span>
<span class="c"># Usage: certwatch.sh DAYS host[:port] ...</span>
<span class="c"># Exit status: 0 all fine, 1 at least one expiring, 2 at least one unreachable.</span>
<span class="nb">set</span> <span class="nt">-u</span>
<span class="nv">OPENSSL</span><span class="o">=</span><span class="k">${</span><span class="nv">OPENSSL</span><span class="k">:-</span><span class="nv">openssl</span><span class="k">}</span>

<span class="k">if</span> <span class="o">[</span> <span class="nv">$# </span><span class="nt">-lt</span> 2 <span class="o">]</span><span class="p">;</span> <span class="k">then
  </span><span class="nb">echo</span> <span class="s2">"usage: </span><span class="nv">$0</span><span class="s2"> DAYS host[:port] ..."</span> <span class="o">&gt;</span>&amp;2
  <span class="nb">exit </span>64
<span class="k">fi
</span><span class="nv">days</span><span class="o">=</span><span class="nv">$1</span>
<span class="nb">shift
</span><span class="nv">status</span><span class="o">=</span>0

fetch<span class="o">()</span> <span class="o">{</span>
  <span class="s2">"</span><span class="nv">$OPENSSL</span><span class="s2">"</span> s_client <span class="nt">-connect</span> <span class="s2">"</span><span class="nv">$1</span><span class="s2">:</span><span class="nv">$2</span><span class="s2">"</span> <span class="nt">-servername</span> <span class="s2">"</span><span class="nv">$1</span><span class="s2">"</span> &lt;/dev/null 2&gt;/dev/null <span class="se">\</span>
    | <span class="s2">"</span><span class="nv">$OPENSSL</span><span class="s2">"</span> x509 2&gt;/dev/null
<span class="o">}</span>

<span class="k">for </span>target <span class="k">in</span> <span class="s2">"</span><span class="nv">$@</span><span class="s2">"</span><span class="p">;</span> <span class="k">do
  </span><span class="nv">host</span><span class="o">=</span><span class="k">${</span><span class="nv">target</span><span class="p">%%</span>:<span class="p">*</span><span class="k">}</span>
  <span class="nv">port</span><span class="o">=</span><span class="k">${</span><span class="nv">target</span><span class="p">#*</span>:<span class="k">}</span>
  <span class="o">[</span> <span class="s2">"</span><span class="nv">$port</span><span class="s2">"</span> <span class="o">=</span> <span class="s2">"</span><span class="nv">$target</span><span class="s2">"</span> <span class="o">]</span> <span class="o">&amp;&amp;</span> <span class="nv">port</span><span class="o">=</span>443

  <span class="nv">cert</span><span class="o">=</span><span class="si">$(</span>fetch <span class="s2">"</span><span class="nv">$host</span><span class="s2">"</span> <span class="s2">"</span><span class="nv">$port</span><span class="s2">"</span><span class="si">)</span>
  <span class="o">[</span> <span class="nt">-z</span> <span class="s2">"</span><span class="nv">$cert</span><span class="s2">"</span> <span class="o">]</span> <span class="o">&amp;&amp;</span> <span class="nv">cert</span><span class="o">=</span><span class="si">$(</span>fetch <span class="s2">"</span><span class="nv">$host</span><span class="s2">"</span> <span class="s2">"</span><span class="nv">$port</span><span class="s2">"</span><span class="si">)</span>   <span class="c"># one retry for a dropped handshake</span>
  <span class="k">if</span> <span class="o">[</span> <span class="nt">-z</span> <span class="s2">"</span><span class="nv">$cert</span><span class="s2">"</span> <span class="o">]</span><span class="p">;</span> <span class="k">then
    </span><span class="nb">echo</span> <span class="s2">"ERROR  </span><span class="nv">$target</span><span class="s2">: no certificate received"</span>
    <span class="nv">status</span><span class="o">=</span>2
    <span class="k">continue
  fi

  </span><span class="nv">end</span><span class="o">=</span><span class="si">$(</span><span class="nb">printf</span> <span class="s1">'%s\n'</span> <span class="s2">"</span><span class="nv">$cert</span><span class="s2">"</span> | <span class="s2">"</span><span class="nv">$OPENSSL</span><span class="s2">"</span> x509 <span class="nt">-noout</span> <span class="nt">-enddate</span> | <span class="nb">cut</span> <span class="nt">-d</span><span class="o">=</span> <span class="nt">-f2</span><span class="si">)</span>
  <span class="k">if </span><span class="nb">printf</span> <span class="s1">'%s\n'</span> <span class="s2">"</span><span class="nv">$cert</span><span class="s2">"</span> | <span class="s2">"</span><span class="nv">$OPENSSL</span><span class="s2">"</span> x509 <span class="nt">-noout</span> <span class="nt">-checkend</span> <span class="k">$((</span>days <span class="o">*</span> <span class="m">86400</span><span class="k">))</span> <span class="o">&gt;</span>/dev/null<span class="p">;</span> <span class="k">then
    </span><span class="nb">echo</span> <span class="s2">"OK     </span><span class="nv">$target</span><span class="s2">: expires </span><span class="nv">$end</span><span class="s2">"</span>
  <span class="k">else
    </span><span class="nb">echo</span> <span class="s2">"WARN   </span><span class="nv">$target</span><span class="s2">: expires </span><span class="nv">$end</span><span class="s2">"</span>
    <span class="o">[</span> <span class="s2">"</span><span class="nv">$status</span><span class="s2">"</span> <span class="nt">-eq</span> 0 <span class="o">]</span> <span class="o">&amp;&amp;</span> <span class="nv">status</span><span class="o">=</span>1
  <span class="k">fi
done

</span><span class="nb">exit</span> <span class="s2">"</span><span class="nv">$status</span><span class="s2">"</span>
</code></pre></div></div>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ ./certwatch.sh 30 example.com expired.badssl.com badssl.com wikipedia.org:443 no-such-host.example
OK     example.com: expires Dec 25 22:56:35 2026 GMT
WARN   expired.badssl.com: expires Apr 12 23:59:59 2015 GMT
OK     badssl.com: expires Dec 28 20:02:55 2026 GMT
OK     wikipedia.org:443: expires Jan  2 18:34:50 2027 GMT
ERROR  no-such-host.example: no certificate received
$ echo $?
2
</code></pre></div></div>

<p>A host that sends no certificate is an error, so a dead server does not pass silently. The script always sends SNI and runs unchanged on LibreSSL, OpenSSL 3.5 and OpenSSL 4.1. It does not parse IPv6 literals, and an unreachable host waits out the system’s connect timeout. Run it from cron with a threshold longer than your renewal interval.</p>

<h2 id="verifying-a-chain"><a class="anchor" href="#verifying-a-chain">Verifying a chain</a></h2>

<p><code class="language-plaintext highlighter-rouge">openssl verify</code> checks a certificate against the system trust store. Given the server certificate alone, it fails, because the intermediates are missing:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ openssl verify example.pem
CN=example.com
error 20 at 0 depth lookup: unable to get local issuer certificate
error example.pem: verification failed
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">-untrusted</code> supplies them: they help build the path, but the path still has to end at a root in the trust store. Save everything after the first certificate from <code class="language-plaintext highlighter-rouge">-showcerts</code> into <code class="language-plaintext highlighter-rouge">chain.pem</code>, then:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ openssl verify -untrusted chain.pem example.pem
example.pem: OK
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">-CAfile</code> replaces the trust store with a file of your own, which is how you check against a private CA.</p>

<h2 id="does-the-key-match-the-certificate"><a class="anchor" href="#does-the-key-match-the-certificate">Does the key match the certificate</a></h2>

<p>A certificate and a private key belong together only if they share a public key, and a server that refuses a newly installed certificate usually has the wrong key. Extract the public key from each and compare hashes:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>openssl x509 <span class="nt">-in</span> site.crt <span class="nt">-noout</span> <span class="nt">-pubkey</span> | openssl sha256
openssl pkey <span class="nt">-in</span> site.key <span class="nt">-pubout</span> | openssl sha256
</code></pre></div></div>

<p>Identical hashes mean a pair. The common advice to compare <code class="language-plaintext highlighter-rouge">-modulus</code> works only for RSA keys; the <code class="language-plaintext highlighter-rouge">-pubkey</code> form works for EC and Ed25519 as well.</p>

<h2 id="a-practice-ca-of-your-own"><a class="anchor" href="#a-practice-ca-of-your-own">A practice CA of your own</a></h2>

<p>Everything above can be tried without touching a real server. A throwaway self-signed certificate, valid for 30 days, with a SAN:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>openssl req <span class="nt">-x509</span> <span class="nt">-newkey</span> ec <span class="nt">-pkeyopt</span> ec_paramgen_curve:P-256 <span class="nt">-nodes</span> <span class="se">\</span>
  <span class="nt">-keyout</span> test.key <span class="nt">-out</span> test.crt <span class="nt">-days</span> 30 <span class="se">\</span>
  <span class="nt">-subj</span> <span class="s2">"/CN=test.local"</span> <span class="nt">-addext</span> <span class="s2">"subjectAltName=DNS:test.local,DNS:localhost"</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">-nodes</code> leaves the key unencrypted: fine for practice, wrong for anything else.</p>

<p>A self-signed certificate has no chain. For a chain, make a tiny CA and sign a server certificate with it:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># the root</span>
openssl req <span class="nt">-x509</span> <span class="nt">-newkey</span> rsa:2048 <span class="nt">-nodes</span> <span class="nt">-keyout</span> ca.key <span class="nt">-out</span> ca.crt <span class="nt">-days</span> 365 <span class="se">\</span>
  <span class="nt">-subj</span> <span class="s2">"/CN=Practice Root CA"</span> <span class="se">\</span>
  <span class="nt">-addext</span> <span class="s2">"basicConstraints=critical,CA:TRUE"</span> <span class="nt">-addext</span> <span class="s2">"keyUsage=critical,keyCertSign,cRLSign"</span>

<span class="c"># a key and signing request for the server</span>
openssl req <span class="nt">-newkey</span> rsa:2048 <span class="nt">-nodes</span> <span class="nt">-keyout</span> site.key <span class="nt">-out</span> site.csr <span class="nt">-subj</span> <span class="s2">"/CN=site.test"</span>

<span class="c"># the root signs it</span>
<span class="nb">printf</span> <span class="s1">'subjectAltName=DNS:site.test\nbasicConstraints=CA:FALSE\nextendedKeyUsage=serverAuth\n'</span> <span class="o">&gt;</span> site.ext
openssl x509 <span class="nt">-req</span> <span class="nt">-in</span> site.csr <span class="nt">-CA</span> ca.crt <span class="nt">-CAkey</span> ca.key <span class="nt">-CAcreateserial</span> <span class="se">\</span>
  <span class="nt">-out</span> site.crt <span class="nt">-days</span> 30 <span class="nt">-extfile</span> site.ext

openssl verify <span class="nt">-CAfile</span> ca.crt site.crt
</code></pre></div></div>

<p>The last line prints <code class="language-plaintext highlighter-rouge">site.crt: OK</code>. Without <code class="language-plaintext highlighter-rouge">-CAfile</code> it fails with error 20. <code class="language-plaintext highlighter-rouge">-extfile</code> is needed because <code class="language-plaintext highlighter-rouge">x509 -req</code> drops the extensions in a request unless told otherwise, and a server certificate without a SAN is rejected by every current browser.</p>

<h2 id="which-tls-versions-a-server-accepts"><a class="anchor" href="#which-tls-versions-a-server-accepts">Which TLS versions a server accepts</a></h2>

<p><code class="language-plaintext highlighter-rouge">s_client</code> takes one flag per version, <code class="language-plaintext highlighter-rouge">-tls1</code>, <code class="language-plaintext highlighter-rouge">-tls1_1</code>, <code class="language-plaintext highlighter-rouge">-tls1_2</code> and <code class="language-plaintext highlighter-rouge">-tls1_3</code>, and offers only that version. Look at the <code class="language-plaintext highlighter-rouge">New,</code> line:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ openssl s_client -connect example.com:443 -servername example.com -tls1_2 &lt;/dev/null 2&gt;&amp;1 | grep '^New,'
New, TLSv1.2, Cipher is ECDHE-ECDSA-CHACHA20-POLY1305
$ openssl s_client -connect tls-v1-2.badssl.com:1012 -servername tls-v1-2.badssl.com -tls1_3 &lt;/dev/null 2&gt;&amp;1 | grep -E '^New,|alert'
...ssl/tls alert handshake failure...SSL alert number 40
New, (NONE), Cipher is (NONE)
</code></pre></div></div>

<p>A cipher name means the version was accepted; <code class="language-plaintext highlighter-rouge">(NONE)</code> and an alert mean it was refused. Ignore the <code class="language-plaintext highlighter-rouge">Protocol:</code> line: OpenSSL 3.5 printed <code class="language-plaintext highlighter-rouge">Protocol: TLSv1.3</code> for handshakes that never happened.</p>

<p>On OpenSSL 3 and later, <code class="language-plaintext highlighter-rouge">-tls1</code> alone fails before anything is sent, with <code class="language-plaintext highlighter-rouge">no protocols available</code>, because the default security level forbids TLS 1.0 and 1.1. Lower it for the test:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ openssl s_client -connect example.com:443 -servername example.com -tls1 -cipher 'DEFAULT@SECLEVEL=0' &lt;/dev/null 2&gt;&amp;1 | grep '^New,'
New, TLSv1.0, Cipher is ECDHE-RSA-AES128-SHA
</code></pre></div></div>

<p>So example.com still accepts TLS 1.0. LibreSSL offers it without the extra flag.</p>

<h2 id="gotchas"><a class="anchor" href="#gotchas">Gotchas</a></h2>

<p>Missing SNI returns the wrong certificate. OpenSSL 1.1.1 and later send SNI from the <code class="language-plaintext highlighter-rouge">-connect</code> host automatically. The LibreSSL 3.3.6 that macOS ships at <code class="language-plaintext highlighter-rouge">/usr/bin/openssl</code> does not, and gets whatever the server sends to nameless clients:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ /usr/bin/openssl s_client -connect badssl.com:443 &lt;/dev/null 2&gt;/dev/null | grep ^subject
subject=/C=US/ST=California/L=San Francisco/O=BadSSL Fallback. Unknown subdomain or no SNI./CN=badssl-fallback-unknown-subdomain-or-no-sni
</code></pre></div></div>

<p>Connecting by IP address does the same on any version. Always pass <code class="language-plaintext highlighter-rouge">-servername</code>.</p>

<p>LibreSSL is not OpenSSL. Besides SNI, <code class="language-plaintext highlighter-rouge">/usr/bin/openssl</code> on macOS has no <code class="language-plaintext highlighter-rouge">x509 -ext</code> and no <code class="language-plaintext highlighter-rouge">s_client -verify_hostname</code>, prints names as <code class="language-plaintext highlighter-rouge">/C=US/O=...</code>, and prints nothing for <code class="language-plaintext highlighter-rouge">-checkend</code>. Install OpenSSL with Homebrew and call it by path: plain <code class="language-plaintext highlighter-rouge">openssl</code> there is now 4.1, and <code class="language-plaintext highlighter-rouge">$(brew --prefix openssl@3)/bin/openssl</code> is 3.5. Ask for fingerprints in a command of their own. OpenSSL 4.1.0 printed a wrong SHA-256 fingerprint when <code class="language-plaintext highlighter-rouge">-ext subjectAltName</code> was in the same command; 3.5 and LibreSSL printed the right one, which <code class="language-plaintext highlighter-rouge">openssl x509 -outform DER | shasum -a 256</code> confirms.</p>

<p><code class="language-plaintext highlighter-rouge">s_client</code> does not check the name. For <code class="language-plaintext highlighter-rouge">wrong.host.badssl.com</code>, whose certificate does not cover that name, plain <code class="language-plaintext highlighter-rouge">s_client</code> says <code class="language-plaintext highlighter-rouge">0 (ok)</code>, while adding <code class="language-plaintext highlighter-rouge">-verify_hostname wrong.host.badssl.com</code> gives <code class="language-plaintext highlighter-rouge">62 (hostname mismatch)</code>.</p>

<p><code class="language-plaintext highlighter-rouge">0 (ok)</code> can come with no certificate at all. When the server drops the connection mid-handshake, OpenSSL 3.5 prints <code class="language-plaintext highlighter-rouge">no peer certificate available</code> and then <code class="language-plaintext highlighter-rouge">Verify return code: 0 (ok)</code>. The badssl.com servers did this intermittently to OpenSSL 3’s larger post-quantum ClientHello. A script that greps for <code class="language-plaintext highlighter-rouge">0 (ok)</code> reports a dead server as healthy. Check that a certificate came back, as <code class="language-plaintext highlighter-rouge">certwatch.sh</code> does.</p>

<p>Servers that leave out the intermediate break most clients. Browsers often hide this by caching intermediates or fetching them from the certificate’s Authority Information Access URL. Most other clients, curl and Python included, do neither and fail:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ openssl s_client -connect incomplete-chain.badssl.com:443 -servername incomplete-chain.badssl.com &lt;/dev/null 2&gt;&amp;1 | grep -E 'depth|Verify return'
depth=0 CN=*.badssl.com
    Verify return code: 21 (unable to verify the first certificate)
</code></pre></div></div>

<p>Only depth 0 came back. The fix is on the server: configure the full chain file, not the bare certificate.</p>

<p>Clock skew breaks validation both ways. A machine whose clock is behind sees a freshly issued certificate as <code class="language-plaintext highlighter-rouge">not yet valid</code> (error 9), and one whose clock is ahead sees a current one as expired (error 10). <code class="language-plaintext highlighter-rouge">openssl verify -attime</code> with a Unix timestamp shows what such a client sees. Check <code class="language-plaintext highlighter-rouge">date -u</code> before you blame the server.</p>

<p>Certificate transparency logs show everything a CA has issued. Since April 2018 Chrome has required every new public certificate to appear in the public logs defined by RFC 6962. crt.sh, run by Sectigo, searches them:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>curl <span class="nt">-s</span> <span class="s1">'https://crt.sh/?q=example.com&amp;output=json'</span> <span class="se">\</span>
  | jq <span class="nt">-r</span> <span class="s1">'.[] | [.not_before, .not_after, .name_value] | @tsv'</span> | <span class="nb">sort</span> <span class="nt">-r</span> | <span class="nb">head</span>
</code></pre></div></div>

<p>Each certificate usually appears twice, as precertificate and final certificate. The logs show certificates for your names that you did not ask for, and every hostname you have ever put in a SAN, so keep private hostnames off public certificates.</p>

<h2 id="sources"><a class="anchor" href="#sources">Sources</a></h2>

<ul>
  <li>Dierks, T. and C. Allen. RFC 2246, “The TLS Protocol Version 1.0.” January 1999.</li>
  <li>Rescorla, E. RFC 8446, “The Transport Layer Security (TLS) Protocol Version 1.3.” August 2018.</li>
  <li>Freier, A., P. Karlton and P. Kocher. RFC 6101, “The Secure Sockets Layer (SSL) Protocol Version 3.0.” August 2011 (historic record of the 1996 protocol).</li>
  <li>Moriarty, K. and S. Farrell. RFC 8996, “Deprecating TLS 1.0 and TLS 1.1.” March 2021.</li>
  <li>Cooper, D., S. Santesson, S. Farrell, S. Boeyen, R. Housley and W. Polk. RFC 5280, “Internet X.509 Public Key Infrastructure Certificate and Certificate Revocation List (CRL) Profile.” May 2008.</li>
  <li>Eastlake, D. RFC 6066, “Transport Layer Security (TLS) Extensions: Extension Definitions” (Server Name Indication, section 3). January 2011.</li>
  <li>Laurie, B., A. Langley and E. Kasper. RFC 6962, “Certificate Transparency.” June 2013.</li>
  <li>CA/Browser Forum. Ballot SC-081v3, “Introduce Schedule of Reducing Validity and Data Reuse Periods.” April 2025.</li>
  <li>OpenSSL Project. openssl-s_client(1), openssl-x509(1), openssl-verify(1), openssl-req(1) and openssl-s_server(1) manual pages, OpenSSL 3.5.</li>
  <li>LibreSSL. openssl(1) manual page.</li>
  <li>badssl.com test hosts and crt.sh certificate search.</li>
</ul>]]></content><author><name>Securus</name></author><category term="Portfolio" /><category term="Cryptography" /><category term="tls" /><category term="openssl" /><category term="x509" /><category term="certificates" /><category term="pki" /><category term="bash" /><category term="security" /><summary type="html"><![CDATA[What a certificate and its chain are, how to pull them off a live server and read them with openssl, a tested script that warns before certificates expire, a practice CA to experiment on, and the mistakes that make openssl give the wrong answer.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://securus.pages.dev/assets/img/social-preview.png" /><media:content medium="image" url="https://securus.pages.dev/assets/img/social-preview.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">auditd: who did what</title><link href="https://securus.pages.dev/posts/auditd-who-did-what/" rel="alternate" type="text/html" title="auditd: who did what" /><published>2026-11-04T00:00:00-05:00</published><updated>2026-11-04T00:00:00-05:00</updated><id>https://securus.pages.dev/posts/auditd-who-did-what</id><content type="html" xml:base="https://securus.pages.dev/posts/auditd-who-did-what/"><![CDATA[<h2 id="why-auditd-exists"><a class="anchor" href="#why-auditd-exists">Why auditd exists</a></h2>

<p>Most logs on a Linux machine are written by the programs themselves. sshd says who logged in, sudo says what it was asked to run, nginx says what it served. Each program decides what to write, and a program that is compromised, misconfigured or simply quiet writes nothing useful.</p>

<p>The audit framework works one level down. The kernel watches system calls as they return and, when one matches a rule, writes a record about it: which process, which file, which user, whether it succeeded. The program never gets a say. The kernel side arrived in the Linux 2.6 series in 2004, built at Red Hat so that Linux could be certified against the Common Criteria’s Controlled Access Protection Profile, which required exactly this kind of record. auditd is the userspace daemon that receives those records and writes them to <code class="language-plaintext highlighter-rouge">/var/log/audit/audit.log</code>.</p>

<p>That makes it the tool for the questions that come up after something has gone wrong. Who edited <code class="language-plaintext highlighter-rouge">/etc/sudoers</code> on Tuesday? Which commands ran as root last night, and which person was behind them? A web log cannot answer either.</p>

<p>It is worth being clear about what auditd is not. It does not block anything: a rule records an action, it never refuses one. It is not an intrusion detection system, and it records only what the rules ask for, which by default on most distributions is almost nothing. It is also not a replacement for journald. The journal collects what services print; audit collects what the kernel saw them do. Without auditd running, the kernel still emits audit records and the journal may pick some of them up, but there is no dedicated log, no rotation or disk-full policy for it, and nothing for <code class="language-plaintext highlighter-rouge">ausearch</code> to read.</p>

<h2 id="how-it-actually-works"><a class="anchor" href="#how-it-actually-works">How it actually works</a></h2>

<p>Three pieces do the work. The kernel matches events against a list of rules. auditd writes matching records to disk. <code class="language-plaintext highlighter-rouge">ausearch</code> and <code class="language-plaintext highlighter-rouge">aureport</code> read the disk back.</p>

<p>Rules come in two kinds. A file watch says “record anything that writes to this path”. A syscall rule says “record every call to this system call that matches these fields”. Both carry a key, a short label of your choosing (<code class="language-plaintext highlighter-rouge">-k sudoers</code>), and the key is what you search on later.</p>

<p>The field that makes audit worth having is <code class="language-plaintext highlighter-rouge">auid</code>, the audit or login user ID. When someone logs in, PAM’s <code class="language-plaintext highlighter-rouge">pam_loginuid</code> module writes their UID into <code class="language-plaintext highlighter-rouge">/proc/self/loginuid</code>. Every process they start inherits it, and it does not change when the identity does: <code class="language-plaintext highlighter-rouge">su</code>, <code class="language-plaintext highlighter-rouge">sudo</code> and setuid programs change the uid and euid, but the auid stays put. You can see it for yourself:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">cat</span> /proc/self/loginuid
<span class="nb">sudo cat</span> /proc/self/loginuid
</code></pre></div></div>

<p>Both print the same number. So when a command runs as root, the record says <code class="language-plaintext highlighter-rouge">uid=root</code> and also <code class="language-plaintext highlighter-rouge">auid=alice</code>, and the question “who was root at the time” has an answer. Processes started at boot by systemd never logged in, and their auid is unset, which the kernel stores as 4294967295 (the 32-bit form of -1) and the tools print as <code class="language-plaintext highlighter-rouge">unset</code>.</p>

<h2 id="installing-it"><a class="anchor" href="#installing-it">Installing it</a></h2>

<p>On Fedora, RHEL and their relatives the package is <code class="language-plaintext highlighter-rouge">audit</code>, and it is usually installed and running already:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">sudo </span>dnf <span class="nb">install </span>audit
<span class="nb">sudo </span>systemctl <span class="nb">enable</span> <span class="nt">--now</span> auditd
</code></pre></div></div>

<p>On Debian and Ubuntu the package is <code class="language-plaintext highlighter-rouge">auditd</code>, and installing it starts the service:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">sudo </span>apt <span class="nb">install </span>auditd
</code></pre></div></div>

<p>Check that it is running and the kernel side is enabled:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">sudo </span>auditctl <span class="nt">-s</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">enabled 1</code> means auditing is on. The same output shows <code class="language-plaintext highlighter-rouge">lost</code> and <code class="language-plaintext highlighter-rouge">backlog</code>, which matter later.</p>

<p>One Red Hat quirk: the auditd unit refuses <code class="language-plaintext highlighter-rouge">systemctl stop</code> and <code class="language-plaintext highlighter-rouge">systemctl restart</code> on purpose, and Red Hat’s documentation says to use <code class="language-plaintext highlighter-rouge">service auditd restart</code> instead, keeping <code class="language-plaintext highlighter-rouge">systemctl</code> for <code class="language-plaintext highlighter-rouge">enable</code> and <code class="language-plaintext highlighter-rouge">status</code>. You rarely need either. Rules load without a restart, and auditd rereads <code class="language-plaintext highlighter-rouge">auditd.conf</code> on SIGHUP.</p>

<h2 id="writing-rules"><a class="anchor" href="#writing-rules">Writing rules</a></h2>

<p>Rules live in files ending in <code class="language-plaintext highlighter-rouge">.rules</code> under <code class="language-plaintext highlighter-rouge">/etc/audit/rules.d/</code>. Files with any other ending are ignored. <code class="language-plaintext highlighter-rouge">augenrules</code> joins them in natural sort order into <code class="language-plaintext highlighter-rouge">/etc/audit/audit.rules</code>, moves the control lines (<code class="language-plaintext highlighter-rouge">-D</code>, <code class="language-plaintext highlighter-rouge">-b</code>, <code class="language-plaintext highlighter-rouge">-f</code>, <code class="language-plaintext highlighter-rouge">-e</code>) to their proper places, and with <code class="language-plaintext highlighter-rouge">--load</code> sends the result to the kernel:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">sudo </span>augenrules <span class="nt">--load</span>
<span class="nb">sudo </span>auditctl <span class="nt">-l</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">auditctl -l</code> lists what the kernel actually has. Rules can also be added straight from the command line with <code class="language-plaintext highlighter-rouge">auditctl</code>, which is handy for testing, but those vanish at reboot. The files are the configuration.</p>

<p>Leave the file the package ships (usually <code class="language-plaintext highlighter-rouge">audit.rules</code> in the same directory) alone. It clears old rules and sets the buffer size and failure mode, and your own files go next to it.</p>

<h3 id="file-watches"><a class="anchor" href="#file-watches">File watches</a></h3>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>-w /etc/sudoers -p wa -k sudoers
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">-w</code> names the path. <code class="language-plaintext highlighter-rouge">-p</code> lists the access types to record: <code class="language-plaintext highlighter-rouge">r</code> read, <code class="language-plaintext highlighter-rouge">w</code> write, <code class="language-plaintext highlighter-rouge">x</code> execute, <code class="language-plaintext highlighter-rouge">a</code> attribute change (owner, mode, timestamps). <code class="language-plaintext highlighter-rouge">wa</code> is the usual choice for configuration: changes get logged, reads do not. On a directory the watch is recursive, so <code class="language-plaintext highlighter-rouge">-w /etc/sudoers.d/ -p wa -k sudoers</code> catches any file dropped into it.</p>

<p>The auditctl man page now calls the <code class="language-plaintext highlighter-rouge">-w</code> form deprecated, kept for backwards compatibility, and gives the syscall form as the replacement: <code class="language-plaintext highlighter-rouge">-a always,exit -F arch=b64 -F path=/etc/sudoers -F perm=wa -k sudoers</code> for a file, and <code class="language-plaintext highlighter-rouge">-F dir=</code> for a directory. Both forms still load on current releases. The starter set below uses <code class="language-plaintext highlighter-rouge">-w</code> because it is easier to read; convert the lines if you are writing rules for many paths.</p>

<h3 id="syscall-rules"><a class="anchor" href="#syscall-rules">Syscall rules</a></h3>

<p>This one records every program run as root by a person who logged in:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>-a always,exit -F arch=b64 -S execve -F euid=0 -F auid&gt;=1000 -F auid!=unset -k root-cmds
-a always,exit -F arch=b32 -S execve -F euid=0 -F auid&gt;=1000 -F auid!=unset -k root-cmds
</code></pre></div></div>

<p>Read it left to right. <code class="language-plaintext highlighter-rouge">-a always,exit</code> adds the rule to the exit list and always records a match. <code class="language-plaintext highlighter-rouge">-F arch=b64</code> says which system call table to use, and it must come before <code class="language-plaintext highlighter-rouge">-S</code>. <code class="language-plaintext highlighter-rouge">-S execve</code> is the call that starts a program. <code class="language-plaintext highlighter-rouge">-F euid=0</code> keeps only calls running with root’s effective UID. <code class="language-plaintext highlighter-rouge">-F auid&gt;=1000</code> keeps only real accounts, since 1000 is the default <code class="language-plaintext highlighter-rouge">UID_MIN</code> on Debian, Ubuntu, Fedora and RHEL. <code class="language-plaintext highlighter-rouge">-F auid!=unset</code> drops daemons that never logged in; <code class="language-plaintext highlighter-rouge">unset</code>, <code class="language-plaintext highlighter-rouge">-1</code> and <code class="language-plaintext highlighter-rouge">4294967295</code> all mean the same thing here.</p>

<p>The rule appears twice because a 64-bit x86 kernel can also run 32-bit programs, and their system calls go through a separate table with different numbers. A rule for <code class="language-plaintext highlighter-rouge">b64</code> alone never sees them, and anyone who knows that can run a 32-bit binary to stay out of the log. Write both.</p>

<h2 id="a-starter-rule-set"><a class="anchor" href="#a-starter-rule-set">A starter rule set</a></h2>

<p>Two files. The first holds the rules:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>## /etc/audit/rules.d/50-who-did-what.rules

# Accounts and groups
-w /etc/passwd -p wa -k identity
-w /etc/group -p wa -k identity
-w /etc/shadow -p wa -k identity
-w /etc/gshadow -p wa -k identity

# Who may use sudo
-w /etc/sudoers -p wa -k sudoers
-w /etc/sudoers.d/ -p wa -k sudoers

# SSH server settings
-w /etc/ssh/sshd_config -p wa -k sshd
-w /etc/ssh/sshd_config.d/ -p wa -k sshd

# The audit configuration itself
-w /etc/audit/ -p wa -k audit-config

# Every program run as root by a logged-in user
-a always,exit -F arch=b64 -S execve -F euid=0 -F auid&gt;=1000 -F auid!=unset -k root-cmds
-a always,exit -F arch=b32 -S execve -F euid=0 -F auid&gt;=1000 -F auid!=unset -k root-cmds
</code></pre></div></div>

<p>The second, added only after the first has run for a while without trouble, locks the rules:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>## /etc/audit/rules.d/99-finalize.rules
-e 2
</code></pre></div></div>

<p>Load them with <code class="language-plaintext highlighter-rouge">sudo augenrules --load</code>.</p>

<h2 id="locking-the-rules"><a class="anchor" href="#locking-the-rules">Locking the rules</a></h2>

<p><code class="language-plaintext highlighter-rouge">-e</code> sets the audit state: <code class="language-plaintext highlighter-rouge">0</code> disables auditing, <code class="language-plaintext highlighter-rouge">1</code> enables it, and <code class="language-plaintext highlighter-rouge">2</code> enables it and locks the configuration. Once the kernel is in mode 2, no rule can be added, removed or changed and auditing cannot be turned off, by anyone, root included, until the machine reboots. <code class="language-plaintext highlighter-rouge">auditctl -s</code> then shows <code class="language-plaintext highlighter-rouge">enabled 2</code>.</p>

<p>That is the point. An intruder who gets root can otherwise run <code class="language-plaintext highlighter-rouge">auditctl -D</code> and erase the rules before doing anything interesting. In mode 2 the attempt fails, and the reboot needed to get around it is noticeable in itself.</p>

<p>The cost is the same for you. Every rule change needs a reboot, which is why the lock goes in last. <code class="language-plaintext highlighter-rouge">augenrules</code> always moves the <code class="language-plaintext highlighter-rouge">-e</code> line to the end of the combined file, so the name <code class="language-plaintext highlighter-rouge">99-finalize.rules</code> is a convention for people reading the directory, not a requirement.</p>

<h2 id="reading-the-results"><a class="anchor" href="#reading-the-results">Reading the results</a></h2>

<p><code class="language-plaintext highlighter-rouge">ausearch</code> finds events. Search by key, and always add <code class="language-plaintext highlighter-rouge">-i</code> to turn numbers into names:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">sudo </span>ausearch <span class="nt">-k</span> sudoers <span class="nt">-i</span>
<span class="nb">sudo </span>ausearch <span class="nt">-k</span> root-cmds <span class="nt">-i</span> <span class="nt">-ts</span> today
<span class="nb">sudo </span>ausearch <span class="nt">-ua</span> alice <span class="nt">-i</span> <span class="nt">-ts</span> yesterday <span class="nt">-te</span> today
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">-ts</code> and <code class="language-plaintext highlighter-rouge">-te</code> take a start and end time, either a date and time or a keyword: <code class="language-plaintext highlighter-rouge">now</code>, <code class="language-plaintext highlighter-rouge">recent</code> (ten minutes ago), <code class="language-plaintext highlighter-rouge">today</code>, <code class="language-plaintext highlighter-rouge">yesterday</code>, <code class="language-plaintext highlighter-rouge">this-week</code>, <code class="language-plaintext highlighter-rouge">boot</code>. <code class="language-plaintext highlighter-rouge">-ua</code> matches a user in the uid, euid or auid field. Other useful filters are <code class="language-plaintext highlighter-rouge">-f</code> for a file name, <code class="language-plaintext highlighter-rouge">-x</code> for an executable, <code class="language-plaintext highlighter-rouge">-m</code> for a record type such as <code class="language-plaintext highlighter-rouge">EXECVE</code>, and <code class="language-plaintext highlighter-rouge">--success no</code> for calls that failed.</p>

<p>One event is several records sharing a timestamp and serial number. For the <code class="language-plaintext highlighter-rouge">root-cmds</code> rule, trimmed down, it looks like this:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>----
type=PROCTITLE msg=audit(11/04/2026 14:02:17.351:2214) : proctitle=systemctl restart nginx
type=CWD msg=audit(11/04/2026 14:02:17.351:2214) : cwd=/home/alice
type=EXECVE msg=audit(11/04/2026 14:02:17.351:2214) : argc=3 a0=systemctl a1=restart a2=nginx
type=SYSCALL msg=audit(11/04/2026 14:02:17.351:2214) : arch=x86_64 syscall=execve success=yes exit=0 ... auid=alice uid=root gid=root euid=root ... tty=pts0 ses=3 comm=systemctl exe=/usr/bin/systemctl key=root-cmds
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">EXECVE</code> holds the full command line, <code class="language-plaintext highlighter-rouge">CWD</code> where it ran, and <code class="language-plaintext highlighter-rouge">SYSCALL</code> the identities. <code class="language-plaintext highlighter-rouge">auid=alice</code> with <code class="language-plaintext highlighter-rouge">uid=root</code> is the answer to “who did it”. <code class="language-plaintext highlighter-rouge">ses</code> is the login session number, so <code class="language-plaintext highlighter-rouge">ausearch --session 3 -i</code> pulls up everything else alice did in that session.</p>

<p><code class="language-plaintext highlighter-rouge">aureport</code> turns the same log into summaries:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">sudo </span>aureport <span class="nt">--summary</span>
<span class="nb">sudo </span>aureport <span class="nt">-k</span> <span class="nt">--summary</span>
<span class="nb">sudo </span>aureport <span class="nt">-x</span> <span class="nt">--summary</span> <span class="nt">-i</span>
<span class="nb">sudo </span>aureport <span class="nt">-au</span> <span class="nt">--failed</span> <span class="nt">-i</span> <span class="nt">-ts</span> this-week
</code></pre></div></div>

<p>The first gives totals for the whole log. <code class="language-plaintext highlighter-rouge">-k --summary</code> counts events per key, which is the fastest way to spot a rule that is firing far more than it should. <code class="language-plaintext highlighter-rouge">-x --summary</code> ranks executables, and <code class="language-plaintext highlighter-rouge">-au --failed</code> lists failed authentication attempts.</p>

<h2 id="log-size-and-rotation"><a class="anchor" href="#log-size-and-rotation">Log size and rotation</a></h2>

<p>auditd rotates its own log. Do not point logrotate at <code class="language-plaintext highlighter-rouge">/var/log/audit/</code>. The settings are in <code class="language-plaintext highlighter-rouge">/etc/audit/auditd.conf</code>:</p>

<div class="language-ini highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="py">max_log_file</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="s">50</span>
<span class="py">num_logs</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="s">10</span>
<span class="py">max_log_file_action</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="s">ROTATE</span>
<span class="py">space_left</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="s">500</span>
<span class="py">space_left_action</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="s">SYSLOG</span>
<span class="py">admin_space_left</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="s">100</span>
<span class="py">admin_space_left_action</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="s">SUSPEND</span>
<span class="py">disk_full_action</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="s">SUSPEND</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">max_log_file</code> is in MiB, so this keeps ten files of 50 MiB each. <code class="language-plaintext highlighter-rouge">num_logs</code> below 2 turns rotation off. <code class="language-plaintext highlighter-rouge">space_left</code> and <code class="language-plaintext highlighter-rouge">admin_space_left</code> are free-space thresholds in MiB on the log’s filesystem (recent versions also accept a percentage such as <code class="language-plaintext highlighter-rouge">25%</code>), and the <code class="language-plaintext highlighter-rouge">_action</code> lines say what happens when they are crossed. <code class="language-plaintext highlighter-rouge">SUSPEND</code> stops writing records but keeps the daemon running; <code class="language-plaintext highlighter-rouge">SINGLE</code> drops the machine to single-user mode and <code class="language-plaintext highlighter-rouge">HALT</code> shuts it down, which some compliance regimes require and most servers should not do.</p>

<p>Apply changes with:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">sudo </span>pkill <span class="nt">-HUP</span> auditd
</code></pre></div></div>

<p>Records on the machine itself are only as trustworthy as the machine. An intruder with root can stop auditd or delete the files, even when the rules are locked. For anything that matters, ship the records elsewhere as they are written, with the <code class="language-plaintext highlighter-rouge">audisp-remote</code> plugin (package <code class="language-plaintext highlighter-rouge">audispd-plugins</code> on both Fedora and Debian) or through syslog to a central collector.</p>

<h2 id="noise-and-performance"><a class="anchor" href="#noise-and-performance">Noise and performance</a></h2>

<p>Every syscall rule is checked on every matching system call, on every CPU, all the time. A few rules cost nothing you would notice. A rule on a busy call with no filters can generate thousands of records a second and slow the machine.</p>

<p>Three habits keep it in check. Always give syscall rules an <code class="language-plaintext highlighter-rouge">-F arch=</code>, because without one the kernel has to check the rule against every system call. Filter on <code class="language-plaintext highlighter-rouge">auid</code> so that daemons doing their normal work are excluded. Watch the key summary from <code class="language-plaintext highlighter-rouge">aureport -k --summary</code> after the first day, and cut or narrow any rule that dominates it.</p>

<p>Reads are the usual trap. <code class="language-plaintext highlighter-rouge">-w /etc/shadow -p r</code> records every login, every <code class="language-plaintext highlighter-rouge">sudo</code> and every cron job that checks a password. Record writes unless reads are what you are investigating.</p>

<p>When the kernel produces records faster than auditd takes them, they queue in a backlog, and when the backlog is full they are dropped. <code class="language-plaintext highlighter-rouge">auditctl -s</code> shows the count as <code class="language-plaintext highlighter-rouge">lost</code>. If it climbs, raise the buffer with a <code class="language-plaintext highlighter-rouge">-b</code> line (the shipped rules usually set <code class="language-plaintext highlighter-rouge">-b 8192</code>) or, better, cut the noise.</p>

<h2 id="troubleshooting"><a class="anchor" href="#troubleshooting">Troubleshooting</a></h2>

<p><code class="language-plaintext highlighter-rouge">auditctl -l</code> says <code class="language-plaintext highlighter-rouge">No rules</code>. The file probably does not end in <code class="language-plaintext highlighter-rouge">.rules</code>, or <code class="language-plaintext highlighter-rouge">augenrules --load</code> was never run. <code class="language-plaintext highlighter-rouge">sudo augenrules --check</code> reports whether the combined file is out of date.</p>

<p><code class="language-plaintext highlighter-rouge">augenrules --load</code> fails with an error about the audit system being in immutable mode. The kernel is in mode 2, and <code class="language-plaintext highlighter-rouge">auditctl -s</code> will show <code class="language-plaintext highlighter-rouge">enabled 2</code>. Edit the files and reboot.</p>

<p>A rule loads but the expected events never appear. Check the filters before the rule. Commands run from cron or a systemd unit have an unset auid, so <code class="language-plaintext highlighter-rouge">-F auid!=unset</code> excludes them by design. A user whose UID is below 1000 is excluded by <code class="language-plaintext highlighter-rouge">auid&gt;=1000</code>. A command that never ran as root does not match <code class="language-plaintext highlighter-rouge">euid=0</code>.</p>

<p><code class="language-plaintext highlighter-rouge">auditctl</code> rejects the <code class="language-plaintext highlighter-rouge">b32</code> line. Some 64-bit kernels, often on ARM, are built without 32-bit compatibility, so there are no 32-bit calls to catch and the line can go.</p>

<p>auditd will not start inside a container. The kernel accepts audit control only from the host’s initial namespaces. Run auditd on the host, where it sees the container’s processes anyway.</p>

<p><code class="language-plaintext highlighter-rouge">ausearch</code> prints <code class="language-plaintext highlighter-rouge">&lt;no matches&gt;</code> for a key you know has fired. Check the spelling of the key, and check the time window: without <code class="language-plaintext highlighter-rouge">-ts</code>, ausearch reads every log file it has, but rotated files beyond <code class="language-plaintext highlighter-rouge">num_logs</code> are gone.</p>

<h2 id="where-it-fits"><a class="anchor" href="#where-it-fits">Where it fits</a></h2>

<p>The earlier posts in this series are about keeping people out and limiting what a service can do: the <a href="/posts/iptables-firewall-rules/">firewall</a>, <a href="/posts/hardening-ssh/">SSH hardening</a>, <a href="/posts/fail2ban-ssh-lockouts/">fail2ban</a> and <a href="/posts/systemd-service-hardening/">systemd sandboxing</a>. auditd stops none of it. What it does is leave a record, written by the kernel rather than by the program being watched, of who changed the files that grant power and what they ran once they had it. The starter set above is a dozen lines. Load it, leave it unlocked for a week while you read <code class="language-plaintext highlighter-rouge">aureport -k --summary</code>, then add the <code class="language-plaintext highlighter-rouge">-e 2</code> file and reboot.</p>

<h2 id="sources"><a class="anchor" href="#sources">Sources</a></h2>

<ul>
  <li>Linux Audit project. auditd(8), auditctl(8), audit.rules(7), augenrules(8), ausearch(8), aureport(8) and auditd.conf(5) manual pages.</li>
  <li>Linux-PAM. pam_loginuid(8) manual page.</li>
  <li>Red Hat. “Auditing the system.” <em>Security hardening</em>, Red Hat Enterprise Linux 9 documentation.</li>
  <li>Debian. <code class="language-plaintext highlighter-rouge">auditd</code> and <code class="language-plaintext highlighter-rouge">audispd-plugins</code> package descriptions, packages.debian.org.</li>
</ul>]]></content><author><name>Securus</name></author><category term="Portfolio" /><category term="Linux" /><category term="auditd" /><category term="audit" /><category term="logging" /><category term="linux" /><category term="forensics" /><category term="sudo" /><category term="security" /><summary type="html"><![CDATA[How the Linux audit framework records file changes and privileged commands, a starter rule set to copy, how to read the results with ausearch and aureport, and what to watch for with log size, noise and locked rules.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://securus.pages.dev/assets/img/social-preview.png" /><media:content medium="image" url="https://securus.pages.dev/assets/img/social-preview.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">TOTP: the six digits behind two-factor login</title><link href="https://securus.pages.dev/posts/totp-two-factor-codes/" rel="alternate" type="text/html" title="TOTP: the six digits behind two-factor login" /><published>2026-10-28T00:00:00-04:00</published><updated>2026-10-28T00:00:00-04:00</updated><id>https://securus.pages.dev/posts/totp-two-factor-codes</id><content type="html" xml:base="https://securus.pages.dev/posts/totp-two-factor-codes/"><![CDATA[<h2 id="why-the-codes-exist"><a class="anchor" href="#why-the-codes-exist">Why the codes exist</a></h2>

<p>A password is a secret that never changes, which is the trouble with it. Once someone has read it over a shoulder, pulled it from a breach dump or typed it into a fake login page for its owner, it works for them exactly as it works for the owner, for as long as nobody changes it.</p>

<p>A one-time password changes every time. In December 2005 members of the Initiative for Open Authentication (OATH), a group of token and security vendors, wrote RFC 4226, which defined HOTP: a code computed from a shared secret and a counter that goes up by one with each login. In May 2011 RFC 6238 replaced the counter with the clock. That is TOTP, and it is what Google Authenticator, Aegis, Ente Auth, 1Password, Bitwarden and nearly every other authenticator app computes when it shows six digits and a shrinking ring.</p>

<p>Nothing in the scheme is secret except the key. The algorithm is public, the time is public, and the app never talks to the server. The server and the app hold the same key, read the same clock, and arrive at the same six digits independently.</p>

<h2 id="how-it-actually-works"><a class="anchor" href="#how-it-actually-works">How it actually works</a></h2>

<p>There are four steps, and the first two are the whole difference between TOTP and HOTP.</p>

<p>First, take the current Unix time and divide by 30, discarding the remainder. Everyone in the world agrees on that number for the same 30 seconds. RFC 6238 calls it T, and “RECOMMEND[s] a default time-step size of 30 seconds.”</p>

<p>Second, feed T to HOTP as its counter. HOTP computes HMAC-SHA-1 of the counter, written as eight bytes, using the shared key. The result is 20 bytes.</p>

<p>Third, cut it down. RFC 4226 calls this dynamic truncation: the low four bits of the last byte give an offset between 0 and 15, and the four bytes starting at that offset become a 31-bit number (the top bit is masked off so the number is never negative, whatever the language).</p>

<p>Fourth, keep the last six decimal digits of that number, padding with leading zeros.</p>

<p>The key is usually handed over as a QR code. Inside it is a URI in the format Google documented for its Authenticator app, with the key in Base32 (RFC 4648) so it survives being typed by hand:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>otpauth://totp/Example:alice@example.com?secret=JBSWY3DPEHPK3PXP&amp;issuer=Example
</code></pre></div></div>

<p>Scanning it is the enrolment. From then on the phone needs no network at all.</p>

<h2 id="a-working-implementation"><a class="anchor" href="#a-working-implementation">A working implementation</a></h2>

<p>The standard library has everything needed. This is the complete algorithm:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="n">base64</span><span class="p">,</span> <span class="n">hashlib</span><span class="p">,</span> <span class="n">hmac</span><span class="p">,</span> <span class="n">struct</span><span class="p">,</span> <span class="n">time</span>

<span class="k">def</span> <span class="nf">hotp</span><span class="p">(</span><span class="n">key</span><span class="p">:</span> <span class="nb">bytes</span><span class="p">,</span> <span class="n">counter</span><span class="p">:</span> <span class="nb">int</span><span class="p">,</span> <span class="n">digits</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">6</span><span class="p">,</span> <span class="n">digest</span><span class="o">=</span><span class="n">hashlib</span><span class="p">.</span><span class="n">sha1</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="nb">str</span><span class="p">:</span>
    <span class="n">mac</span> <span class="o">=</span> <span class="n">hmac</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="n">key</span><span class="p">,</span> <span class="n">struct</span><span class="p">.</span><span class="nf">pack</span><span class="p">(</span><span class="sh">"</span><span class="s">&gt;Q</span><span class="sh">"</span><span class="p">,</span> <span class="n">counter</span><span class="p">),</span> <span class="n">digest</span><span class="p">).</span><span class="nf">digest</span><span class="p">()</span>
    <span class="n">offset</span> <span class="o">=</span> <span class="n">mac</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span> <span class="o">&amp;</span> <span class="mh">0x0F</span>
    <span class="n">code</span> <span class="o">=</span> <span class="n">struct</span><span class="p">.</span><span class="nf">unpack</span><span class="p">(</span><span class="sh">"</span><span class="s">&gt;I</span><span class="sh">"</span><span class="p">,</span> <span class="n">mac</span><span class="p">[</span><span class="n">offset</span><span class="p">:</span><span class="n">offset</span> <span class="o">+</span> <span class="mi">4</span><span class="p">])[</span><span class="mi">0</span><span class="p">]</span> <span class="o">&amp;</span> <span class="mh">0x7FFFFFFF</span>
    <span class="k">return</span> <span class="nf">str</span><span class="p">(</span><span class="n">code</span> <span class="o">%</span> <span class="mi">10</span> <span class="o">**</span> <span class="n">digits</span><span class="p">).</span><span class="nf">zfill</span><span class="p">(</span><span class="n">digits</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">totp</span><span class="p">(</span><span class="n">key</span><span class="p">:</span> <span class="nb">bytes</span><span class="p">,</span> <span class="n">now</span><span class="p">:</span> <span class="nb">float</span> <span class="o">|</span> <span class="bp">None</span> <span class="o">=</span> <span class="bp">None</span><span class="p">,</span> <span class="n">step</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">30</span><span class="p">,</span> <span class="n">digits</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">6</span><span class="p">,</span> <span class="n">digest</span><span class="o">=</span><span class="n">hashlib</span><span class="p">.</span><span class="n">sha1</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="nb">str</span><span class="p">:</span>
    <span class="n">t</span> <span class="o">=</span> <span class="nf">int</span><span class="p">((</span><span class="n">time</span><span class="p">.</span><span class="nf">time</span><span class="p">()</span> <span class="k">if</span> <span class="n">now</span> <span class="ow">is</span> <span class="bp">None</span> <span class="k">else</span> <span class="n">now</span><span class="p">)</span> <span class="o">//</span> <span class="n">step</span><span class="p">)</span>
    <span class="k">return</span> <span class="nf">hotp</span><span class="p">(</span><span class="n">key</span><span class="p">,</span> <span class="n">t</span><span class="p">,</span> <span class="n">digits</span><span class="p">,</span> <span class="n">digest</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">key_from_base32</span><span class="p">(</span><span class="n">secret</span><span class="p">:</span> <span class="nb">str</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="nb">bytes</span><span class="p">:</span>
    <span class="n">s</span> <span class="o">=</span> <span class="n">secret</span><span class="p">.</span><span class="nf">replace</span><span class="p">(</span><span class="sh">"</span><span class="s"> </span><span class="sh">"</span><span class="p">,</span> <span class="sh">""</span><span class="p">).</span><span class="nf">upper</span><span class="p">()</span>
    <span class="k">return</span> <span class="n">base64</span><span class="p">.</span><span class="nf">b32decode</span><span class="p">(</span><span class="n">s</span> <span class="o">+</span> <span class="sh">"</span><span class="s">=</span><span class="sh">"</span> <span class="o">*</span> <span class="p">(</span><span class="o">-</span><span class="nf">len</span><span class="p">(</span><span class="n">s</span><span class="p">)</span> <span class="o">%</span> <span class="mi">8</span><span class="p">))</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">struct.pack("&gt;Q", ...)</code> writes the counter as an unsigned 64-bit big-endian integer, which is what the RFC specifies. The <code class="language-plaintext highlighter-rouge">&amp; 0x7FFFFFFF</code> is the masked top bit. <code class="language-plaintext highlighter-rouge">zfill</code> is the leading zeros: a code of <code class="language-plaintext highlighter-rouge">012345</code> is a valid code, and an implementation that drops the zero will reject one login in ten.</p>

<p>Both RFCs end with test vectors, and an implementation that has not been run against them is unfinished. With the ASCII key <code class="language-plaintext highlighter-rouge">12345678901234567890</code>:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">k</span> <span class="o">=</span> <span class="sa">b</span><span class="sh">"</span><span class="s">12345678901234567890</span><span class="sh">"</span>

<span class="c1"># RFC 4226, Appendix D: HOTP for counters 0 to 9
</span><span class="k">assert</span> <span class="p">[</span><span class="nf">hotp</span><span class="p">(</span><span class="n">k</span><span class="p">,</span> <span class="n">c</span><span class="p">)</span> <span class="k">for</span> <span class="n">c</span> <span class="ow">in</span> <span class="nf">range</span><span class="p">(</span><span class="mi">10</span><span class="p">)]</span> <span class="o">==</span> <span class="p">[</span>
    <span class="sh">"</span><span class="s">755224</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">287082</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">359152</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">969429</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">338314</span><span class="sh">"</span><span class="p">,</span>
    <span class="sh">"</span><span class="s">254676</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">287922</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">162583</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">399871</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">520489</span><span class="sh">"</span><span class="p">]</span>

<span class="c1"># RFC 6238, Appendix B: TOTP with SHA-1, 8 digits
</span><span class="k">for</span> <span class="n">t</span><span class="p">,</span> <span class="n">want</span> <span class="ow">in</span> <span class="p">[(</span><span class="mi">59</span><span class="p">,</span> <span class="sh">"</span><span class="s">94287082</span><span class="sh">"</span><span class="p">),</span> <span class="p">(</span><span class="mi">1111111109</span><span class="p">,</span> <span class="sh">"</span><span class="s">07081804</span><span class="sh">"</span><span class="p">),</span>
                <span class="p">(</span><span class="mi">1111111111</span><span class="p">,</span> <span class="sh">"</span><span class="s">14050471</span><span class="sh">"</span><span class="p">),</span> <span class="p">(</span><span class="mi">1234567890</span><span class="p">,</span> <span class="sh">"</span><span class="s">89005924</span><span class="sh">"</span><span class="p">),</span>
                <span class="p">(</span><span class="mi">2000000000</span><span class="p">,</span> <span class="sh">"</span><span class="s">69279037</span><span class="sh">"</span><span class="p">),</span> <span class="p">(</span><span class="mi">20000000000</span><span class="p">,</span> <span class="sh">"</span><span class="s">65353130</span><span class="sh">"</span><span class="p">)]:</span>
    <span class="k">assert</span> <span class="nf">totp</span><span class="p">(</span><span class="n">k</span><span class="p">,</span> <span class="n">t</span><span class="p">,</span> <span class="n">digits</span><span class="o">=</span><span class="mi">8</span><span class="p">)</span> <span class="o">==</span> <span class="n">want</span>
</code></pre></div></div>

<p>The last vector is a time in the year 2603, which catches anyone who keeps Unix time in a 32-bit integer. One trap in Appendix B: the SHA-256 and SHA-512 rows use longer keys (32 and 64 bytes, the same digits repeated), though the table does not say so. Run them with the 20-byte key and they fail on a correct implementation.</p>

<p>Making a new secret is one line. RFC 4226 says the key “MUST be at least 128 bits” and recommends 160:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="n">secrets</span>
<span class="n">secret</span> <span class="o">=</span> <span class="n">base64</span><span class="p">.</span><span class="nf">b32encode</span><span class="p">(</span><span class="n">secrets</span><span class="p">.</span><span class="nf">token_bytes</span><span class="p">(</span><span class="mi">20</span><span class="p">)).</span><span class="nf">decode</span><span class="p">()</span>   <span class="c1"># 32 Base32 characters
</span></code></pre></div></div>

<h2 id="checking-a-code-on-the-server"><a class="anchor" href="#checking-a-code-on-the-server">Checking a code on the server</a></h2>

<p>Computing a code is the easy half. A server that checks them has three more jobs, and each one is a line in an RFC that is easy to skip.</p>

<p>Allow for drift, narrowly. Phones run a few seconds fast or slow, and people type the code just as the ring runs out. RFC 6238 says: “We RECOMMEND that at most one time step is allowed as the network delay.” So accept the current step and the one either side, and no more.</p>

<p>Refuse a code that has already worked. The same RFC: “The verifier MUST NOT accept the second attempt of the OTP after the successful validation has been issued for the first OTP.” A code is otherwise good for up to 90 seconds with the window above, plenty of time for someone watching to use it again. Store the last step that succeeded for each user and accept only later ones.</p>

<p>Limit the guesses. Six digits is a million possibilities, and with a three-step window three of them are right at any moment. RFC 4226 puts an attacker’s chance at about <em>sv</em>/10^<em>Digit</em>, for <em>s</em> accepted codes and <em>v</em> attempts. At ten guesses a second for an hour, that is a little over a ten percent chance of getting in, with no throttling. Section 7.3 asks for a maximum number of attempts, and adds that “the delay or lockout schemes MUST be across login sessions,” so an attacker cannot reset the count by reconnecting.</p>

<p>All three fit in one function:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">verify</span><span class="p">(</span><span class="n">key</span><span class="p">:</span> <span class="nb">bytes</span><span class="p">,</span> <span class="n">code</span><span class="p">:</span> <span class="nb">str</span><span class="p">,</span> <span class="n">last_step</span><span class="p">:</span> <span class="nb">int</span><span class="p">,</span> <span class="n">now</span><span class="p">:</span> <span class="nb">float</span> <span class="o">|</span> <span class="bp">None</span> <span class="o">=</span> <span class="bp">None</span><span class="p">,</span>
           <span class="n">window</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">1</span><span class="p">,</span> <span class="n">step</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">30</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="nb">int</span> <span class="o">|</span> <span class="bp">None</span><span class="p">:</span>
    <span class="n">t</span> <span class="o">=</span> <span class="nf">int</span><span class="p">((</span><span class="n">time</span><span class="p">.</span><span class="nf">time</span><span class="p">()</span> <span class="k">if</span> <span class="n">now</span> <span class="ow">is</span> <span class="bp">None</span> <span class="k">else</span> <span class="n">now</span><span class="p">)</span> <span class="o">//</span> <span class="n">step</span><span class="p">)</span>
    <span class="k">for</span> <span class="n">s</span> <span class="ow">in</span> <span class="nf">range</span><span class="p">(</span><span class="n">t</span> <span class="o">-</span> <span class="n">window</span><span class="p">,</span> <span class="n">t</span> <span class="o">+</span> <span class="n">window</span> <span class="o">+</span> <span class="mi">1</span><span class="p">):</span>
        <span class="k">if</span> <span class="n">s</span> <span class="o">&gt;</span> <span class="n">last_step</span> <span class="ow">and</span> <span class="n">hmac</span><span class="p">.</span><span class="nf">compare_digest</span><span class="p">(</span><span class="nf">hotp</span><span class="p">(</span><span class="n">key</span><span class="p">,</span> <span class="n">s</span><span class="p">),</span> <span class="n">code</span><span class="p">):</span>
            <span class="k">return</span> <span class="n">s</span>      <span class="c1"># save this as the user's new last_step
</span>    <span class="k">return</span> <span class="bp">None</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">hmac.compare_digest</code> compares in constant time, so the response time leaks nothing about how many digits matched. The rate limit lives outside the function, in front of it, counted per account.</p>

<h2 id="gotchas-worth-knowing"><a class="anchor" href="#gotchas-worth-knowing">Gotchas worth knowing</a></h2>

<p>The server keeps the secret in a form it can use. A password can be stored as a slow hash, and a stolen hash still has to be cracked. A TOTP key cannot: the server needs the key itself to compute the codes. Anyone who copies the key table can generate valid codes for every user, forever, without touching a phone. RFC 6238 says “The key store MUST be in a secure area,” which in practice means encrypted at rest with the encryption key kept outside the database. If the table ever leaks, every user has to enrol again.</p>

<p>The clock is part of the security. A server whose clock drifts by more than a step starts refusing good codes, and the usual fix, widening the window, makes guessing easier. Keep the server on NTP and leave the window alone.</p>

<p>The QR code is the key. A screenshot of the enrolment screen, a QR code left in a support ticket, or a secret pasted into chat is the second factor, handed over in full. Show it once, over HTTPS, and never log it.</p>

<p>Recovery codes are passwords. Most services hand out a list of single-use backup codes at enrolment. They skip the second factor entirely, so they need the same care as the key: stored hashed on the server, and somewhere offline by the user.</p>

<h2 id="the-attack-it-cannot-stop"><a class="anchor" href="#the-attack-it-cannot-stop">The attack it cannot stop</a></h2>

<p>TOTP proves that someone has the key now. It cannot prove who is asking for the code.</p>

<p>From March 2022 a group that Group-IB later called 0ktapus sent text messages to employees of Twilio, Cloudflare and well over a hundred other companies, linking to pages made to look like their companies’ Okta login. The pages asked for a username, a password, and then the six-digit code, and passed everything to the attackers in real time, inside the 30 seconds the code was good for. Group-IB’s count, published on 25 August 2022, was 9,931 stolen credentials and 5,441 one-time codes, from 136 email domains.</p>

<p>Cloudflare’s account of its part is the clearest lesson. At least 76 employees got the texts, and three typed their credentials into the fake page. Nobody got in. “Cloudflare does not use TOTP codes”; instead, “every employee at the company is issued a FIDO2-compliant security key.” A FIDO2 key signs a challenge bound to the website’s real origin, so a lookalike domain gets a signature that the real site rejects, and there is no code for a person to read out.</p>

<p>CISA’s October 2022 fact sheet, “Implementing Phishing-Resistant MFA,” draws the same line. FIDO/WebAuthn (security keys and passkeys) and PKI smart cards are phishing-resistant; app-based one-time codes are not. App codes, with push prompts that use number matching, are “the best options for small- and medium-size business that cannot immediately implement phishing-resistant MFA.”</p>

<h2 id="where-it-fits"><a class="anchor" href="#where-it-fits">Where it fits</a></h2>

<p>TOTP is a large improvement over a password alone. It defeats reused and leaked passwords, which is what most account takeovers use, and it costs nothing: the phone works offline and is already in everyone’s pocket. For a self-hosted service it is often the only second factor on offer, and turning it on is always better than not.</p>

<p>It is weakest exactly where a phishing page is strongest: a person who believes the page in front of them will type whatever it asks for. Where an account matters and passkeys or security keys are supported, use those, and keep TOTP for everything else. Where TOTP is what you run, the four rules above cover most of the ways it fails: a narrow window, no reuse, a limit on guesses, and a key store treated like the password database it really is.</p>

<h2 id="sources"><a class="anchor" href="#sources">Sources</a></h2>

<ul>
  <li>M’Raihi, D., M. Bellare, F. Hoornaert, D. Naccache and O. Ranen. RFC 4226, “HOTP: An HMAC-Based One-Time Password Algorithm.” December 2005.</li>
  <li>M’Raihi, D., S. Machani, M. Pei and J. Rydell. RFC 6238, “TOTP: Time-Based One-Time Password Algorithm.” May 2011.</li>
  <li>Josefsson, S. RFC 4648, “The Base16, Base32, and Base64 Data Encodings.” October 2006.</li>
  <li>Google. “Key Uri Format.” google-authenticator wiki, GitHub.</li>
  <li>Group-IB. “Roasting 0ktapus: The phishing campaign going after Okta identity credentials.” 25 August 2022.</li>
  <li>Cloudflare. “The mechanics of a sophisticated phishing scam and how we stopped it.” 9 August 2022.</li>
  <li>Cybersecurity and Infrastructure Security Agency. “Implementing Phishing-Resistant MFA.” Fact sheet, October 2022.</li>
  <li>Python Software Foundation. Documentation for the <code class="language-plaintext highlighter-rouge">hmac</code>, <code class="language-plaintext highlighter-rouge">hashlib</code>, <code class="language-plaintext highlighter-rouge">struct</code>, <code class="language-plaintext highlighter-rouge">base64</code> and <code class="language-plaintext highlighter-rouge">secrets</code> modules.</li>
</ul>]]></content><author><name>Securus</name></author><category term="Portfolio" /><category term="Cryptography" /><category term="totp" /><category term="hotp" /><category term="mfa" /><category term="authentication" /><category term="python" /><category term="phishing" /><category term="security" /><summary type="html"><![CDATA[How an authenticator app turns a shared secret and the clock into a six-digit code, a working implementation checked against the RFC test vectors, what a server has to get right when it checks one, and the attack the codes cannot stop.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://securus.pages.dev/assets/img/social-preview.png" /><media:content medium="image" url="https://securus.pages.dev/assets/img/social-preview.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">systemd service hardening: sandboxing what you already run</title><link href="https://securus.pages.dev/posts/systemd-service-hardening/" rel="alternate" type="text/html" title="systemd service hardening: sandboxing what you already run" /><published>2026-07-21T00:00:00-04:00</published><updated>2026-07-21T00:00:00-04:00</updated><id>https://securus.pages.dev/posts/systemd-service-hardening</id><content type="html" xml:base="https://securus.pages.dev/posts/systemd-service-hardening/"><![CDATA[<h2 id="why-this-exists"><a class="anchor" href="#why-this-exists">Why this exists</a></h2>

<p>In September 1975 Jerome Saltzer and Michael Schroeder published “The Protection of Information in Computer Systems,” a paper that set out eight design principles for secure systems. Most of them are still quoted. The best known is the principle of least privilege: “Every program and every user of the system should operate using the least set of privileges necessary to complete the job.” Their reasoning was about damage. A program that holds only what it needs can do only limited harm when it goes wrong, and fewer programs have to be trusted at all.</p>

<p>For most of the following thirty-five years, Unix daemons ignored the advice, mostly because the operating system gave them no practical way to follow it. A service ran as some user and could do whatever that user could do. The kernel grew the tools piece by piece: capabilities in Linux 2.2, mount namespaces in 2.4.19, seccomp in 2005 and its programmable form, seccomp-bpf, in 2012, written for the Chrome sandbox. Using them meant writing wrapper code. When Lennart Poettering and Kay Sievers began systemd in 2010, they made them lines in a unit file.</p>

<p>A firewall decides who reaches the service. SSH hardening decides who reaches the host. Neither says anything about what a service can do to the rest of the machine once it is running and, one day, compromised.</p>

<p>That gap matters because most of what you run does not need most of what it can touch. A metrics exporter has no business reading <code class="language-plaintext highlighter-rouge">/home</code>. A web app does not need to load kernel modules. A media server never writes to <code class="language-plaintext highlighter-rouge">/etc</code>. By default every one of them can, because a plain unit runs with the full ambient authority of its user.</p>

<p>systemd ships a long list of directives that take that authority away one piece at a time. They cost nothing to run, need no extra package, and most services never notice them. This is the cheapest hardening on the list, and the one people skip.</p>

<hr />

<h2 id="how-it-actually-works"><a class="anchor" href="#how-it-actually-works">How it actually works</a></h2>

<p>The kernel already has the primitives: namespaces, capabilities, seccomp, mount restrictions. Wiring them up by hand is miserable. systemd exposes them as unit options, applies them before the service’s process starts, and gives you one command to score the result.</p>

<p>Three ideas cover most of it.</p>

<p>Filesystem isolation mounts the host read-only for the service, hides directories it should never see, and hands back only the paths it writes to.</p>

<p>Privilege reduction drops Linux capabilities to the empty set, blocks privilege escalation, and refuses memory that is both writable and executable.</p>

<p>Kernel surface reduction filters system calls down to the ones a normal service uses, and blocks the address families and namespaces it will never open.</p>

<p>You do not need to understand each kernel feature to benefit. You need to know which directive maps to which “this service should never do that.”</p>

<hr />

<h2 id="minimum-useful-config"><a class="anchor" href="#minimum-useful-config">Minimum useful config</a></h2>

<p>Do not edit the packaged unit. Use a drop-in, so package updates leave your changes alone:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">sudo </span>systemctl edit myservice
</code></pre></div></div>

<p>That opens an override at <code class="language-plaintext highlighter-rouge">/etc/systemd/system/myservice.service.d/override.conf</code>. A sensible starting set:</p>

<div class="language-ini highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nn">[Service]</span><span class="w">
</span><span class="c"># Refuse setuid/setgid escalation for the process and everything it spawns
</span><span class="py">NoNewPrivileges</span><span class="p">=</span><span class="s">true</span>
<span class="w">
</span><span class="c"># Read-only view of the whole OS, private /tmp, home directories hidden
</span><span class="py">ProtectSystem</span><span class="p">=</span><span class="s">strict</span>
<span class="py">ProtectHome</span><span class="p">=</span><span class="s">true</span>
<span class="py">PrivateTmp</span><span class="p">=</span><span class="s">true</span>
<span class="w">
</span><span class="c"># Hand back only what the service actually writes to
</span><span class="py">ReadWritePaths</span><span class="p">=</span><span class="s">/var/lib/myservice</span>
<span class="w">
</span><span class="c"># Kernel is off-limits
</span><span class="py">ProtectKernelTunables</span><span class="p">=</span><span class="s">true</span>
<span class="py">ProtectKernelModules</span><span class="p">=</span><span class="s">true</span>
<span class="py">ProtectControlGroups</span><span class="p">=</span><span class="s">true</span>
<span class="w">
</span><span class="c"># Drop every capability, then add back only what is needed (usually nothing)
</span><span class="py">CapabilityBoundingSet</span><span class="p">=</span>
<span class="py">AmbientCapabilities</span><span class="p">=</span>
<span class="w">
</span><span class="c"># Syscall allow/deny list: allow the normal service set, drop the rest
</span><span class="py">SystemCallFilter</span><span class="p">=</span><span class="s">@system-service</span>
<span class="py">SystemCallErrorNumber</span><span class="p">=</span><span class="s">EPERM</span>
<span class="w">
</span><span class="c"># Network families most services never need
</span><span class="py">RestrictAddressFamilies</span><span class="p">=</span><span class="s">AF_INET AF_INET6 AF_UNIX</span>
<span class="py">RestrictNamespaces</span><span class="p">=</span><span class="s">true</span>
<span class="py">MemoryDenyWriteExecute</span><span class="p">=</span><span class="s">true</span>
</code></pre></div></div>

<p>Reload and restart:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">sudo </span>systemctl daemon-reload
<span class="nb">sudo </span>systemctl restart myservice
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">ProtectSystem=strict</code> does the heavy lifting, and it is the one most likely to break something, because a service that quietly writes outside its data directory will now fail. That failure is the point. It tells you exactly which path to add to <code class="language-plaintext highlighter-rouge">ReadWritePaths</code>, and nothing else stays writable.</p>

<p>The empty <code class="language-plaintext highlighter-rouge">CapabilityBoundingSet=</code> is the bluntest line here. An empty assignment clears the set entirely, so even a service started as root keeps none of root’s special powers. A service that needs one, a DNS server binding port 53 for instance, gets it back by name (<code class="language-plaintext highlighter-rouge">CapabilityBoundingSet=CAP_NET_BIND_SERVICE</code>), and if it runs as an ordinary user rather than starting as root, names it in <code class="language-plaintext highlighter-rouge">AmbientCapabilities=</code> as well. Nothing else comes back.</p>

<hr />

<h2 id="watching-it-work"><a class="anchor" href="#watching-it-work">Watching it work</a></h2>

<p>systemd scores a unit’s exposure for you:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>systemd-analyze security myservice
</code></pre></div></div>

<p>You get a table of directives and an overall number from 0 (locked down) to 10 (wide open). A stock third-party unit usually lands around 9. The config above typically pulls the same service under 3.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>→ Overall exposure level for myservice.service: 2.4 OK 🙂
</code></pre></div></div>

<p>The number is a guide, not a grade. A high score on a service that only talks to localhost matters less than a low score on something exposed to the internet. Read the table as well as the total, and spend the effort where the reachable attack surface actually is.</p>

<p>A restriction written in a file is not yet a restriction in force. To see what a directive does, run a throwaway command under it:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">sudo </span>systemd-run <span class="nt">--property</span><span class="o">=</span><span class="nv">ProtectHome</span><span class="o">=</span><span class="nb">true</span> <span class="nt">--pty</span> <span class="nb">ls</span> /home
</code></pre></div></div>

<p>An empty listing is the sandbox doing its job. That transient unit shows the directive, though, not the service. To look through the running service’s own eyes, list the directory through its root in <code class="language-plaintext highlighter-rouge">/proc</code>, which shows the filesystem exactly as the process sees it, mount namespace included:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">sudo ls</span> /proc/<span class="si">$(</span>systemctl show <span class="nt">-p</span> MainPID <span class="nt">--value</span> myservice<span class="si">)</span>/root/home
</code></pre></div></div>

<p>If the drop-in took effect, that listing is empty too.</p>

<hr />

<h2 id="gotchas-worth-knowing"><a class="anchor" href="#gotchas-worth-knowing">Gotchas worth knowing</a></h2>

<p><code class="language-plaintext highlighter-rouge">ProtectSystem=strict</code> breaks sloppy services on purpose. If a unit fails to start after you apply it, read <code class="language-plaintext highlighter-rouge">journalctl -u myservice</code> for the read-only-filesystem error, add that path to <code class="language-plaintext highlighter-rouge">ReadWritePaths</code>, and try again. Do not fall back to the weaker <code class="language-plaintext highlighter-rouge">ProtectSystem=full</code> without a real reason; it trades away most of the benefit.</p>

<p><code class="language-plaintext highlighter-rouge">SystemCallFilter</code> changes how failures look. With <code class="language-plaintext highlighter-rouge">SystemCallErrorNumber=EPERM</code>, as in the config above, a blocked system call simply fails, and the service logs “Operation not permitted” or behaves oddly. Without that line, the kernel kills the process with <code class="language-plaintext highlighter-rouge">SIGSYS</code> the moment it makes the call. Either way, find the missing group and add it rather than removing the filter: <code class="language-plaintext highlighter-rouge">systemd-analyze syscall-filter</code> lists every group and its calls. <code class="language-plaintext highlighter-rouge">@system-service</code> already includes the common ones, <code class="language-plaintext highlighter-rouge">@resources</code> among them. A time-sync daemon, for instance, needs <code class="language-plaintext highlighter-rouge">@clock</code>, which it leaves out. Never allow <code class="language-plaintext highlighter-rouge">@obsolete</code> or <code class="language-plaintext highlighter-rouge">@raw-io</code> without a specific need.</p>

<p><code class="language-plaintext highlighter-rouge">MemoryDenyWriteExecute=true</code> and just-in-time compilers do not mix. The systemd documentation says as much: the option is incompatible with programs that generate code at runtime. A service built on the JVM, Node.js or another JIT runtime may refuse to start or crash under it, and for those services the line has to go.</p>

<p>Containers already do some of this. If a service runs as a rootless Podman or Quadlet unit, it inherits its own namespaces and a default seccomp profile, so a few directives are redundant. The filesystem and capability options still apply to the container runtime itself and are worth keeping.</p>

<p>Test the actual workload as well as startup. A service can start clean and then fail the first time it opens a socket, forks a helper or writes a cache file. Exercise the real paths after hardening, watch the journal, and only then walk away.</p>

<hr />

<h2 id="where-it-fits"><a class="anchor" href="#where-it-fits">Where it fits</a></h2>

<p>The layers run from the outside in. The <a href="/posts/iptables-firewall-rules/">firewall</a> denies inbound traffic by default and opens only the ports you serve. <a href="/posts/hardening-ssh/">SSH hardening</a> means keys only, no root login, no passwords. <a href="/posts/fail2ban-ssh-lockouts/">fail2ban</a> bans the brute-force noise that gets past the first two. Service sandboxing assumes a service will eventually be compromised, and makes sure that when it is, it lands in an empty room.</p>

<p>The first three keep attackers out. This one decides how much they get when one of the others fails, and eventually one of them will. It is the difference between a compromised exporter reading a metric and a compromised exporter reading your home directory. Saltzer and Schroeder asked for it in 1975. The directives are already installed, and the only cost is the ten minutes it takes to write the drop-in and read the journal once.</p>

<h2 id="sources"><a class="anchor" href="#sources">Sources</a></h2>

<ul>
  <li>Saltzer, Jerome H., and Michael D. Schroeder. “The Protection of Information in Computer Systems.” <em>Proceedings of the IEEE</em> 63, no. 9 (September 1975): 1278 to 1308.</li>
  <li>systemd project. systemd.exec(5), systemd-analyze(1) and systemd-run(1) manual pages.</li>
  <li>Linux man-pages project. proc(5), on <code class="language-plaintext highlighter-rouge">/proc/[pid]/root</code>.</li>
  <li>Drewry, Will. “Dynamic seccomp policies (using BPF filters).” Linux kernel mailing list, January 2012.</li>
</ul>]]></content><author><name>Securus</name></author><category term="Portfolio" /><category term="Linux" /><category term="systemd" /><category term="hardening" /><category term="sandboxing" /><category term="linux" /><category term="security" /><category term="homelab" /><summary type="html"><![CDATA[How to lock down a systemd service with the sandboxing directives that ship in the box, how to measure the result and check it is live, and where it sits next to a firewall and a hardened SSH setup.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://securus.pages.dev/assets/img/social-preview.png" /><media:content medium="image" url="https://securus.pages.dev/assets/img/social-preview.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">fail2ban: the lockouts iptables doesn’t do</title><link href="https://securus.pages.dev/posts/fail2ban-ssh-lockouts/" rel="alternate" type="text/html" title="fail2ban: the lockouts iptables doesn’t do" /><published>2026-04-07T00:00:00-04:00</published><updated>2026-04-07T00:00:00-04:00</updated><id>https://securus.pages.dev/posts/fail2ban-ssh-lockouts</id><content type="html" xml:base="https://securus.pages.dev/posts/fail2ban-ssh-lockouts/"><![CDATA[<h2 id="why-fail2ban-exists"><a class="anchor" href="#why-fail2ban-exists">Why fail2ban exists</a></h2>

<p>Every SSH server on the internet keeps a written record of the people trying to get into it. The record is the authentication log, and on a server with port 22 open it fills with failed logins from addresses nobody has heard of, at every hour, for as long as the machine is up. On most machines, for a long time, the log was the end of it. An administrator could read it, and usually did not.</p>

<p>Cyril Jaquier started fail2ban in 2004 to close that loop. The program reads the log, recognizes a failed login, counts, and when one address has failed too often, tells the firewall to stop listening to it for a while.</p>

<p><code class="language-plaintext highlighter-rouge">iptables</code> decides <em>who is allowed to connect</em>. SSH hardening decides <em>what they can do if they reach you</em>. Neither addresses the problem in between: an attacker who is technically allowed to reach port 22 and is spending all day guessing passwords.</p>

<p>The manual version is to tail <code class="language-plaintext highlighter-rouge">journalctl</code>, watch for failed logins and write a rule. Nobody does that for long. <code class="language-plaintext highlighter-rouge">fail2ban</code> automates exactly that loop: read a log, match a pattern, push a temporary firewall rule against the offending IP, and expire the rule later.</p>

<p>That is the whole mental model. Everything else is configuration.</p>

<hr />

<h2 id="how-it-actually-works"><a class="anchor" href="#how-it-actually-works">How it actually works</a></h2>

<p>It is built from three pieces.</p>

<p>A filter is a regex that matches “this log line means a failed authentication.” Filters come pre-shipped for SSH, nginx, Postfix and dozens of other services.</p>

<p>A jail binds one filter to a backend (which log to watch), a threshold (how many matches before acting) and an action (what to do).</p>

<p>An action is usually an <code class="language-plaintext highlighter-rouge">iptables</code> or <code class="language-plaintext highlighter-rouge">nftables</code> rule that blocks the source IP, plus a timer that reverses it.</p>

<p><code class="language-plaintext highlighter-rouge">fail2ban-server</code> runs as a daemon, tails the relevant logs and applies actions when thresholds are hit. <code class="language-plaintext highlighter-rouge">fail2ban-client</code> is how you talk to it.</p>

<hr />

<h2 id="minimum-useful-config"><a class="anchor" href="#minimum-useful-config">Minimum useful config</a></h2>

<p>The default install does almost nothing until a jail is enabled. Override the defaults in <code class="language-plaintext highlighter-rouge">/etc/fail2ban/jail.local</code>. Never edit <code class="language-plaintext highlighter-rouge">jail.conf</code> directly; its own header warns that it will be overwritten by package updates.</p>

<div class="language-ini highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nn">[DEFAULT]</span><span class="w">
</span><span class="py">bantime</span><span class="w">  </span><span class="p">=</span><span class="w"> </span><span class="s">1h</span>
<span class="py">findtime</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="s">10m</span>
<span class="py">maxretry</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="s">5</span>
<span class="py">backend</span><span class="w">  </span><span class="p">=</span><span class="w"> </span><span class="s">systemd</span>
<span class="py">ignoreip</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="s">127.0.0.1/8 ::1 100.64.0.0/10</span>
<span class="w">
</span><span class="nn">[sshd]</span><span class="w">
</span><span class="py">enabled</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="s">true</span>
</code></pre></div></div>

<p>What this says:</p>

<ul>
  <li>Five failed attempts within ten minutes earn a one-hour ban.</li>
  <li>Logs come from the systemd journal, not a flat file, which suits any modern Fedora, Debian or Ubuntu.</li>
  <li><code class="language-plaintext highlighter-rouge">ignoreip</code> exempts loopback and the whole of <code class="language-plaintext highlighter-rouge">100.64.0.0/10</code>. That range is the shared address space RFC 6598 set aside for carrier-grade NAT, and Tailscale assigns its devices addresses from it, so a typo on a machine reached over the tailnet cannot lock its administrator out.</li>
  <li>The <code class="language-plaintext highlighter-rouge">[sshd]</code> jail uses the built-in filter at <code class="language-plaintext highlighter-rouge">/etc/fail2ban/filter.d/sshd.conf</code>.</li>
</ul>

<p>An exemption is trust, and it is exactly as wide as the range written down. Exempting a whole private range means any device in it, including one that has been compromised, can guess passwords without limit. Keep the list as narrow as the access paths you actually use.</p>

<p>Enable and start:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">sudo </span>systemctl <span class="nb">enable</span> <span class="nt">--now</span> fail2ban
</code></pre></div></div>

<p>Verify it’s watching the right thing:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">sudo </span>fail2ban-client status sshd
</code></pre></div></div>

<p>The output looks something like this:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Status for the jail: sshd
|- Filter
|  |- Currently failed: 0
|  |- Total failed:     0
|  `- Journal matches:  _SYSTEMD_UNIT=sshd.service + _COMM=sshd + _COMM=sshd-session
`- Actions
   |- Currently banned: 0
   |- Total banned:     0
   `- Banned IP list:
</code></pre></div></div>

<p>With the systemd backend, the third line of the filter section lists the journal matches the jail selects on; a file-based backend prints <code class="language-plaintext highlighter-rouge">File list:</code> and the paths instead. The exact matches depend on the fail2ban version. That is a working jail with no current offenders. On a server with port 22 exposed to the internet, the “Total banned” counter starts climbing within hours.</p>

<hr />

<h2 id="watching-it-work"><a class="anchor" href="#watching-it-work">Watching it work</a></h2>

<p>The most informative single command is the same one:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">sudo </span>fail2ban-client status sshd
</code></pre></div></div>

<p>It lists the currently banned IPs and the lifetime totals for that jail.</p>

<p>To unban an IP by hand (your own, after a self-inflicted lockout):</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">sudo </span>fail2ban-client <span class="nb">set </span>sshd unbanip 203.0.113.42
</code></pre></div></div>

<p>To see the rules fail2ban’s actions have put in the firewall:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">sudo </span>iptables <span class="nt">-L</span> f2b-sshd <span class="nt">-n</span> <span class="nt">--line-numbers</span>
</code></pre></div></div>

<p>The <code class="language-plaintext highlighter-rouge">f2b-sshd</code> chain is created by the iptables actions on the first ban and holds the active blocks. When a ban expires, its line is removed automatically. With an nftables action the bans live in nftables instead, and <code class="language-plaintext highlighter-rouge">sudo nft list ruleset</code> shows them.</p>

<hr />

<h2 id="gotchas-worth-knowing"><a class="anchor" href="#gotchas-worth-knowing">Gotchas worth knowing</a></h2>

<p>Bans survive a restart. Since version 0.9, fail2ban keeps them in an SQLite database, <code class="language-plaintext highlighter-rouge">/var/lib/fail2ban/fail2ban.sqlite3</code>, and puts back the ones that have not expired when it starts. What it does not do by default is remember repeat offenders. Adding <code class="language-plaintext highlighter-rouge">bantime.increment = true</code>, and tuning <code class="language-plaintext highlighter-rouge">bantime.maxtime</code>, makes each new ban for the same address longer than the last, growing exponentially, which is closer to what you want. The database forgets bans after a day by default, so for that memory to last longer, raise <code class="language-plaintext highlighter-rouge">dbpurgeage</code> in <code class="language-plaintext highlighter-rouge">fail2ban.local</code> as well.</p>

<p>The backend decides what is read. With <code class="language-plaintext highlighter-rouge">backend = systemd</code>, fail2ban reads the journal and ignores any <code class="language-plaintext highlighter-rouge">logpath</code>. That is the right choice where no syslog daemon runs: Debian 12 no longer installs rsyslog by default, so on a fresh install there is no <code class="language-plaintext highlighter-rouge">/var/log/auth.log</code>, and a jail pointed at it has nothing to read. The silent failure is a journal filter that matches nothing. The sshd filter picks journal entries by unit and process name, and when OpenSSH 9.8 moved authentication into a separate <code class="language-plaintext highlighter-rouge">sshd-session</code> process, filters had to learn the new name. Current fail2ban matches it; older releases may not. The test is simple: fail one login on purpose, then check that “Total failed” went up.</p>

<p><code class="language-plaintext highlighter-rouge">ignoreip</code> is the safety net. If you are remote and rely on a VPN or jump host to reach the machine, exempt that range explicitly. Locking yourself out of a remote host because of a sticky key is a fixable mistake, but an annoying one.</p>

<p>fail2ban needs something to install rules into. Without iptables or nftables available, the action layer has nowhere to put a ban. On a minimal container or a stripped-down system, <code class="language-plaintext highlighter-rouge">firewalld</code> or plain <code class="language-plaintext highlighter-rouge">iptables</code> may need installing first.</p>

<hr />

<h2 id="where-it-fits"><a class="anchor" href="#where-it-fits">Where it fits</a></h2>

<p>In layers, from the outside in. The <a href="/posts/iptables-firewall-rules/">firewall</a> denies inbound traffic by default and opens only the ports actually served. <a href="/posts/hardening-ssh/">SSH hardening</a> takes away passwords and root logins, and closes port 22 where that can be managed. fail2ban catches what gets through anyway.</p>

<p>Each layer assumes the one before it is in place. fail2ban substitutes for neither of the others; it is the alarm installed after the door is already locked. It is cheap to set up and costs nothing to run, and it turns a constant stream of probes into a problem that mostly solves itself. With passwords switched off, the guesses it bans could never have succeeded. What it saves is the noise, and the log that an administrator might, one day, actually read.</p>

<h2 id="sources"><a class="anchor" href="#sources">Sources</a></h2>

<ul>
  <li>fail2ban project. <code class="language-plaintext highlighter-rouge">jail.conf</code>, <code class="language-plaintext highlighter-rouge">fail2ban.conf</code> and <code class="language-plaintext highlighter-rouge">filter.d/sshd.conf</code>, and the fail2ban(1) manual pages.</li>
  <li>Weil, J., V. Kuarsingh, C. Donley, C. Liljenstolpe and M. Azinger. RFC 6598, “IANA-Reserved IPv4 Prefix for Shared Address Space.” April 2012.</li>
  <li>OpenSSH 9.8 release notes, July 2024.</li>
  <li>Debian. <em>Release notes for Debian 12 (bookworm)</em>.</li>
</ul>]]></content><author><name>Securus</name></author><category term="Portfolio" /><category term="Linux" /><category term="fail2ban" /><category term="linux" /><category term="security" /><category term="ssh" /><category term="firewall" /><category term="intrusion-prevention" /><summary type="html"><![CDATA[fail2ban's model of filters, jails and actions, the minimum useful config, how to confirm it is watching the right log, and where it sits beside iptables and a hardened SSH setup.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://securus.pages.dev/assets/img/social-preview.png" /><media:content medium="image" url="https://securus.pages.dev/assets/img/social-preview.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">iptables: building rules that make sense</title><link href="https://securus.pages.dev/posts/iptables-firewall-rules/" rel="alternate" type="text/html" title="iptables: building rules that make sense" /><published>2026-02-18T00:00:00-05:00</published><updated>2026-02-18T00:00:00-05:00</updated><id>https://securus.pages.dev/posts/iptables-firewall-rules</id><content type="html" xml:base="https://securus.pages.dev/posts/iptables-firewall-rules/"><![CDATA[<h2 id="four-firewalls-in-under-a-decade"><a class="anchor" href="#four-firewalls-in-under-a-decade">Four firewalls in under a decade</a></h2>

<p>Linux has rewritten its firewall more often than most parts of the kernel. The first, ipfw, was borrowed from BSD. Linux 2.0 replaced it with ipfwadm, and 2.2 with ipchains. In 1998 Rusty Russell started the netfilter project to do the job properly, as a set of hooks in the kernel’s network stack with a stateful packet filter on top, and its command-line tool, iptables, arrived with Linux 2.4 in January 2001. Russell wrote the project’s early guides himself, in a breezy voice, under the series title “Rusty’s Remarkably Unreliable Guides.”</p>

<p>iptables has also outlived the arrival of its replacement. nftables entered the kernel in version 3.13, in 2014, and on most current distributions the <code class="language-plaintext highlighter-rouge">iptables</code> command is in fact <code class="language-plaintext highlighter-rouge">iptables-nft</code>, which accepts the old syntax and writes nftables rules underneath. The syntax survives because so many scripts and so much documentation depend on it.</p>

<p><code class="language-plaintext highlighter-rouge">iptables</code> has a reputation for being arcane. The reputation is partly deserved: the syntax is terse, and the documentation assumes the reader already knows what chains, tables and targets are. The underlying model is logical once it is internalized, though, and the visibility it gives over network traffic is worth the learning curve.</p>

<p>This is a walkthrough of how to approach iptables, and the ruleset used here as a baseline on personal systems.</p>

<hr />

<h2 id="the-mental-model"><a class="anchor" href="#the-mental-model">The mental model</a></h2>

<p><code class="language-plaintext highlighter-rouge">iptables</code> filters packets in the kernel by passing them through a series of chains in specific tables. For most firewall purposes only the <code class="language-plaintext highlighter-rouge">filter</code> table matters, and within it three chains:</p>

<ul>
  <li>INPUT: traffic destined for the local machine</li>
  <li>OUTPUT: traffic originating from the local machine</li>
  <li>FORWARD: traffic passing through (router or gateway use)</li>
</ul>

<p>Within a chain, rules are checked from the top down, and the first rule whose match fits and whose target is final (<code class="language-plaintext highlighter-rouge">ACCEPT</code>, <code class="language-plaintext highlighter-rouge">DROP</code>, <code class="language-plaintext highlighter-rouge">REJECT</code>) decides the packet. Order is everything. A packet that matches no rule gets the chain’s default policy, and the two meaningful policies are <code class="language-plaintext highlighter-rouge">ACCEPT</code> and <code class="language-plaintext highlighter-rouge">DROP</code>.</p>

<p>A sane starting point: default DROP on INPUT, default ACCEPT on OUTPUT.</p>

<hr />

<h2 id="a-working-baseline"><a class="anchor" href="#a-working-baseline">A working baseline</a></h2>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># Flush existing rules</span>
iptables <span class="nt">-F</span>
iptables <span class="nt">-X</span>

<span class="c"># Default policies</span>
iptables <span class="nt">-P</span> INPUT DROP
iptables <span class="nt">-P</span> FORWARD DROP
iptables <span class="nt">-P</span> OUTPUT ACCEPT

<span class="c"># Allow established and related connections (return traffic)</span>
iptables <span class="nt">-A</span> INPUT <span class="nt">-m</span> conntrack <span class="nt">--ctstate</span> ESTABLISHED,RELATED <span class="nt">-j</span> ACCEPT

<span class="c"># Allow loopback</span>
iptables <span class="nt">-A</span> INPUT <span class="nt">-i</span> lo <span class="nt">-j</span> ACCEPT

<span class="c"># Allow SSH (adjust port if you've changed it)</span>
iptables <span class="nt">-A</span> INPUT <span class="nt">-p</span> tcp <span class="nt">--dport</span> 22 <span class="nt">-j</span> ACCEPT

<span class="c"># Allow HTTP and HTTPS if hosting anything</span>
iptables <span class="nt">-A</span> INPUT <span class="nt">-p</span> tcp <span class="nt">--dport</span> 80 <span class="nt">-j</span> ACCEPT
iptables <span class="nt">-A</span> INPUT <span class="nt">-p</span> tcp <span class="nt">--dport</span> 443 <span class="nt">-j</span> ACCEPT

<span class="c"># Allow ICMP (ping), optional but useful</span>
iptables <span class="nt">-A</span> INPUT <span class="nt">-p</span> icmp <span class="nt">-j</span> ACCEPT

<span class="c"># Drop everything else (covered by default policy, but explicit is clear)</span>
iptables <span class="nt">-A</span> INPUT <span class="nt">-j</span> DROP
</code></pre></div></div>

<p>The <code class="language-plaintext highlighter-rouge">ESTABLISHED,RELATED</code> rule is the one that makes default-deny livable. Without it, DROP on INPUT would block all return traffic, including the replies to connections the machine itself opened, which would break nearly everything. It is also why the rule comes first: most packets on a busy host belong to connections already established, and they are decided at the first rule checked.</p>

<blockquote class="prompt-warning">
  <p>Run this as a script, not line by line over SSH. Typed one command at a time, the session dies at <code class="language-plaintext highlighter-rouge">iptables -P INPUT DROP</code>, because the rule that would let its packets back in has not been added yet. The <code class="language-plaintext highlighter-rouge">iptables-apply</code> tool goes further: it loads a saved ruleset and rolls it back automatically unless the change is confirmed within a timeout.</p>
</blockquote>

<p>These rules cover IPv4 only. IPv6 has its own table, managed with <code class="language-plaintext highlighter-rouge">ip6tables</code>, and a host with an IPv6 address and no ip6tables rules is wide open on that side whatever the IPv4 rules say. The IPv6 version of the baseline needs one change beyond the command name: ICMPv6 must be allowed, because IPv6 uses it to find neighbours on the local network.</p>

<hr />

<h2 id="logging-before-dropping"><a class="anchor" href="#logging-before-dropping">Logging before dropping</a></h2>

<p>Before the final DROP, a LOG rule shows what is being blocked:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>iptables <span class="nt">-A</span> INPUT <span class="nt">-m</span> limit <span class="nt">--limit</span> 5/min <span class="nt">-j</span> LOG <span class="nt">--log-prefix</span> <span class="s2">"iptables-drop: "</span> <span class="nt">--log-level</span> 4
iptables <span class="nt">-A</span> INPUT <span class="nt">-j</span> DROP
</code></pre></div></div>

<p>These two lines replace the explicit DROP at the end of the baseline; they do not follow it. Appended after a rule that drops everything, the LOG rule would never see a packet. The <code class="language-plaintext highlighter-rouge">--limit</code> keeps a port scan from flooding the log. The output appears in <code class="language-plaintext highlighter-rouge">/var/log/kern.log</code>, or in <code class="language-plaintext highlighter-rouge">journalctl -k</code> on systems that keep kernel messages in the journal. Watching it for a while gives a clear picture of what is actually hitting the machine.</p>

<hr />

<h2 id="rate-limiting-ssh"><a class="anchor" href="#rate-limiting-ssh">Rate limiting SSH</a></h2>

<p>SSH brute force is a constant reality, even on non-standard ports. iptables can rate-limit connection attempts:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>iptables <span class="nt">-A</span> INPUT <span class="nt">-p</span> tcp <span class="nt">--dport</span> 22 <span class="nt">-m</span> state <span class="nt">--state</span> NEW <span class="nt">-m</span> recent <span class="nt">--set</span>
iptables <span class="nt">-A</span> INPUT <span class="nt">-p</span> tcp <span class="nt">--dport</span> 22 <span class="nt">-m</span> state <span class="nt">--state</span> NEW <span class="nt">-m</span> recent <span class="nt">--update</span> <span class="nt">--seconds</span> 60 <span class="nt">--hitcount</span> 4 <span class="nt">-j</span> DROP
</code></pre></div></div>

<p>This drops any source IP that makes more than 3 new SSH connection attempts within 60 seconds. Crude, but effective. Fail2Ban is more sophisticated, but this works in the kernel with no daemon required.</p>

<p>The order trap applies again. These two rules must sit above the rule that accepts port 22, because a new connection that has already been accepted never reaches them. In the baseline script, put them directly before the SSH line. (<code class="language-plaintext highlighter-rouge">-m state --state NEW</code> is the older spelling of <code class="language-plaintext highlighter-rouge">-m conntrack --ctstate NEW</code>; both work.)</p>

<hr />

<h2 id="persistence"><a class="anchor" href="#persistence">Persistence</a></h2>

<p><code class="language-plaintext highlighter-rouge">iptables</code> rules do not survive a reboot by default. To make them persistent:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># Debian/Ubuntu</span>
<span class="nb">sudo </span>apt <span class="nb">install </span>iptables-persistent
<span class="nb">sudo </span>netfilter-persistent save

<span class="c"># Fedora/RHEL, with the iptables-services package and firewalld stopped and disabled:</span>
<span class="nb">sudo </span>sh <span class="nt">-c</span> <span class="s1">'iptables-save &gt; /etc/sysconfig/iptables'</span>
<span class="nb">sudo </span>systemctl <span class="nb">enable </span>iptables
</code></pre></div></div>

<p>On Fedora and RHEL, firewalld is the default firewall and drives nftables directly, so saved iptables rules and firewalld should not both be in charge. The <code class="language-plaintext highlighter-rouge">sh -c</code> wrapper matters: in <code class="language-plaintext highlighter-rouge">sudo iptables-save &gt; file</code>, the redirection is done by the unprivileged shell before sudo runs, and it fails with “Permission denied.” The IPv6 rules are saved the same way, with <code class="language-plaintext highlighter-rouge">ip6tables-save</code> into <code class="language-plaintext highlighter-rouge">/etc/sysconfig/ip6tables</code>.</p>

<p>Alternatively, write the rules into a shell script and call it from a systemd unit at boot. That makes the ruleset self-documenting and easy to keep under version control.</p>

<hr />

<h2 id="security-relevance"><a class="anchor" href="#security-relevance">Security relevance</a></h2>

<p>In the CompTIA Security+ outline (SY0-701), network-layer filtering is a mitigation under Domain 2, Threats, Vulnerabilities, and Mitigations: a direct control against unauthorized access that reduces exposure to scanning and brute-force attempts. Firewall rules, access lists, ports and protocols appear by name under Domain 4, Security Operations. Understanding why rules are ordered as they are, and what a default policy means, informs better network architecture.</p>

<hr />

<h2 id="what-the-habits-are"><a class="anchor" href="#what-the-habits-are">What the habits are</a></h2>

<p>Writing a bad ruleset that blocks everything important is just as easy as writing a good one. The habits that prevent it are few. Start with an explicit default policy. Allow established connections before anything else. Remember that order decides, so a rule below a final ACCEPT or DROP for the same traffic is dead. Test changes carefully, above all on remote systems, and log what you drop.</p>

<p>Once the model clicks, iptables becomes one of the more satisfying tools to work with. The kernel does exactly what it was told, and every accepted or rejected packet can be traced to the line that decided it. Russell’s guides called themselves unreliable. The packet filter they described has been anything but.</p>

<p>Tools used: <code class="language-plaintext highlighter-rouge">iptables</code>, <code class="language-plaintext highlighter-rouge">iptables-save</code>, <code class="language-plaintext highlighter-rouge">iptables-restore</code>, <code class="language-plaintext highlighter-rouge">conntrack</code>, <code class="language-plaintext highlighter-rouge">netfilter-persistent</code>.</p>

<h2 id="sources"><a class="anchor" href="#sources">Sources</a></h2>

<ul>
  <li>Russell, Rusty. <em>Linux 2.4 Packet Filtering HOWTO</em>. Netfilter project, 2002.</li>
  <li>Netfilter project. iptables(8), iptables-extensions(8) and iptables-apply(8) manual pages.</li>
  <li>Red Hat. <em>Configuring firewalls and packet filters</em>, RHEL documentation.</li>
  <li>CompTIA. <em>Security+ (SY0-701) Exam Objectives</em>.</li>
</ul>]]></content><author><name>Securus</name></author><category term="Portfolio" /><category term="Linux" /><category term="iptables" /><category term="linux" /><category term="firewall" /><category term="networking" /><category term="security" /><category term="security-plus" /><summary type="html"><![CDATA[How iptables passes packets through tables and chains, a default-deny baseline built from scratch, and the ordering mistakes that make good rules do nothing.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://securus.pages.dev/assets/img/social-preview.png" /><media:content medium="image" url="https://securus.pages.dev/assets/img/social-preview.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Hardening SSH: the defaults worth changing</title><link href="https://securus.pages.dev/posts/hardening-ssh/" rel="alternate" type="text/html" title="Hardening SSH: the defaults worth changing" /><published>2025-12-10T00:00:00-05:00</published><updated>2025-12-10T00:00:00-05:00</updated><id>https://securus.pages.dev/posts/hardening-ssh</id><content type="html" xml:base="https://securus.pages.dev/posts/hardening-ssh/"><![CDATA[<h2 id="where-ssh-came-from"><a class="anchor" href="#where-ssh-came-from">Where SSH came from</a></h2>

<p>Early in 1995 Tatu Ylönen, a researcher at the Helsinki University of Technology, learned that a password sniffer had been running on the university’s network. Logins then travelled by Telnet and rlogin, in the clear. Ylönen wrote a replacement that encrypted the whole session, released it that July as SSH, and by the end of the year it had some 20,000 users in fifty countries. OpenSSH followed from the OpenBSD project in 1999.</p>

<p>Thirty years on, SSH is the primary administrative interface for most Linux systems, which makes it one of the more consequential services to get right. The defaults are functional but not particularly strict, and a few deliberate changes, none of them much effort, narrow the attack surface considerably. What follows are the steps applied to a set of personal systems, with the reasoning for each and the places where the obvious reading of a setting is wrong.</p>

<hr />

<h2 id="disable-password-authentication"><a class="anchor" href="#disable-password-authentication">Disable password authentication</a></h2>

<p>This is the most important one. With password authentication enabled, the server is permanently exposed to brute-force attacks. Fail2Ban helps, but the better fix is to accept no passwords at all.</p>

<p>In <code class="language-plaintext highlighter-rouge">/etc/ssh/sshd_config</code>:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>PasswordAuthentication no
ChallengeResponseAuthentication no
</code></pre></div></div>

<p>The second line closes the other route by which a password can reach the server, keyboard-interactive authentication. Since OpenSSH 8.7 its proper name is <code class="language-plaintext highlighter-rouge">KbdInteractiveAuthentication</code>; <code class="language-plaintext highlighter-rouge">ChallengeResponseAuthentication</code> still works as a deprecated alias.</p>

<blockquote class="prompt-warning">
  <p>Before applying this, make absolutely sure key-based authentication works. Test it from a second terminal before closing the first. Losing the only access path to a remote server is an avoidable lesson.</p>
</blockquote>

<hr />

<h2 id="change-the-default-port"><a class="anchor" href="#change-the-default-port">Change the default port</a></h2>

<p>Port 22 is scanned constantly. Moving SSH to a non-standard port (anything above 1024, something memorable and not commonly scanned) cuts the noise in the logs dramatically and takes the server out of most automated scan-and-attack pipelines.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Port 2222
</code></pre></div></div>

<p>This is security through obscurity and no substitute for real hardening. Combined with the rest, it makes the server effectively invisible to most opportunistic scanning, and the logs go quiet. A targeted attacker will find the port with one full scan.</p>

<p>Update the firewall rules to match, and put the port in the client config (<code class="language-plaintext highlighter-rouge">~/.ssh/config</code>) to avoid typing it every time. Two distributions need one more step. On Fedora and RHEL, SELinux has to be told the new port belongs to SSH, with <code class="language-plaintext highlighter-rouge">sudo semanage port -a -t ssh_port_t -p tcp 2222</code>. On Ubuntu 24.04, sshd is started by <code class="language-plaintext highlighter-rouge">ssh.socket</code>, which a generator configures from <code class="language-plaintext highlighter-rouge">sshd_config</code>, so a port change takes effect only after <code class="language-plaintext highlighter-rouge">sudo systemctl daemon-reload</code> and a restart of <code class="language-plaintext highlighter-rouge">ssh.socket</code>.</p>

<hr />

<h2 id="restrict-root-login"><a class="anchor" href="#restrict-root-login">Restrict root login</a></h2>

<p>Direct root login should be disabled. For elevated access, log in as a normal user and escalate with <code class="language-plaintext highlighter-rouge">sudo</code>, which also leaves a record of who did what.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>PermitRootLogin no
</code></pre></div></div>

<p>If some automation needs direct root access (some backup agents, for instance), <code class="language-plaintext highlighter-rouge">PermitRootLogin prohibit-password</code> is the compromise: it allows key-based root login and blocks password attempts. It has been OpenSSH’s own default since version 7.0, so <code class="language-plaintext highlighter-rouge">no</code> is the stricter choice.</p>

<hr />

<h2 id="limit-which-users-can-connect"><a class="anchor" href="#limit-which-users-can-connect">Limit which users can connect</a></h2>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>AllowUsers yourusername
</code></pre></div></div>

<p>This creates an explicit allowlist. Even if another account exists on the system and has SSH access configured, it cannot connect unless it appears here. It is the principle of least privilege, applied at the login.</p>

<hr />

<h2 id="disconnect-dead-sessions"><a class="anchor" href="#disconnect-dead-sessions">Disconnect dead sessions</a></h2>

<p>Two settings make sshd notice when a client has gone away:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>ClientAliveInterval 300
ClientAliveCountMax 2
</code></pre></div></div>

<p>After 300 seconds with nothing from the client, sshd sends a keepalive probe through the encrypted channel, and after 2 unanswered probes it disconnects. A client that has vanished, because a laptop went to sleep or a network dropped, is cut off after roughly 10 minutes, and its session stops holding resources on the server.</p>

<p>These settings do not end idle sessions, though they are often described as if they did. A connected client answers every probe automatically, whether or not anyone is at the keyboard, so a terminal left open on a desk stays open indefinitely. For a true idle timeout there are two tools. OpenSSH 9.2 added <code class="language-plaintext highlighter-rouge">ChannelTimeout</code>, which closes a channel after a period with no traffic:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>ChannelTimeout session=10m
</code></pre></div></div>

<p>On older servers, setting the shell variable <code class="language-plaintext highlighter-rouge">TMOUT</code> (for example <code class="language-plaintext highlighter-rouge">TMOUT=600</code>, made read-only in a file under <code class="language-plaintext highlighter-rouge">/etc/profile.d/</code>) makes bash log out after ten minutes at an idle prompt.</p>

<hr />

<h2 id="disable-unused-features"><a class="anchor" href="#disable-unused-features">Disable unused features</a></h2>

<p>Several SSH features serve narrow purposes and widen the attack surface for everyone else:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>X11Forwarding no
AllowTcpForwarding no
AllowAgentForwarding no
</code></pre></div></div>

<p>Upstream OpenSSH already defaults X11 forwarding to off, but several distributions, Debian and Ubuntu among them, ship a configuration that turns it on. TCP and agent forwarding are on by default upstream. If X11 forwarding or SSH tunnelling is in actual use, keep what is needed; otherwise, disable it. Features that are off cannot be exploited.</p>

<p>The man page adds a caution worth keeping in mind: “disabling TCP forwarding does not improve security unless users are also denied shell access,” because a user with a shell can always run a forwarder of their own. The setting removes a convenience; a determined user keeps the capability.</p>

<hr />

<h2 id="use-stronger-key-types"><a class="anchor" href="#use-stronger-key-types">Use stronger key types</a></h2>

<p>When generating new key pairs, prefer Ed25519 over the older RSA:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>ssh-keygen <span class="nt">-t</span> ed25519 <span class="nt">-C</span> <span class="s2">"your-label"</span>
</code></pre></div></div>

<p>Ed25519 keys are shorter and faster, and they rest on more modern elliptic-curve cryptography, the scheme Daniel J. Bernstein and his colleagues published in 2011. OpenSSH added them in version 6.5, in 2014, and since 9.5 <code class="language-plaintext highlighter-rouge">ssh-keygen</code> generates them by default. Old RSA-2048 keys still lying around are worth rotating while you are at it.</p>

<hr />

<h2 id="apply-the-changes"><a class="anchor" href="#apply-the-changes">Apply the changes</a></h2>

<p>After editing <code class="language-plaintext highlighter-rouge">/etc/ssh/sshd_config</code>, validate the config before restarting:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">sudo </span>sshd <span class="nt">-t</span>
<span class="nb">sudo </span>systemctl restart sshd
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">sshd -t</code> exits silently if the config is valid and prints the error if not. Restarting with a broken config file means the daemon does not come back, and every new login fails until someone reaches the console. Sessions already open survive the restart, which is why one should stay open until a fresh login has been tested.</p>

<p>There is one trap <code class="language-plaintext highlighter-rouge">sshd -t</code> does not catch. For each keyword, sshd uses the first value it reads, not the last. Debian and Ubuntu begin <code class="language-plaintext highlighter-rouge">sshd_config</code> with <code class="language-plaintext highlighter-rouge">Include /etc/ssh/sshd_config.d/*.conf</code>, and a drop-in there, such as one written by cloud-init, can set <code class="language-plaintext highlighter-rouge">PasswordAuthentication yes</code> before the main file is ever read. The way to know what sshd will actually do is to ask it for its effective configuration:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">sudo </span>sshd <span class="nt">-T</span> | <span class="nb">grep</span> <span class="nt">-i</span> passwordauthentication
</code></pre></div></div>

<hr />

<h2 id="security-relevance"><a class="anchor" href="#security-relevance">Security relevance</a></h2>

<p>In the CompTIA Security+ outline (SY0-701), this work sits in Domain 2, Threats, Vulnerabilities, and Mitigations: reducing the attack surface of the primary administrative interface directly limits the paths available for unauthorized access. It also sits in Domain 4, Security Operations, whose first objective covers hardening targets. Configuration hardening is a foundational control in every major security framework.</p>

<h2 id="what-it-adds-up-to"><a class="anchor" href="#what-it-adds-up-to">What it adds up to</a></h2>

<p>None of these steps is novel or complicated, but together they are a clear improvement over the defaults. A system with password authentication off, a non-standard port, no root login, an explicit list of users and dead sessions cleaned up is substantially harder to compromise than one running SSH out of the box.</p>

<p>The cost is close to nothing, and the reason to pay it is the same as in 1995. Ylönen’s university was not attacked through some exotic flaw. Someone listened, and the passwords were there.</p>

<h2 id="sources"><a class="anchor" href="#sources">Sources</a></h2>

<ul>
  <li>Ylönen, Tatu. “SSH: Secure Login Connections over the Internet.” <em>Proceedings of the 6th USENIX Security Symposium</em>, 1996.</li>
  <li>OpenBSD. sshd_config(5) and sshd(8) manual pages.</li>
  <li>OpenSSH release notes for versions 7.0, 8.7, 9.2 and 9.5.</li>
  <li>Bernstein, Daniel J., Niels Duif, Tanja Lange, Peter Schwabe and Bo-Yin Yang. “High-speed high-security signatures.” CHES 2011.</li>
  <li>CompTIA. <em>Security+ (SY0-701) Exam Objectives</em>.</li>
</ul>]]></content><author><name>Securus</name></author><category term="Portfolio" /><category term="Linux" /><category term="ssh" /><category term="linux" /><category term="security" /><category term="hardening" /><category term="homelab" /><category term="security-plus" /><summary type="html"><![CDATA[The sshd settings that most reduce the attack surface of a Linux host's front door, what each one actually does, and how to apply them without locking yourself out.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://securus.pages.dev/assets/img/social-preview.png" /><media:content medium="image" url="https://securus.pages.dev/assets/img/social-preview.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Passive OSINT: mapping an attack surface before touching anything</title><link href="https://securus.pages.dev/posts/osint-attack-surface/" rel="alternate" type="text/html" title="Passive OSINT: mapping an attack surface before touching anything" /><published>2025-10-03T00:00:00-04:00</published><updated>2025-10-03T00:00:00-04:00</updated><id>https://securus.pages.dev/posts/osint-attack-surface</id><content type="html" xml:base="https://securus.pages.dev/posts/osint-attack-surface/"><![CDATA[<p>In the summer of 2011 someone broke into DigiNotar, a Dutch certificate authority, and issued themselves certificates for hundreds of domains, <code class="language-plaintext highlighter-rouge">*.google.com</code> among them. For weeks that one was used to intercept the Gmail traffic of users in Iran, and browsers trusted it, because a trusted authority had signed it. DigiNotar was bankrupt by September. The answer Google’s Ben Laurie and Adam Langley proposed was Certificate Transparency: every certificate a public authority issues would be written into open, append-only logs that anyone could search, so that a rogue certificate could not stay secret. It became RFC 6962 in 2013, and since 2018 Chrome has refused new certificates that are not logged.</p>

<p>It worked. It also built, as a side effect, a public directory of nearly every hostname any organization has ever put a certificate on.</p>

<p>That is the territory of passive OSINT, open source intelligence gathered without touching a target’s systems. There is a meaningful gap between what an organization thinks is exposed and what is visible from the internet, and passive OSINT lives in that gap. It is legal, it is quiet, and in the right hands it paints a surprisingly complete picture.</p>

<p>It is worth understanding from both sides. A defender who knows what an adversary can learn without triggering a single alert knows where to harden first. For anyone doing reconnaissance, passive OSINT is where every serious engagement starts.</p>

<hr />

<h2 id="what-counts-as-passive"><a class="anchor" href="#what-counts-as-passive">What counts as passive</a></h2>

<p>The distinction matters. Active reconnaissance sends packets to a target: scanning ports, probing services, triggering server responses. It leaves traces, and in most contexts it requires explicit authorization.</p>

<p>Passive reconnaissance gathers what is already public. It is reading, not touching. DNS records, certificate transparency logs, WHOIS data, archived web pages, search engine results, social media and job postings can all be read without any contact with the target’s infrastructure.</p>

<p>The line blurs in a few places. Querying a third-party service that once scanned the target, as Shodan does, is passive for the person asking but was not passive for the service. The core principle holds: if it is already public, reading it is passive.</p>

<hr />

<h2 id="dns-and-certificate-intelligence"><a class="anchor" href="#dns-and-certificate-intelligence">DNS and certificate intelligence</a></h2>

<p>DNS is remarkably talkative for something most people treat as invisible infrastructure.</p>

<p>Certificate transparency logs are public by design. Tools like <a href="https://crt.sh">crt.sh</a> enumerate subdomains by searching for every certificate issued to a domain. Internal staging environments, developer portals and forgotten legacy services all show up there if they ever had a publicly trusted certificate. A wildcard certificate hides the individual names, which is one reason some organizations prefer them.</p>

<p>WHOIS records reveal registration dates and registrars, and sometimes contact information. Less of it than before: since the EU’s General Data Protection Regulation took effect in May 2018, most registrars redact personal contact details, and since January 2025 ICANN has treated RDAP, the Registration Data Access Protocol, as the definitive source for generic top-level domains. Older registrations are still interesting, because they can point to infrastructure that predates an organization’s current security posture.</p>

<p>DNS history services (SecurityTrails, DNSDumpster and similar) keep historical records: IP addresses once associated with a domain, MX records that have since changed, moves from one nameserver to another. That history can reveal relationships between pieces of infrastructure that the current records no longer show.</p>

<hr />

<h2 id="the-job-posting-problem"><a class="anchor" href="#the-job-posting-problem">The job posting problem</a></h2>

<p>Job postings are an underrated source. A posting for a “Senior Engineer, AWS infrastructure (EKS, RDS, Terraform)” names the cloud provider, the orchestration layer, the database and the infrastructure-as-code tooling. A posting for a SOC analyst that requires “experience with CrowdStrike and Splunk” names the endpoint detection and the SIEM.</p>

<p>Organizations advertise their technology stack to the world this way, and most never think about it as a security matter. Defenders should read their own job listings through this lens from time to time.</p>

<hr />

<h2 id="what-this-looked-like-in-practice"><a class="anchor" href="#what-this-looked-like-in-practice">What this looked like in practice</a></h2>

<p>Run against a small personal footprint, the exercise turned up four things:</p>

<ul>
  <li>crt.sh returned several subdomains that had been set up and half forgotten, including an old dev instance</li>
  <li>Shodan (passive, querying data it had already indexed) showed the external IP with ports 22 and 443 open, which was correct</li>
  <li>DNS history through SecurityTrails revealed a previous hosting provider, and the window of the move between providers was visible</li>
  <li>GitHub, searched for the organization name, turned up a public repository from two years before with a hard-coded staging domain in a config file, since removed but still indexed</li>
</ul>

<p>None of it required touching anything. All of it would be useful to someone planning a targeted attack. The last item is the one to dwell on: deleting a file from a repository does not delete it from history, from forks or from the indexes that copied it.</p>

<hr />

<h2 id="the-defenders-takeaway"><a class="anchor" href="#the-defenders-takeaway">The defender’s takeaway</a></h2>

<p>Passive OSINT is the starting point for any serious threat intelligence or red team exercise, and what it surfaces is available to anyone. Running the same exercise against one’s own footprint is among the most useful things a security-minded individual or small team can do in an afternoon.</p>

<p>The questions are simple. What do the job postings reveal? What is in the certificate logs? What does the DNS history show, and is there anything in public repositories that should not be there?</p>

<p>The answers are usually more interesting than expected. Certificate Transparency was built so that nobody could quietly hold a certificate for someone else’s name. The same openness means nobody can quietly hold one for their own.</p>

<hr />

<p>Tools used (passive): crt.sh, DNSDumpster, SecurityTrails (free tier), Shodan (previously indexed data), GitHub search, Google dorks.</p>

<h2 id="sources"><a class="anchor" href="#sources">Sources</a></h2>

<ul>
  <li>Laurie, B., A. Langley and E. Kasper. RFC 6962, “Certificate Transparency.” June 2013.</li>
  <li>Fox-IT. <em>DigiNotar Certificate Authority Breach: “Operation Black Tulip.”</em> Interim report for the Dutch government, September 2011.</li>
  <li>ICANN. Announcements on the transition from WHOIS to RDAP for generic top-level domains, 2025.</li>
  <li>Long, Johnny. <em>Google Hacking for Penetration Testers</em>. Syngress, 2005.</li>
</ul>]]></content><author><name>Securus</name></author><category term="Articles" /><category term="Security" /><category term="OSINT" /><category term="recon" /><category term="threat-intel" /><category term="security" /><category term="portfolio" /><category term="networking" /><summary type="html"><![CDATA[How passive reconnaissance with open source intelligence reveals more than most people expect without sending a single packet to the target, and what a defender should do with that.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://securus.pages.dev/assets/img/social-preview.png" /><media:content medium="image" url="https://securus.pages.dev/assets/img/social-preview.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Watching the wire with tcpdump</title><link href="https://securus.pages.dev/posts/tcpdump-traffic-analysis/" rel="alternate" type="text/html" title="Watching the wire with tcpdump" /><published>2025-08-14T00:00:00-04:00</published><updated>2025-08-14T00:00:00-04:00</updated><id>https://securus.pages.dev/posts/tcpdump-traffic-analysis</id><content type="html" xml:base="https://securus.pages.dev/posts/tcpdump-traffic-analysis/"><![CDATA[<h2 id="where-it-came-from"><a class="anchor" href="#where-it-came-from">Where it came from</a></h2>

<p>In October 1986 the link between the Lawrence Berkeley Laboratory and the University of California at Berkeley, sites some 400 yards apart, slowed from 32 kilobits a second to 40 bits a second. Van Jacobson, at LBL, went looking for the cause, and in 1988 he and Mike Karels published it: TCP had no way to back off when the network filled up. Their fixes are still in every TCP stack. Finding the answer meant watching packets, and the tool for that came out of the same LBL group in 1988. Its manual page credits Jacobson, Craig Leres and Steven McCanne. They called it tcpdump. In 1993 McCanne and Jacobson published the BSD Packet Filter, the in-kernel machine that the filter syntax still compiles down to.</p>

<p>This exercise used <code class="language-plaintext highlighter-rouge">tcpdump</code> to capture live traffic on a local interface and see what was actually moving across the wire. It is easy to assume a network is quiet until someone looks. The output looks dense at first, but once each field makes sense the picture is remarkably detailed.</p>

<hr />

<h2 id="capturing-traffic"><a class="anchor" href="#capturing-traffic">Capturing traffic</a></h2>

<p>To start a basic capture on the primary interface:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">sudo </span>tcpdump <span class="nt">-i</span> eth0
</code></pre></div></div>

<p>The <code class="language-plaintext highlighter-rouge">-i</code> flag selects the interface. Replace <code class="language-plaintext highlighter-rouge">eth0</code> with whatever <code class="language-plaintext highlighter-rouge">ip a</code> shows for the active interface (<code class="language-plaintext highlighter-rouge">ens3</code>, <code class="language-plaintext highlighter-rouge">wlan0</code>, and so on). Without filters this floods the terminal within seconds, so in practice a capture is almost always narrowed down.</p>

<p>To capture to a file for later analysis in Wireshark or <code class="language-plaintext highlighter-rouge">tshark</code>:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">sudo </span>tcpdump <span class="nt">-i</span> eth0 <span class="nt">-w</span> capture.pcap
</code></pre></div></div>

<p>Capturing needs root, or the <code class="language-plaintext highlighter-rouge">CAP_NET_RAW</code> and <code class="language-plaintext highlighter-rouge">CAP_NET_ADMIN</code> capabilities, because it reads raw frames from the interface rather than data handed up through a socket. That is also why a capture file deserves the care of any other sensitive data: whatever crossed the wire unencrypted is now sitting in it.</p>

<hr />

<h2 id="filtering"><a class="anchor" href="#filtering">Filtering</a></h2>

<p>Filters are where <code class="language-plaintext highlighter-rouge">tcpdump</code> becomes useful. The Berkeley Packet Filter (BPF) syntax can be very specific:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># Only HTTP and HTTPS traffic</span>
<span class="nb">sudo </span>tcpdump <span class="nt">-i</span> eth0 port 80 or port 443

<span class="c"># Traffic to or from a specific host</span>
<span class="nb">sudo </span>tcpdump <span class="nt">-i</span> eth0 host 192.168.1.1

<span class="c"># Only TCP SYN packets (connection attempts)</span>
<span class="nb">sudo </span>tcpdump <span class="nt">-i</span> eth0 <span class="s1">'tcp[tcpflags] == tcp-syn'</span>

<span class="c"># DNS queries only</span>
<span class="nb">sudo </span>tcpdump <span class="nt">-i</span> eth0 udp port 53
</code></pre></div></div>

<p>Combining filters with <code class="language-plaintext highlighter-rouge">and</code>, <code class="language-plaintext highlighter-rouge">or</code> and <code class="language-plaintext highlighter-rouge">not</code> slices traffic precisely without capturing everything and sorting through it afterwards. The SYN filter shows what BPF can do: <code class="language-plaintext highlighter-rouge">tcp[tcpflags]</code> reads the flags byte straight out of the TCP header, and <code class="language-plaintext highlighter-rouge">== tcp-syn</code> keeps only packets where SYN is the one flag set, so the SYN-ACK replies are left out. The quotes keep the shell from interpreting the brackets.</p>

<p>One more flag earns a place in nearly every command: <code class="language-plaintext highlighter-rouge">-n</code>. By default tcpdump turns addresses into hostnames and port numbers into service names, and to do that it sends reverse DNS lookups of its own, which then appear in the capture. <code class="language-plaintext highlighter-rouge">-n</code> turns that off:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">sudo </span>tcpdump <span class="nt">-n</span> <span class="nt">-i</span> eth0 udp port 53
</code></pre></div></div>

<hr />

<h2 id="reading-the-output"><a class="anchor" href="#reading-the-output">Reading the output</a></h2>

<p>A DNS query, captured with <code class="language-plaintext highlighter-rouge">-n</code>, looks like this:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>12:34:56.789012 IP 192.168.1.42.52318 &gt; 8.8.8.8.53: 41325+ A? example.com. (29)
</code></pre></div></div>

<p>Breaking it down:</p>
<ul>
  <li>timestamp: microsecond precision</li>
  <li>network protocol: <code class="language-plaintext highlighter-rouge">IP</code> for IPv4, <code class="language-plaintext highlighter-rouge">IP6</code> for IPv6, <code class="language-plaintext highlighter-rouge">ARP</code> for address resolution</li>
  <li>source.port &gt; destination.port: the direction of the packet; tcpdump joins the port to the address with a dot</li>
  <li>protocol details: here tcpdump has decoded DNS, so it prints the query ID (<code class="language-plaintext highlighter-rouge">41325</code>), a <code class="language-plaintext highlighter-rouge">+</code> for “recursion desired”, and the question, an A record for <code class="language-plaintext highlighter-rouge">example.com</code></li>
  <li>length: for DNS, the size of the DNS message in bytes, in brackets at the end</li>
</ul>

<p>Without <code class="language-plaintext highlighter-rouge">-n</code>, the same line would show <code class="language-plaintext highlighter-rouge">dns.google.domain</code> in place of <code class="language-plaintext highlighter-rouge">8.8.8.8.53</code>. For UDP traffic tcpdump has no decoder for, the details shrink to the generic <code class="language-plaintext highlighter-rouge">UDP, length 33</code>, where the number is the UDP payload in bytes.</p>

<p>For TCP, you’ll see flags like <code class="language-plaintext highlighter-rouge">[S]</code> (SYN), <code class="language-plaintext highlighter-rouge">[S.]</code> (SYN-ACK), <code class="language-plaintext highlighter-rouge">[.]</code> (ACK), <code class="language-plaintext highlighter-rouge">[P.]</code> (PSH-ACK, data), <code class="language-plaintext highlighter-rouge">[F.]</code> (FIN) and <code class="language-plaintext highlighter-rouge">[R]</code> (RST). Watching a full three-way handshake followed by data transfer followed by FIN shows how TCP actually behaves in the wild, and it is the same exchange Jacobson was trying to see in 1986.</p>

<hr />

<h2 id="security-relevance"><a class="anchor" href="#security-relevance">Security relevance</a></h2>

<p>Mapped to the CompTIA Security+ exam outline (SY0-701), the work touches three domains.</p>

<p>Domain 2, Threats, Vulnerabilities, and Mitigations: identifying unusual traffic patterns, unexpected protocols, or connections to suspicious destinations.</p>

<p>Domain 3, Security Architecture: understanding how protocols behave at the packet level informs better firewall rules and network segmentation.</p>

<p>Domain 4, Security Operations: <code class="language-plaintext highlighter-rouge">tcpdump</code> is a staple of incident response. When something goes wrong, a packet capture is often the first thing a responder reaches for.</p>

<hr />

<h2 id="the-habit"><a class="anchor" href="#the-habit">The habit</a></h2>

<p><code class="language-plaintext highlighter-rouge">tcpdump</code> has low overhead, ships on almost every Unix-like system, and needs nothing but a terminal and the right permissions. There is no substitute for watching traffic. Knowing how TCP works in theory is useful; watching a handshake, a retransmission and a reset in real time is something else.</p>

<p>With Wireshark for visual analysis or <code class="language-plaintext highlighter-rouge">tshark</code> for scripting, it makes a capable packet-analysis workflow that costs nothing and installs almost nothing. It serves for baselining traffic, spotting anomalies, debugging protocols and incident response on any Linux or BSD system.</p>

<p>Jacobson found the cause of an eight-hundredfold slowdown by looking at packets. The tool that came out of that looking is already installed.</p>

<h2 id="sources"><a class="anchor" href="#sources">Sources</a></h2>

<ul>
  <li>Jacobson, Van, and Michael J. Karels. “Congestion Avoidance and Control.” <em>Proceedings of SIGCOMM ‘88</em>, 1988.</li>
  <li>McCanne, Steven, and Van Jacobson. “The BSD Packet Filter: A New Architecture for User-level Packet Capture.” <em>Proceedings of the USENIX Winter 1993 Conference</em>, 1993.</li>
  <li>The Tcpdump Group. tcpdump(1) and pcap-filter(7) manual pages.</li>
  <li>CompTIA. <em>Security+ (SY0-701) Exam Objectives</em>.</li>
</ul>]]></content><author><name>Securus</name></author><category term="Portfolio" /><category term="Linux" /><category term="tcpdump" /><category term="networking" /><category term="packets" /><category term="traffic-analysis" /><category term="security" /><category term="linux" /><summary type="html"><![CDATA[Using tcpdump to capture, filter and read live network traffic from the command line, and where the tool and its filter language came from.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://securus.pages.dev/assets/img/social-preview.png" /><media:content medium="image" url="https://securus.pages.dev/assets/img/social-preview.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Rootless, immutable and open: rethinking the modern stack</title><link href="https://securus.pages.dev/posts/Modern-Linux/" rel="alternate" type="text/html" title="Rootless, immutable and open: rethinking the modern stack" /><published>2025-07-20T00:00:00-04:00</published><updated>2025-07-20T00:00:00-04:00</updated><id>https://securus.pages.dev/posts/Modern-Linux</id><content type="html" xml:base="https://securus.pages.dev/posts/Modern-Linux/"><![CDATA[<p>On 29 March 2024 Andres Freund, a Microsoft engineer who works on PostgreSQL, posted to the oss-security mailing list that the xz compression library had been backdoored. He had noticed SSH logins on a Debian test machine taking about half a second longer and using more CPU than they should, and he followed the delay down into versions 5.6.0 and 5.6.1 of liblzma. The code had been put there by a maintainer who had spent more than two years earning the project’s trust. It had reached Debian’s testing branch and Fedora’s development releases. It had not yet reached the stable releases most servers run, and it was caught by one person’s irritation at a slow login.</p>

<p>The episode sits at the meeting point of three changes in how serious infrastructure is built. None of them gets keynotes. They happen in distribution decisions, container defaults and the wording of compliance requirements: containers that do not need root, operating systems that cannot be modified by accident, and a software supply chain where most of the code was written by someone the user has never heard of.</p>

<p>No single part of this is new. What is new is how the combination changes the way a competent administrator works, and the security model it produces is materially different from the one most people learned.</p>

<p><a class="img-link" href="/assets/img/tp_quote.webp"><img src="/assets/img/tp_quote.webp" alt="Envisioning The Future" width="1600" height="900" loading="lazy" decoding="async"></a>
<em>“The empires of the future are the empires of the mind”: Churchill at Harvard in 1943, on an IBM ThinkPad wallpaper.</em></p>

<h2 id="going-rootless"><a class="anchor" href="#going-rootless">Going rootless</a></h2>

<p>Root on a Unix system has had unlimited authority since the beginning: user ID 0 bypasses every permission check the kernel makes. For decades that was treated as a fact of life. The admin has root, the daemon has root, the container runtime has root, and the security posture is whatever can be built on top of that. When Docker arrived in 2013, its daemon ran as root, and anyone who could talk to it could, in effect, become root on the host.</p>

<p>Rootless containers break the pattern by running the container runtime inside a user namespace, so the privileges available to anything inside the container are the privileges of an ordinary user on the host. Linux completed unprivileged user namespaces in version 3.8, in 2013. Tools like Podman and Buildah run as normal users by default, and no central daemon sits in the background with elevated privileges. A rootless container cannot bind a port below 1024 unless the administrator lowers the <code class="language-plaintext highlighter-rouge">net.ipv4.ip_unprivileged_port_start</code> sysctl, and even then the container does not become root on the host.</p>

<p>The mechanics come in four parts.</p>

<p>User namespaces do the central work. The kernel maps an unprivileged host UID to a “fake” root inside the container. The container thinks it is root; the host disagrees. The container cannot read or write files belonging to other users, cannot load kernel modules and cannot touch firmware.</p>

<p>Networking runs in user space. <code class="language-plaintext highlighter-rouge">slirp4netns</code> and <code class="language-plaintext highlighter-rouge">bypass4netns</code> give containers networking without requiring <code class="language-plaintext highlighter-rouge">CAP_NET_RAW</code> or any other elevated capability on the host, and since Podman 5.0 the default has been <code class="language-plaintext highlighter-rouge">pasta</code>, from the passt project. The performance cost used to be significant. Recent work has reduced it to the point where most workloads do not notice.</p>

<p>There is no daemon. Podman starts a container by forking a process, so there is no always-on service to compromise, and <code class="language-plaintext highlighter-rouge">systemd</code> can supervise containers directly through Quadlet units. Resource accounting works the way it does for any other systemd service.</p>

<p>It scales well past the desktop. HPC environments use rootless containers in shared multi-user clusters, GPU access included. Singularity and Apptainer extend the model to multi-node setups, and Usernetes runs Kubernetes itself rootless.</p>

<p>The result is a model where the blast radius of a container compromise is bounded by the privileges of the user that started it. That is a far smaller target than “the host system.”</p>

<h2 id="immutable-systems"><a class="anchor" href="#immutable-systems">Immutable systems</a></h2>

<p>The next layer is an immutable host OS. The base system is read-only, and updates are applied as atomic snapshots instead of in-place modifications. Fedora Silverblue, openSUSE MicroOS, Ubuntu Core, NixOS and Vanilla OS each do this slightly differently. NixOS goes back furthest, to Eelco Dolstra’s 2006 doctoral thesis at Utrecht on a purely functional model of software deployment.</p>

<p>The base is read-only. The OS is delivered as a single image, usually built with OSTree or something similar. Day-to-day changes (new packages, configs) happen in containers or overlays, and the base never changes outside an update transaction. Silverblue’s base is an OSTree snapshot; user apps come through Flatpak, and development tools live in <code class="language-plaintext highlighter-rouge">toolbox</code> containers.</p>

<p>Updates are atomic and can be rolled back. An update downloads and stages a new snapshot, and on reboot the system boots into it. If something fails, a reboot returns to the previous one. There is no half-applied state and no “the upgrade failed and now <code class="language-plaintext highlighter-rouge">apt</code> is stuck” situation. NixOS takes this further: the whole system is defined in a configuration file, and rebuilding produces a new generation that is either complete and bootable or not adopted at all.</p>

<p>Configuration is declarative. NixOS and Ubuntu Core let you describe the system as code: packages, services, users, kernel options, boot devices. Any change is intentional, and the configuration itself can be versioned. You can branch an operating system the way you branch code.</p>

<p>Apps live in containers. Immutable distributions lean heavily on container-style packaging. Silverblue uses Flatpak for desktop applications, Vanilla OS uses Apx, which installs each app inside its own container, and Ubuntu Core uses Snaps. The pattern is consistent: keep the base image clean and put everything else in isolated, versioned packages.</p>

<p>In any environment with more than a handful of machines, the advantage is configuration drift, or rather its absence. Rolling out a config change is a snapshot promotion, not a patch applied host by host. Failed updates revert in one reboot. Auditors get a single source of truth for what is actually running.</p>

<p>The trade-off is that administrators have to adopt container-based workflows instead of installing libraries directly on the host. For most people that is a net improvement once the habits are built. For the rest, it is a fight. Either way, regulation is pushing in this direction: the EU Cyber Resilience Act, the US executive order on improving the nation’s cybersecurity (Executive Order 14028 of May 2021), and sector-specific compliance rules.</p>

<h2 id="the-open-source-illusion"><a class="anchor" href="#the-open-source-illusion">The open source illusion</a></h2>

<p><a class="img-link" href="/assets/img/open-source.webp"><img src="/assets/img/open-source.webp" alt="open source vs proprietary" width="1024" height="1024" loading="lazy" decoding="async"></a>
<em>Open and proprietary software, as they are usually contrasted.</em></p>

<p>Open source software is now the substrate of nearly everything. Black Duck’s 2025 Open Source Security and Risk Analysis, which covers the codebases it audited during 2024, found open source components in 97% of them, and most enterprises in its survey had increased their use of open source year over year.</p>

<p>Transparency is real, and it matters. It is still not the same thing as safety, and a few problems compound.</p>

<p>Maintenance lags. An open codebase can be audited, but only if someone actually does it. Most open source in production is maintained by a small number of contributors, sometimes one person. The Black Duck audit found outdated components in 91% of codebases, and components more than ten versions behind upstream in 90%. Finding the code is easy; keeping it patched is the actual work.</p>

<p>The vulnerability surface is wide. 86% of audited applications had at least one known open source vulnerability, and 81% had at least one high or critical-risk bug. Most of those bugs sit in old versions of common libraries, jQuery the perennial example, that nobody ever upgraded, and few in anything obscure. Vulnerability scanning and SBOM generation are slowly becoming mandatory in regulated industries, and about a quarter of organizations now produce SBOMs for compliance reasons.</p>

<p>Licensing and provenance are uncertain. 56% of audited codebases had license conflicts. Beyond licensing there is the question of whether anyone knows who wrote the code and whether they followed reasonable security practices. xz made this concrete: a maintainer relationship cultivated patiently over years, then used to insert a backdoor that nearly shipped in major distributions. That story did not end as badly as it could have, but nothing about the method prevents its repetition.</p>

<p>Open source is still the right answer in most cases. Vendor lock-in is real, the ability to audit and patch matters, and a healthy upstream community is worth a lot. What has to go is the assumption that “open” by itself produces “secure.” It produces “auditable,” which is a precondition. The audit still has to happen, and the patches still have to land.</p>

<h2 id="why-it-matters"><a class="anchor" href="#why-it-matters">Why it matters</a></h2>

<p>The trends are converging in production. The CNCF’s annual survey for 2024, published in April 2025, put cloud-native adoption at 89% of surveyed organizations, with 91% running containers in production. Kubernetes was in use, in pilot or under evaluation at 93% of respondents.</p>

<p>Containers and microservices have compressed the deployment cycle. CI/CD adoption climbed 31% in one year, and 29% of teams now deploy to production several times a day. Every commit can reach production within hours. In that environment, trusting any single deployment by default is unwise. Every change has to be guarded and reversible.</p>

<p>The cost side has moved the other way. IBM’s Cost of a Data Breach report for 2024, researched by the Ponemon Institute, put the global average at $4.88 million, up 10% on 2023. A third of breaches involved shadow data, kept in places the security team did not know about. Reducing attack surface has stopped being an aspiration.</p>

<p>This is where the three patterns reinforce each other. Rootless containers limit the privileges an attacker actually obtains when a service is compromised. Immutable hosts make persistence harder, because the base system cannot be written to in place: an attacker who wants to survive a reboot is pushed out of <code class="language-plaintext highlighter-rouge">/usr</code> and into <code class="language-plaintext highlighter-rouge">/etc</code> and <code class="language-plaintext highlighter-rouge">/var</code>, which stay writable and persist across updates on most of these systems, and which are much smaller places to watch. Strict open source hygiene (vetted dependencies, SBOMs, prompt patching) narrows the way in to begin with.</p>

<p>Regulation points the same way. The EU Cyber Resilience Act entered into force on 10 December 2024. Its duty to report actively exploited vulnerabilities applies from 11 September 2026, and the rest of its obligations, built around provable integrity in the software supply chain, from 11 December 2027. Sector-specific requirements in finance and healthcare are doing similar work in the US. The rough consensus across regulators is that trust has to be earned and demonstrated, not assumed.</p>

<p>For a hobbyist running a homelab, none of this is binding. For anyone shipping software to other people, it increasingly is. The same patterns work at both scales. The setup that keeps a small lab honest is the setup, scaled up, that keeps an organization defensible, and the xz backdoor was found on a test machine by someone who noticed half a second.</p>

<h2 id="sources"><a class="anchor" href="#sources">Sources</a></h2>

<ul>
  <li>Freund, Andres. “backdoor in upstream xz/liblzma leading to ssh server compromise.” oss-security mailing list, 29 March 2024. CVE-2024-3094.</li>
  <li>Dolstra, Eelco. <em>The Purely Functional Software Deployment Model</em>. PhD thesis, Utrecht University, 2006.</li>
  <li>Red Hat. Podman documentation, rootless mode and networking.</li>
  <li>Black Duck. <em>2025 Open Source Security and Risk Analysis</em>. February 2025.</li>
  <li>Cloud Native Computing Foundation. <em>Cloud Native 2024: Approaching a Decade of Code, Cloud, and Change</em>. April 2025.</li>
  <li>IBM Security and Ponemon Institute. <em>Cost of a Data Breach Report 2024</em>.</li>
  <li>Executive Order 14028, “Improving the Nation’s Cybersecurity.” 12 May 2021.</li>
  <li>Regulation (EU) 2024/2847, the Cyber Resilience Act.</li>
  <li>Open Source Security Foundation (OpenSSF).</li>
</ul>]]></content><author><name>Securus</name></author><category term="Articles" /><category term="Linux" /><category term="rootless" /><category term="security" /><category term="open source" /><category term="podman" /><category term="immutable" /><category term="containers" /><summary type="html"><![CDATA[Where rootless containers, immutable operating systems and open source software meet, why the three together are becoming the new baseline, and what each still leaves open.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://securus.pages.dev/assets/img/social-preview.png" /><media:content medium="image" url="https://securus.pages.dev/assets/img/social-preview.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Checking a Linux host for rootkits with chkrootkit</title><link href="https://securus.pages.dev/posts/rootkit/" rel="alternate" type="text/html" title="Checking a Linux host for rootkits with chkrootkit" /><published>2025-06-15T00:00:00-04:00</published><updated>2025-06-15T00:00:00-04:00</updated><id>https://securus.pages.dev/posts/rootkit</id><content type="html" xml:base="https://securus.pages.dev/posts/rootkit/"><![CDATA[<p>In his Turing Award lecture, published in 1984 as “Reflections on Trusting Trust,” Ken Thompson described a C compiler altered to slip a back door into <code class="language-plaintext highlighter-rouge">login</code> whenever it compiled it, and to copy the alteration into any new compiler it built. The source code of both would be clean and the back door would remain. “You can’t trust code that you did not totally create yourself,” he concluded.</p>

<p>A rootkit is a practical cousin of that idea. It does nothing to get an attacker in; its job is to keep one hidden afterwards. Early Unix kits replaced the tools an administrator would look with, so that <code class="language-plaintext highlighter-rouge">ls</code>, <code class="language-plaintext highlighter-rouge">ps</code> and <code class="language-plaintext highlighter-rouge">netstat</code> stopped showing the intruder’s files, processes and connections. Later kits moved into the kernel as loadable modules, where they could filter what every program was told. In 2005 Mark Russinovich found one on his own Windows machine and traced it to the copy protection on a Sony BMG music CD.</p>

<p>The attack is on the instruments, and anything that checks for a rootkit has to be read with that in mind.</p>

<h2 id="what-it-is"><a class="anchor" href="#what-it-is">What it is</a></h2>

<p><code class="language-plaintext highlighter-rouge">chkrootkit</code>, written by Nelson Murilo and Klaus Steding-Jessen, is a small collection of shell and C programs that look for known signs of rootkit infection on a Linux system. It checks core utilities (<code class="language-plaintext highlighter-rouge">ps</code>, <code class="language-plaintext highlighter-rouge">ls</code>, <code class="language-plaintext highlighter-rouge">ifconfig</code>, <code class="language-plaintext highlighter-rouge">netstat</code>) against known patterns of tampering, looks for suspicious modifications in login services, and watches for the kinds of changes a loadable kernel module rootkit would make, such as processes hidden from <code class="language-plaintext highlighter-rouge">ps</code>.</p>

<p>It is a quick, lightweight check, well short of a full EDR, and it should run regularly as a baseline.</p>

<h2 id="installing"><a class="anchor" href="#installing">Installing</a></h2>

<p>On Debian or Ubuntu:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">sudo </span>apt update
<span class="nb">sudo </span>apt <span class="nb">install </span>chkrootkit
</code></pre></div></div>

<p>No configuration is needed. The default ruleset is what almost everyone uses.</p>

<h2 id="running-a-scan"><a class="anchor" href="#running-a-scan">Running a scan</a></h2>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">sudo </span>chkrootkit
</code></pre></div></div>

<p>A clean run produces output like:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Checking 'sshd'... not infected
Checking 'ifconfig'... not infected
Checking 'login'... not infected
</code></pre></div></div>

<p>When something looks wrong, the output flags it explicitly:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Warning: Possible LKM Trojan installed
</code></pre></div></div>

<p>That kind of warning is a starting point, not a verdict. <code class="language-plaintext highlighter-rouge">chkrootkit</code> has a reputation for false positives, so any hit needs corroboration before the host is treated as compromised. Pair it with <code class="language-plaintext highlighter-rouge">rkhunter</code>, with <code class="language-plaintext highlighter-rouge">AIDE</code> for file integrity, and with knowledge of what was recently changed on the machine. Some warnings are habitual: a DHCP client holding a raw socket can be reported as a packet sniffer, and a process that exits in the middle of a scan can trip the hidden-process check.</p>

<h2 id="the-tools-it-borrows"><a class="anchor" href="#the-tools-it-borrows">The tools it borrows</a></h2>

<p>Thompson’s problem applies to <code class="language-plaintext highlighter-rouge">chkrootkit</code> itself. To do its work it calls ordinary system commands, among them <code class="language-plaintext highlighter-rouge">awk</code>, <code class="language-plaintext highlighter-rouge">grep</code>, <code class="language-plaintext highlighter-rouge">ps</code> and <code class="language-plaintext highlighter-rouge">strings</code>, and on a compromised machine those are the very commands a rootkit replaces. Its authors anticipated this. The <code class="language-plaintext highlighter-rouge">-p</code> option tells it where to find known-good copies of the commands it uses, for example from read-only media:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">sudo </span>chkrootkit <span class="nt">-p</span> /mnt/safe/bin
</code></pre></div></div>

<p>The stronger check runs from outside the suspect system altogether. Boot a rescue image, mount the suspect disk, and point <code class="language-plaintext highlighter-rouge">chkrootkit</code> at it with <code class="language-plaintext highlighter-rouge">-r</code>, which treats a directory as the root of the system to examine:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">sudo </span>chkrootkit <span class="nt">-r</span> /mnt
</code></pre></div></div>

<p>A kernel-level rootkit cannot lie to a kernel that is not running.</p>

<h2 id="where-it-fits"><a class="anchor" href="#where-it-fits">Where it fits</a></h2>

<p>This is one tool in a layered host-security setup. It does not replace endpoint protection, it does not catch novel rootkits that match none of its signatures, and it does not give you forensics. What it does give you is a regular, scriptable check that takes seconds to run and flags the obvious cases.</p>

<p>For a homelab or a small fleet that is useful. It is a smoke alarm, and a smoke alarm has never put out a fire.</p>

<h2 id="running-it-on-a-schedule"><a class="anchor" href="#running-it-on-a-schedule">Running it on a schedule</a></h2>

<p>A weekly cron entry that logs to a dated file:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>@weekly root chkrootkit &gt; /var/log/chkrootkit-$(date +\%F).log
</code></pre></div></div>

<p>The line names the user it runs as, <code class="language-plaintext highlighter-rouge">root</code>, so it belongs in a system crontab: <code class="language-plaintext highlighter-rouge">/etc/crontab</code> or a file of its own under <code class="language-plaintext highlighter-rouge">/etc/cron.d/</code>. A personal crontab edited with <code class="language-plaintext highlighter-rouge">crontab -e</code> has no user field and would read <code class="language-plaintext highlighter-rouge">root</code> as the command. The <code class="language-plaintext highlighter-rouge">\%</code> is escaped because cron treats <code class="language-plaintext highlighter-rouge">%</code> as a line separator.</p>

<p>The resulting logs are easy to diff over time, which is more useful than any single scan; the question is rarely “is anything wrong right now?” and more often “what changed since last week?” A rootkit can make a machine look normal on any given day. It is harder for it to make this week look exactly like last week.</p>

<h2 id="sources"><a class="anchor" href="#sources">Sources</a></h2>

<ul>
  <li>Thompson, Ken. “Reflections on Trusting Trust.” <em>Communications of the ACM</em> 27, no. 8 (August 1984): 761 to 763.</li>
  <li>Russinovich, Mark. “Sony, Rootkits and Digital Rights Management Gone Too Far.” Sysinternals blog, 31 October 2005.</li>
  <li>Murilo, Nelson, and Klaus Steding-Jessen. chkrootkit README and manual page.</li>
</ul>]]></content><author><name>Securus</name></author><category term="Portfolio" /><category term="Linux" /><category term="chkrootkit" /><category term="linux" /><category term="host-security" /><category term="threat-detection" /><category term="security-plus" /><summary type="html"><![CDATA[What a rootkit attacks, how chkrootkit looks for the known ones, why its results need a second opinion, and how to run it on a schedule.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://securus.pages.dev/assets/img/social-preview.png" /><media:content medium="image" url="https://securus.pages.dev/assets/img/social-preview.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Reading logs for the first ten minutes</title><link href="https://securus.pages.dev/posts/log-file-analysis/" rel="alternate" type="text/html" title="Reading logs for the first ten minutes" /><published>2025-06-01T00:00:00-04:00</published><updated>2025-06-01T00:00:00-04:00</updated><id>https://securus.pages.dev/posts/log-file-analysis</id><content type="html" xml:base="https://securus.pages.dev/posts/log-file-analysis/"><![CDATA[<p>In 1997 Marcus Ranum, who had built some of the first commercial firewalls, described a way of reading logs he called “artificial ignorance.” Nobody can read a busy system’s logs line by line, he argued, and nobody can write rules for every attack in advance. So do the reverse: write patterns for the lines known to be boring, throw those away, and read what is left.</p>

<p>The script described here takes the other half of that bargain and looks for lines known to be bad. It is a Python script that reads log files and flags patterns associated with common attack behaviour: brute-force login attempts, the traces of port scans, and probes against URLs that should not be accessible.</p>

<p>A real SIEM does far more. This automates the first ten minutes of looking at a log when something feels off, the part where you grep for failed logins and source IPs and stare at the patterns. That work is repetitive and easy to script.</p>

<h2 id="what-it-handles"><a class="anchor" href="#what-it-handles">What it handles</a></h2>

<ul>
  <li><code class="language-plaintext highlighter-rouge">.log</code> input from OpenSSH (<code class="language-plaintext highlighter-rouge">auth.log</code>) and Apache or Nginx (<code class="language-plaintext highlighter-rouge">access.log</code>)</li>
  <li>Failed SSH logins, repeated requests from the same IP, sequences that look like port scans, requests against known-sensitive paths</li>
  <li>Output aggregated by source IP and rule type</li>
  <li>A regex-based rule table that is straightforward to extend</li>
  <li>CLI invocation, suitable for cron or piping into anything else</li>
</ul>

<h2 id="how-it-works"><a class="anchor" href="#how-it-works">How it works</a></h2>

<p>The script reads the file line by line and applies a list of regex rules. Each rule is tagged with a threat type and a severity. Matched events are stored with the timestamp, the source IP when there is one, and the rule that fired. Results print to stdout and optionally to a file.</p>

<p>Rules live in a single dictionary at the top of the file, so a new detection is one line plus a regex.</p>

<h2 id="what-a-log-can-see"><a class="anchor" href="#what-a-log-can-see">What a log can see</a></h2>

<p>A log is written by one service, about that service. <code class="language-plaintext highlighter-rouge">auth.log</code> knows what sshd saw; <code class="language-plaintext highlighter-rouge">access.log</code> knows what the web server saw. A port scan touches hundreds or thousands of ports, and on the ports where nothing is listening it leaves no line in any log at all. What it does leave is a trace on the ports that log: on SSH, connections that open and close without ever attempting a login, and on a web server, short bursts of requests for paths that do not exist. “Possible port scan” in the output below means that kind of trace from one source. To see the scan itself, the evidence has to come from the network, a firewall log or a capture.</p>

<h2 id="example-output"><a class="anchor" href="#example-output">Example output</a></h2>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>[2025-06-01 21:31:44] WARNING - Repeated failed SSH login from 192.168.1.45
[2025-06-01 21:32:05] INFO    - Possible port scan detected from 103.21.244.0
[2025-06-01 21:34:09] ALERT   - Attempted access to /admin (403 Forbidden) from 45.67.89.123
</code></pre></div></div>

<p>The severities rise for a reason. A failed login is ordinary, and many from one address are a warning. A probe of <code class="language-plaintext highlighter-rouge">/admin</code> answered with 403 means someone went looking for an administrative page by name, which is a step past noise.</p>

<h2 id="usage"><a class="anchor" href="#usage">Usage</a></h2>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>python log_analyzer.py <span class="nt">--input</span> /path/to/file.log <span class="nt">--output</span> report.txt
</code></pre></div></div>

<p>Flags:</p>
<ul>
  <li><code class="language-plaintext highlighter-rouge">--input</code> path to the log file</li>
  <li><code class="language-plaintext highlighter-rouge">--output</code> write results to a file instead of stdout</li>
  <li><code class="language-plaintext highlighter-rouge">--verbose</code> include the surrounding lines for each match</li>
</ul>

<h2 id="what-comes-next"><a class="anchor" href="#what-comes-next">What comes next</a></h2>

<ul>
  <li>GeoIP enrichment, so the source country is visible on flagged IPs</li>
  <li>Optional firewall integration, so a flagged IP can be pushed straight to a deny list</li>
  <li>A small web view for browsing results, mostly for convenience</li>
  <li>Configurable thresholds per rule, so a quiet environment does not generate the same severity as a busy one</li>
</ul>

<p>The second item needs care. A script that turns a log line into a firewall rule hands some control of the firewall to whoever can put text into that log. A username crafted to look like an address can get the wrong host banned, and behind a proxy the address in the log may be the proxy’s own. <a href="/posts/fail2ban-ssh-lockouts/">fail2ban</a>, which does exactly this job, limits the damage with bans that expire and a list of addresses it will never ban. A home-grown version needs both.</p>

<p>The current version covers enough to be useful for small environments and to act as a base for anything more ambitious. Real SIEMs do all of this and more, but they also cost money and need infrastructure. For a homelab or a single VPS, a short Python script is a reasonable starting point, and Ranum’s filter of known-boring lines is the next thing worth adding to it.</p>

<h2 id="sources"><a class="anchor" href="#sources">Sources</a></h2>

<ul>
  <li>Ranum, Marcus J. “artificial ignorance: how-to guide.” Posted to the firewall-wizards mailing list, 1997.</li>
</ul>]]></content><author><name>Securus</name></author><category term="Portfolio" /><category term="Logs" /><category term="python" /><category term="log analysis" /><category term="threat-detection" /><category term="portfolio" /><category term="project" /><summary type="html"><![CDATA[A Python log analyzer that reads SSH and web server logs and flags brute-force attempts, scan traces and probes of restricted URLs, and what a log can and cannot see.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://securus.pages.dev/assets/img/social-preview.png" /><media:content medium="image" url="https://securus.pages.dev/assets/img/social-preview.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Removing addresses from an allow list with Python</title><link href="https://securus.pages.dev/posts/python-algorithm/" rel="alternate" type="text/html" title="Removing addresses from an allow list with Python" /><published>2025-05-24T00:00:00-04:00</published><updated>2025-05-24T00:00:00-04:00</updated><id>https://securus.pages.dev/posts/python-algorithm</id><content type="html" xml:base="https://securus.pages.dev/posts/python-algorithm/"><![CDATA[<h2 id="the-problem"><a class="anchor" href="#the-problem">The problem</a></h2>

<p>Around 1990 Wietse Venema, at the Eindhoven University of Technology, was trying to watch an intruder who kept coming back to the university’s machines. The tool he wrote for it, TCP Wrapper, sat in front of network services and decided who could reach them by reading two plain text files, <code class="language-plaintext highlighter-rouge">/etc/hosts.allow</code> and <code class="language-plaintext highlighter-rouge">/etc/hosts.deny</code>. Versions of those files still exist on Linux systems, and the idea outlived them everywhere: a list of addresses, kept as text, that says who may connect.</p>

<p>A list like that is only as good as the last edit to it. Somebody adds an address in a hurry, somebody else removes the wrong line, and nothing complains until a user is locked out or a stranger is let in.</p>

<p>A simulated environment here keeps an allow list of IP addresses in a text file, <code class="language-plaintext highlighter-rouge">allow_list.txt</code>. Periodically, some addresses need to come off it. By hand, that is error-prone the moment the list runs past ten entries, and the operation belongs in code that can be reviewed and kept under version control. This is a short script that does the job.</p>

<hr />

<h2 id="reading-the-file"><a class="anchor" href="#reading-the-file">Reading the file</a></h2>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">import_file</span> <span class="o">=</span> <span class="sh">"</span><span class="s">allow_list.txt</span><span class="sh">"</span>
<span class="k">with</span> <span class="nf">open</span><span class="p">(</span><span class="n">import_file</span><span class="p">,</span> <span class="sh">"</span><span class="s">r</span><span class="sh">"</span><span class="p">)</span> <span class="k">as</span> <span class="nb">file</span><span class="p">:</span>
    <span class="n">ip_addresses</span> <span class="o">=</span> <span class="nb">file</span><span class="p">.</span><span class="nf">read</span><span class="p">()</span>
</code></pre></div></div>

<p><a class="img-link" href="/assets/img/reading-contents.webp"><img src="/assets/img/reading-contents.webp" alt="Screenshot showing code" width="624" height="87" loading="lazy" decoding="async"></a>
<em>Reading the file.</em></p>

<p>Opening in read mode (<code class="language-plaintext highlighter-rouge">"r"</code>) gives the raw text as one string. The <code class="language-plaintext highlighter-rouge">with</code> block closes the file when the block ends, including when an exception ends it early, which is the reason to use it over a bare <code class="language-plaintext highlighter-rouge">open()</code>.</p>

<hr />

<h2 id="splitting-into-a-list"><a class="anchor" href="#splitting-into-a-list">Splitting into a list</a></h2>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">ip_addresses</span> <span class="o">=</span> <span class="n">ip_addresses</span><span class="p">.</span><span class="nf">split</span><span class="p">(</span><span class="sh">"</span><span class="se">\n</span><span class="sh">"</span><span class="p">)</span>
</code></pre></div></div>

<p><a class="img-link" href="/assets/img/string-conversion.webp"><img src="/assets/img/string-conversion.webp" alt="Screenshot showing code of the content split" width="519" height="56" loading="lazy" decoding="async"></a>
<em>String to list.</em></p>

<p><code class="language-plaintext highlighter-rouge">split("\n")</code> turns the multi-line string into a list of lines. Each line is an IP, so each list element is one address. If the file ends with a newline, the last element is an empty string. That does no harm, and the join at the end puts the newline back.</p>

<hr />

<h2 id="removing-the-unauthorized-entries"><a class="anchor" href="#removing-the-unauthorized-entries">Removing the unauthorized entries</a></h2>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">remove_list</span> <span class="o">=</span> <span class="p">[</span><span class="sh">"</span><span class="s">10.0.0.5</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">172.16.0.3</span><span class="sh">"</span><span class="p">]</span>
<span class="k">for</span> <span class="n">element</span> <span class="ow">in</span> <span class="n">remove_list</span><span class="p">:</span>
    <span class="k">if</span> <span class="n">element</span> <span class="ow">in</span> <span class="n">ip_addresses</span><span class="p">:</span>
        <span class="n">ip_addresses</span><span class="p">.</span><span class="nf">remove</span><span class="p">(</span><span class="n">element</span><span class="p">)</span>
</code></pre></div></div>

<p><a class="img-link" href="/assets/img/remove-list.webp"><img src="/assets/img/remove-list.webp" alt="Screenshot showing code of the IP remove_list" width="321" height="112" loading="lazy" decoding="async"></a>
<em>The remove list.</em></p>

<p><a class="img-link" href="/assets/img/removing-ip.webp"><img src="/assets/img/removing-ip.webp" alt="Screenshot showing code" width="529" height="165" loading="lazy" decoding="async"></a>
<em>Iterating and removing.</em></p>

<p>For each IP in <code class="language-plaintext highlighter-rouge">remove_list</code>, the loop checks whether it appears in the allow list and removes it if so. The loop walks <code class="language-plaintext highlighter-rouge">remove_list</code> and changes <code class="language-plaintext highlighter-rouge">ip_addresses</code>, so it never modifies the list it is iterating over. <code class="language-plaintext highlighter-rouge">.remove()</code> deletes the first occurrence only; that is fine here because IPs are unique in the source file.</p>

<p>If duplicates were possible, a list comprehension would be safer: <code class="language-plaintext highlighter-rouge">ip_addresses = [ip for ip in ip_addresses if ip not in remove_list]</code>.</p>

<p>Matching is exact, character for character. A line with a stray trailing space will not match its address and will survive the cleanup, which is one more reason the input needs checking.</p>

<hr />

<h2 id="writing-back"><a class="anchor" href="#writing-back">Writing back</a></h2>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">ip_addresses</span> <span class="o">=</span> <span class="sh">"</span><span class="se">\n</span><span class="sh">"</span><span class="p">.</span><span class="nf">join</span><span class="p">(</span><span class="n">ip_addresses</span><span class="p">)</span>
<span class="k">with</span> <span class="nf">open</span><span class="p">(</span><span class="n">import_file</span><span class="p">,</span> <span class="sh">"</span><span class="s">w</span><span class="sh">"</span><span class="p">)</span> <span class="k">as</span> <span class="nb">file</span><span class="p">:</span>
    <span class="nb">file</span><span class="p">.</span><span class="nf">write</span><span class="p">(</span><span class="n">ip_addresses</span><span class="p">)</span>
</code></pre></div></div>

<p><a class="img-link" href="/assets/img/updating-ip.webp"><img src="/assets/img/updating-ip.webp" alt="Screenshot showing code of the IP overwrite" width="425" height="114" loading="lazy" decoding="async"></a>
<em>Writing the cleaned list back.</em></p>

<p><code class="language-plaintext highlighter-rouge">"\n".join()</code> reverses the earlier <code class="language-plaintext highlighter-rouge">.split("\n")</code>, putting the list back into the file’s original shape. Opening in <code class="language-plaintext highlighter-rouge">"w"</code> mode truncates the file before writing, so the result fully replaces the previous contents.</p>

<p>That truncation is also the script’s weak point. The file is emptied first and written second, and if the process dies in between, the allow list is left empty or half written. The write is not atomic.</p>

<hr />

<h2 id="what-this-is-actually-useful-for"><a class="anchor" href="#what-this-is-actually-useful-for">What this is actually useful for</a></h2>

<p>The script is small. The pattern is what matters: read a structured config file, change it in code, write it back. The same shape applies to firewall config, DNS zone files, <code class="language-plaintext highlighter-rouge">/etc/hosts</code>, allow lists, deny lists, anything text-based.</p>

<p>What is missing here, and would matter in production:</p>

<ul>
  <li>An atomic write: write the new list to a temporary file in the same directory, then swap it into place with <code class="language-plaintext highlighter-rouge">os.replace()</code>, so the file on disk is always either the old list or the new one</li>
  <li>File locking, so two runs cannot race each other</li>
  <li>A backup copy before overwriting, so a bad input can be undone</li>
  <li>Validation that the input file actually looks like an IP list before changing it</li>
  <li>A log of what was removed, with timestamps, for audit</li>
</ul>

<p>For a self-contained exercise this script is enough. For something that controls who can reach a system, those additions are the difference between automation and automation that will one day delete the wrong thing.</p>

<h2 id="sources"><a class="anchor" href="#sources">Sources</a></h2>

<ul>
  <li>Venema, Wietse. “TCP WRAPPER: Network Monitoring, Access Control, and Booby Traps.” <em>Proceedings of the 3rd UNIX Security Symposium</em>, USENIX, 1992.</li>
  <li>Python Software Foundation. Python documentation for <code class="language-plaintext highlighter-rouge">open()</code>, <code class="language-plaintext highlighter-rouge">str.split()</code>, <code class="language-plaintext highlighter-rouge">list.remove()</code> and <code class="language-plaintext highlighter-rouge">os.replace()</code>.</li>
</ul>]]></content><author><name>Securus</name></author><category term="Portfolio" /><category term="Python" /><category term="file-handling" /><category term="python" /><category term="automation" /><category term="scripting" /><category term="security-plus" /><category term="project" /><category term="portfolio" /><summary type="html"><![CDATA[A short Python script that reads a text allow list, removes a set of unauthorized IPs and writes the cleaned list back, and what it would need before it controlled anything real.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://securus.pages.dev/assets/img/social-preview.png" /><media:content medium="image" url="https://securus.pages.dev/assets/img/social-preview.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Incident journal: events and experiences</title><link href="https://securus.pages.dev/posts/incident-journal/" rel="alternate" type="text/html" title="Incident journal: events and experiences" /><published>2025-05-13T00:00:00-04:00</published><updated>2025-05-13T00:00:00-04:00</updated><id>https://securus.pages.dev/posts/incident-journal</id><content type="html" xml:base="https://securus.pages.dev/posts/incident-journal/"><![CDATA[<p>In August 1986 Clifford Stoll, an astronomer turned systems manager at the Lawrence Berkeley Laboratory, was asked to explain a 75-cent discrepancy between two accounting systems. The cents led to an unknown user, the user to an intruder working through the lab’s computers into American military networks, and the intruder, after most of a year, to a hacker in Hanover selling what he found to the KGB. Stoll’s book about it, <em>The Cuckoo’s Egg</em>, is remembered for the chase. What carried the case was his logbook. He wrote down every session, every printout, every call to an agency that would not listen, and when the FBI and the German police finally did, the notebook was the record they worked from.</p>

<p>Incident response has grown into a discipline with frameworks since then, but the logbook is still its spine. Anything not written down at the time has to be reconstructed later from memory, and memory is the first thing an incident costs.</p>

<p>This is a running log of investigations, detections and the automation that falls out of them. Each entry is mapped to a phase of the lifecycle in NIST Special Publication 800-61 Revision 2: preparation; detection and analysis; containment, eradication and recovery; and post-incident activity. Each records what triggered it, how it was scoped and what closed it out. (NIST issued a third revision in April 2025, which recasts the guidance around the functions of its Cybersecurity Framework 2.0. The four phases of Revision 2 remain the common vocabulary, and they are the ones used here.)</p>

<hr />

<h2 id="entry-001-phishing-investigation"><a class="anchor" href="#entry-001-phishing-investigation">Entry 001: Phishing investigation</a></h2>

<p>Date: 2025-05-13<br />
Phase: Detection &amp; Analysis<br />
Tools: Outlook, VirusTotal</p>

<p>A user reported an email impersonating HR with an “updated benefits enrollment” prompt. It had a lookalike sender address and a button pointing at a credential-harvesting page, and it had gone to a broad internal distribution list that put it in front of several other mailboxes.</p>

<p>The full headers, pulled in Outlook, showed the sender domain was spoofed. The embedded URL and its registrant domain went through VirusTotal: flagged, registered days earlier, and with no tie to the organization. A search of mailboxes for the same message scoped who else had received it.</p>

<p>Containment:</p>
<ul>
  <li>Blocked the sender domain and URL at the email gateway.</li>
  <li>Sent an advisory to recipients, and reset the credentials and forced MFA re-registration for the one user who clicked.</li>
  <li>Logged the indicators (sender, subject, URL) and filed the incident.</li>
</ul>

<p>The whole chain was confirmable in minutes with tools everyone already has. The slow part is never the analysis. It is getting the report in the first place, which is why the user who reported it did the most important work in this entry.</p>

<hr />

<h2 id="entry-002-malware-detection-with-suricata"><a class="anchor" href="#entry-002-malware-detection-with-suricata">Entry 002: Malware detection with Suricata</a></h2>

<p>Date: 2025-05-15<br />
Phase: Detection &amp; Analysis<br />
Tools: Suricata, Wireshark</p>

<p>A host on <code class="language-plaintext highlighter-rouge">192.168.1.x</code> was beaconing to a known-malicious IP, a regular call-out consistent with command and control, and the existing rules were letting it through.</p>

<p>The response was a Suricata rule written against the observed pattern and destination, rather than a generic signature pulled from a feed. Before trusting it, the match was confirmed on captured packets in Wireshark. Then the host was isolated and re-imaged clean.</p>

<p>A rule written against real captured traffic fires where a generic signature sits silent. Running Wireshark next to Suricata makes the feedback loop tight enough to tune a rule in one sitting.</p>

<hr />

<h2 id="entry-003-brute-force-detection-in-splunk"><a class="anchor" href="#entry-003-brute-force-detection-in-splunk">Entry 003: Brute-force detection in Splunk</a></h2>

<p>Date: 2025-05-18<br />
Phase: Detection &amp; Analysis<br />
Tools: Splunk</p>

<p>The task was brute-force detection and a monitoring view over an authentication-log dataset with heavy failure noise. Most failed logins are typos. The job is to find the ones that are not.</p>

<p>Work:</p>
<ul>
  <li>Grouped failed logins by <code class="language-plaintext highlighter-rouge">src_ip</code> and <code class="language-plaintext highlighter-rouge">user</code> to pull the outliers out of the noise.</li>
  <li>Built time-series views to surface bursts inside short windows.</li>
  <li>Set threshold alerting on excessive failures per interval.</li>
  <li>Built a dashboard consolidating the failure metrics for review at a glance.</li>
</ul>

<p>Normalization decides everything here. The query is trivial once <code class="language-plaintext highlighter-rouge">src_ip</code> and <code class="language-plaintext highlighter-rouge">user</code> are consistent fields across every source, and miserable when one log calls the address <code class="language-plaintext highlighter-rouge">src</code> and another buries it in free text.</p>

<hr />

<h2 id="entry-004-file-hash-analysis"><a class="anchor" href="#entry-004-file-hash-analysis">Entry 004: File hash analysis</a></h2>

<p>Date: 2025-05-21<br />
Phase: Detection &amp; Analysis<br />
Tools: VirusTotal, Any.run, Hybrid Analysis</p>

<p>A single SHA256 hash, triaged across three reputation and sandbox platforms to build a risk profile.</p>

<ul>
  <li>VirusTotal: flagged by 39 vendors.</li>
  <li>Any.run: a dynamic run showed ransomware behaviour, file enumeration followed by encryption.</li>
  <li>Hybrid Analysis: external call patterns and file-system modifications.</li>
</ul>

<p>VirusTotal gives the verdict and the sandboxes give the behaviour. The vendor count said the file was bad. Any.run’s enumerate-then-encrypt sequence said what kind of bad, and that is the part that changes the response: ransomware means checking backups and looking for shares the host could reach, before anything else.</p>

<hr />

<h2 id="entry-005-ip-allow-list-automation"><a class="anchor" href="#entry-005-ip-allow-list-automation">Entry 005: IP allow list automation</a></h2>

<p>Date: 2025-05-24<br />
Phase: Preparation &amp; Containment<br />
Tools: Python, VS Code</p>

<p>A manual allow-list review, error-prone the moment the file got long, replaced with a short Python cleanup (written up in full in <a href="/posts/python-algorithm/">its own post</a>).</p>

<ul>
  <li>Parsed the allow list and loaded a defined <code class="language-plaintext highlighter-rouge">remove_list</code> of unauthorized entries.</li>
  <li>Filtered out the matches and wrote the cleaned list back.</li>
  <li>Structured it to run on a schedule or drop into a SOAR workflow.</li>
</ul>

<p>The value is not the twenty lines of Python. It is taking a human out of a step where one typo means an outage or an open door.</p>

<hr />

<h2 id="between-entries"><a class="anchor" href="#between-entries">Between entries</a></h2>

<p>Five entries, across detection, containment and preparation. The method is the same in each: scope it, pick the tool that answers the actual question, write down what closed it out. Stoll’s notebook did not look like much either.</p>

<p>Ongoing. Lateral movement, log forensics and response automation are next.</p>

<h2 id="sources"><a class="anchor" href="#sources">Sources</a></h2>

<ul>
  <li>Stoll, Clifford. <em>The Cuckoo’s Egg: Tracking a Spy Through the Maze of Computer Espionage</em>. New York: Doubleday, 1989.</li>
  <li>Cichonski, Paul, Tom Millar, Tim Grance and Karen Scarfone. <em>Computer Security Incident Handling Guide</em>. NIST Special Publication 800-61 Revision 2. August 2012.</li>
  <li>NIST. <em>Incident Response Recommendations and Considerations for Cybersecurity Risk Management: A CSF 2.0 Community Profile</em>. NIST Special Publication 800-61 Revision 3. April 2025.</li>
</ul>]]></content><author><name>Securus</name></author><category term="Portfolio" /><category term="Journal" /><category term="incident-response" /><category term="nist" /><category term="blue-team" /><category term="detection" /><category term="splunk" /><category term="suricata" /><category term="threat-hunting" /><summary type="html"><![CDATA[Working notes from investigations and detection engineering, each entry mapped to a phase of the NIST incident response lifecycle.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://securus.pages.dev/assets/img/social-preview.png" /><media:content medium="image" url="https://securus.pages.dev/assets/img/social-preview.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Proving a file is unchanged: hashing with CertUtil</title><link href="https://securus.pages.dev/posts/certutil-hashing/" rel="alternate" type="text/html" title="Proving a file is unchanged: hashing with CertUtil" /><published>2025-05-12T00:00:00-04:00</published><updated>2025-05-12T00:00:00-04:00</updated><id>https://securus.pages.dev/posts/certutil-hashing</id><content type="html" xml:base="https://securus.pages.dev/posts/certutil-hashing/"><![CDATA[<p>In April 1992 Ronald Rivest published MD5, RFC 1321, which turned any file into a 128-bit fingerprint. In 2004 Xiaoyun Wang and her colleagues showed how to make two inputs with the same MD5 digest, and in 2012 the Flame malware used an MD5 collision to forge a Microsoft code-signing certificate. In February 2017 researchers at Google and CWI Amsterdam did the same to SHA-1 with two different PDF files.</p>

<p>A hash function promises that no two inputs anyone can find will share an output, and the promise ages. The workflow built on it has not changed: hash a file, keep the digest, hash again later, compare.</p>

<p><a class="img-link" href="/assets/img/hash-verified.webp"><img src="/assets/img/hash-verified.webp" alt="CertUtil Hash Algorithm" width="607" height="129" loading="lazy" decoding="async"></a>
<em>Initial SHA256 hash generation using CertUtil.</em></p>

<p>CertUtil is the certificate tool built into Windows, and its <code class="language-plaintext highlighter-rouge">-hashfile</code> verb prints a file’s digest with nothing to install. The convenience cuts both ways: attackers use the same binary to fetch and decode payloads, which is why MITRE ATT&amp;CK lists it.</p>

<h2 id="test-setup"><a class="anchor" href="#test-setup">Test setup</a></h2>

<p><a class="img-link" href="/assets/img/testfile.webp"><img src="/assets/img/testfile.webp" alt="CertUtil Testfile Creation" width="762" height="38" loading="lazy" decoding="async"></a>
<em>testfile successfully created and placed.</em></p>

<p>The test file was <code class="language-plaintext highlighter-rouge">testfile.txt</code>, holding simple text. After creating the sample file, a copy was made so that it could be tampered with:</p>

<p><a class="img-link" href="/assets/img/copy-created.webp"><img src="/assets/img/copy-created.webp" alt="Testfile Copy completed" width="787" height="67" loading="lazy" decoding="async"></a>
<em>Copy of testfile.txt.</em></p>

<p>The two files were hashed with SHA-256:</p>

<div class="language-powershell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">certutil</span><span class="w"> </span><span class="nt">-hashfile</span><span class="w"> </span><span class="nx">testfile.txt</span><span class="w"> </span><span class="nx">SHA256</span><span class="w">
</span><span class="n">certutil</span><span class="w"> </span><span class="nt">-hashfile</span><span class="w"> </span><span class="nx">copy.txt</span><span class="w"> </span><span class="nx">SHA256</span><span class="w">
</span></code></pre></div></div>

<p><a class="img-link" href="/assets/img/hash-identical.webp"><img src="/assets/img/hash-identical.webp" alt="SHA256 Hashes tested" width="677" height="96" loading="lazy" decoding="async"></a>
<em>Identical SHA256 hash generation proven.</em></p>

<p>Both digests began <code class="language-plaintext highlighter-rouge">7b1b1356</code> and matched to the last character, whatever the files were called.</p>

<p>Then the copy was <em>tampered</em> with and hashed again:</p>

<p><a class="img-link" href="/assets/img/hash-change-verified.webp"><img src="/assets/img/hash-change-verified.webp" alt="CertUtil Hash Tamper" width="643" height="103" loading="lazy" decoding="async"></a>
<em>Initial SHA256 hash is now different.</em></p>

<p>The new digest began <code class="language-plaintext highlighter-rouge">a96e3360</code>. A good hash function is built so that one changed character flips about half the output bits, and a small edit cannot hide behind a small difference.</p>

<p>SHA-1 and SHA-512 were tested on the original file as well:</p>

<div class="language-powershell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">certutil</span><span class="w"> </span><span class="nt">-hashfile</span><span class="w"> </span><span class="nx">testfile.txt</span><span class="w"> </span><span class="nx">SHA1</span><span class="w">
</span><span class="n">certutil</span><span class="w"> </span><span class="nt">-hashfile</span><span class="w"> </span><span class="nx">testfile.txt</span><span class="w"> </span><span class="nx">SHA512</span><span class="w">
</span></code></pre></div></div>

<p>The SHA-1 digest is 40 hex characters and the SHA-512 one 128. <code class="language-plaintext highlighter-rouge">-hashfile</code> also accepts MD2, MD4, MD5, SHA256 and SHA384, and with no algorithm named it uses SHA-1.</p>

<h2 id="which-algorithm-and-what-a-match-proves"><a class="anchor" href="#which-algorithm-and-what-a-match-proves">Which algorithm, and what a match proves</a></h2>

<p>For catching accidents, any of them works. Against someone who wants a tampered file to pass, use SHA-256 or longer, because MD5 and SHA-1 collisions can now be manufactured.</p>

<p>A match proves the file is the same as whatever produced the published digest. It says nothing about who produced it. If the digest sits on the same web server as the download, anyone who can replace the file can replace the digest too. That gap is what signatures close: a GPG signature or Authenticode answers who, and the hash answers whether.</p>

<h2 id="where-it-goes-from-here"><a class="anchor" href="#where-it-goes-from-here">Where it goes from here</a></h2>

<p>The exercise lines up with the cryptographic concepts section of Security+, but the useful part is operational. For a file from anywhere not fully trusted, the published hash and a <code class="language-plaintext highlighter-rouge">CertUtil -hashfile</code> against the local copy answer “did this arrive intact?” in one command.</p>

<p>The same trick scales. Hash the binaries that matter on a known-good system, keep the list where the system cannot write, and check again later. Gene Kim and Eugene Spafford built Tripwire on that idea at Purdue in 1992. It only has to be done before the day it is needed.</p>

<h2 id="sources"><a class="anchor" href="#sources">Sources</a></h2>

<ul>
  <li>Rivest, R. RFC 1321, “The MD5 Message-Digest Algorithm.” April 1992.</li>
  <li>Wang, Xiaoyun, Dengguo Feng, Xuejia Lai and Hongbo Yu. “Collisions for Hash Functions MD4, MD5, HAVAL-128 and RIPEMD.” Cryptology ePrint Archive 2004/199.</li>
  <li>Stevens, Marc, Elie Bursztein, Pierre Karpman, Ange Albertini and Yarik Markov. “The First Collision for Full SHA-1.” CRYPTO 2017.</li>
  <li>Kim, Gene H., and Eugene H. Spafford. “The Design and Implementation of Tripwire: A File System Integrity Checker.” <em>Proceedings of the 2nd ACM Conference on Computer and Communications Security</em>, 1994.</li>
  <li>MITRE ATT&amp;CK. Software entry for certutil.</li>
  <li>Microsoft. “certutil” command reference.</li>
</ul>]]></content><author><name>Securus</name></author><category term="Portfolio" /><category term="Cryptography" /><category term="hashing" /><category term="certutil" /><category term="integrity" /><category term="sha256" /><category term="security-plus" /><category term="project" /><category term="portfolio" /><summary type="html"><![CDATA[Generating and comparing file hashes with CertUtil on Windows 11 LTSC IoT, what a matching digest proves, and what it cannot.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://securus.pages.dev/assets/img/social-preview.png" /><media:content medium="image" url="https://securus.pages.dev/assets/img/social-preview.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Closing port 445: SMB, Windows Firewall and lateral movement</title><link href="https://securus.pages.dev/posts/port-management/" rel="alternate" type="text/html" title="Closing port 445: SMB, Windows Firewall and lateral movement" /><published>2025-05-09T00:00:00-04:00</published><updated>2025-05-09T00:00:00-04:00</updated><id>https://securus.pages.dev/posts/port-management</id><content type="html" xml:base="https://securus.pages.dev/posts/port-management/"><![CDATA[<p>On 12 May 2017 the WannaCry ransomware began encrypting computers, and within days it had reached more than 200,000 of them in some 150 countries, hospitals in England’s National Health Service among them. Nobody had to open an attachment. It arrived through port 445 using EternalBlue, an NSA exploit for Windows’ SMBv1 server that a group calling itself the Shadow Brokers had published in April; Microsoft had patched the flaw in March, in MS17-010. Six weeks later NotPetya used the same exploit against companies in Ukraine and far beyond. Once one machine on a flat network falls, SMB is how an attacker, or a worm, walks to the next.</p>

<p><a class="img-link" href="/assets/img/firewall-rule.webp"><img src="/assets/img/firewall-rule.webp" alt="Firewall Rule - Block Port 445" width="1537" height="247" loading="lazy" decoding="async"></a>
<em>Custom rule blocking inbound SMB traffic (port 445) applied to all network profiles.</em></p>

<p>SMB, Server Message Block, is Windows’ file and printer sharing protocol. This post blocks it on one host with Windows Defender Firewall with Advanced Security.</p>

<h2 id="why-port-445-is-a-risk"><a class="anchor" href="#why-port-445-is-a-risk">Why port 445 is a risk</a></h2>

<table>
  <thead>
    <tr>
      <th>Threat type</th>
      <th>Description</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Wormable exploits</td>
      <td>Port 445 was the entry point for EternalBlue, and so for WannaCry and NotPetya</td>
    </tr>
    <tr>
      <td>Lateral movement</td>
      <td>Attackers use SMB to move between machines in a domain</td>
    </tr>
    <tr>
      <td>Remote execution</td>
      <td>Unpatched SMB services can allow unauthenticated code execution</td>
    </tr>
    <tr>
      <td>Enumeration vector</td>
      <td>SMB reveals shares, system names and users to attackers</td>
    </tr>
  </tbody>
</table>

<p>None of this needs the port to be reachable from the internet. Internal exposure is the risk that matters once any machine on the network is compromised.</p>

<h2 id="steps-taken"><a class="anchor" href="#steps-taken">Steps taken</a></h2>

<h3 id="1-opened-the-firewall-console"><a class="anchor" href="#1-opened-the-firewall-console">1. Opened the firewall console</a></h3>

<p>Running <code class="language-plaintext highlighter-rouge">wf.msc</code> opens Windows Defender Firewall with Advanced Security.</p>

<h3 id="2-reviewed-the-existing-rules"><a class="anchor" href="#2-reviewed-the-existing-rules">2. Reviewed the existing rules</a></h3>

<p>Under Inbound Rules, sorted by port, the machine had:</p>

<ul>
  <li>File and Printer Sharing (SMB-In) enabled on Private networks</li>
  <li>Allow rules for TCP 445 (SMB directly over TCP), UDP 137 (the NetBIOS name service) and UDP 138 (the NetBIOS datagram service), all part of the file-sharing stack</li>
</ul>

<h3 id="3-created-a-custom-inbound-block-rule"><a class="anchor" href="#3-created-a-custom-inbound-block-rule">3. Created a custom inbound block rule</a></h3>

<p><a class="img-link" href="/assets/img/firewall-properties.webp"><img src="/assets/img/firewall-properties.webp" alt="Firewall Properties - Block Port 445" width="523" height="463" loading="lazy" decoding="async"></a>
<em>The block rule’s properties: enabled, action set to block the connection.</em></p>

<ul>
  <li>Rule Type: Port</li>
  <li>Protocol: TCP</li>
  <li>Port: 445</li>
  <li>Action: Block the connection</li>
  <li>Profile: All (Domain, Private, Public)</li>
  <li>Name: <code class="language-plaintext highlighter-rouge">Block SMB TCP 445 - Harden Host</code></li>
</ul>

<p>The same rule can be made from PowerShell, which is the form worth keeping if more than one machine needs it:</p>

<div class="language-powershell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">New-NetFirewallRule</span><span class="w"> </span><span class="nt">-DisplayName</span><span class="w"> </span><span class="s2">"Block SMB TCP 445 - Harden Host"</span><span class="w"> </span><span class="nt">-Direction</span><span class="w"> </span><span class="nx">Inbound</span><span class="w"> </span><span class="nt">-Protocol</span><span class="w"> </span><span class="nx">TCP</span><span class="w"> </span><span class="nt">-LocalPort</span><span class="w"> </span><span class="nx">445</span><span class="w"> </span><span class="nt">-Action</span><span class="w"> </span><span class="nx">Block</span><span class="w">
</span></code></pre></div></div>

<p>Where the rule sits in the list does not matter. Windows Firewall has no rule order: a block rule beats any matching allow rule wherever the two appear, unless the allow rule is set to “Override block rules,” which Windows permits only for IPsec-authenticated connections. The screenshot’s Override column reads No throughout, so the block wins.</p>

<h2 id="verification-and-testing"><a class="anchor" href="#verification-and-testing">Verification and testing</a></h2>

<p>The check belongs on a second machine on the same network, where an attacker would stand:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>nmap <span class="nt">-p</span> 445 192.168.X.XX
</code></pre></div></div>

<p>A port blocked by Windows Firewall gives no answer at all, so Nmap should report it as <code class="language-plaintext highlighter-rouge">filtered</code>. <code class="language-plaintext highlighter-rouge">open</code> means the rule is not doing its job, and <code class="language-plaintext highlighter-rouge">closed</code> means something on the host answered with a reset.</p>

<p><a class="img-link" href="/assets/img/firewall-confirmed.webp"><img src="/assets/img/firewall-confirmed.webp" alt="Firewall Confirmation - Port check" width="1827" height="450" loading="lazy" decoding="async"></a>
<em>An Nmap check of ports 80, 443 and 8080 on the host after the change: all three answer closed.</em></p>

<p>The screenshot is of a different check, against ports 80, 443 and 8080. All three came back <code class="language-plaintext highlighter-rouge">closed</code>: the host answered with resets, so it was up, but the scan says nothing about port 445.</p>

<h2 id="what-the-rule-costs"><a class="anchor" href="#what-the-rule-costs">What the rule costs</a></h2>

<p>Blocking inbound 445 on every profile means this machine can no longer share folders or printers. It can still open shares elsewhere, because the rule covers only inbound traffic. For a workstation that serves nothing, that is no loss.</p>

<p>SMBv1, the protocol EternalBlue attacked, is not installed by default on Windows 10 from version 1709 onward; <code class="language-plaintext highlighter-rouge">Get-WindowsOptionalFeature -Online -FeatureName SMB1Protocol</code> in an elevated PowerShell shows whether it lingers on an upgraded machine. Patching still comes first. The firewall rule is for the day patching is late.</p>

<h2 id="sources"><a class="anchor" href="#sources">Sources</a></h2>

<ul>
  <li>Microsoft. Security Bulletin MS17-010, “Security Update for Microsoft Windows SMB Server,” 14 March 2017.</li>
  <li>Microsoft. “Windows Firewall rules” documentation, on rule precedence.</li>
  <li>Microsoft. “SMBv1 is not installed by default in Windows 10 version 1709, Windows Server version 1709 and later versions.”</li>
  <li>National Audit Office. <em>Investigation: WannaCry cyber attack and the NHS</em>. October 2017.</li>
</ul>]]></content><author><name>Securus</name></author><category term="Portfolio" /><category term="Host Security" /><category term="firewall" /><category term="security-plus" /><category term="smb" /><category term="architecture" /><category term="port-control" /><category term="project" /><summary type="html"><![CDATA[Why SMB on port 445 is the door worms walk through, how a host-based Windows Firewall rule closes it, and how to check from outside that the rule holds.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://securus.pages.dev/assets/img/social-preview.png" /><media:content medium="image" url="https://securus.pages.dev/assets/img/social-preview.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Credentials in the clear: what plain HTTP gives away</title><link href="https://securus.pages.dev/posts/intercepting-http/" rel="alternate" type="text/html" title="Credentials in the clear: what plain HTTP gives away" /><published>2025-05-08T00:00:00-04:00</published><updated>2025-05-08T00:00:00-04:00</updated><id>https://securus.pages.dev/posts/intercepting-http</id><content type="html" xml:base="https://securus.pages.dev/posts/intercepting-http/"><![CDATA[<p>In October 2010, at ToorCon in San Diego, Eric Butler released a Firefox extension called Firesheep. On an open Wi-Fi network it collected the session cookies other people’s browsers sent to Facebook, Twitter and a few dozen other sites over plain HTTP, and offered a one-click login as each of them. The attack was as old as those sites. What Firesheep changed was how long the explanation took, and within a few years the large sites had moved to HTTPS. From July 2018 Chrome marked every plain-HTTP page “Not secure.” Plain HTTP did not vanish, though. Much of it moved into software that talks to the network without a window.</p>

<p><a class="img-link" href="/assets/img/Insecure-HTTP.webp"><img src="/assets/img/Insecure-HTTP.webp" alt="Wireshark HTTP Credential Capture" width="1295" height="698" loading="lazy" decoding="async"></a>
<em>A captured HTTP request carrying a username and a password token in clear text.</em></p>

<h2 id="how-it-was-done"><a class="anchor" href="#how-it-was-done">How it was done</a></h2>

<ol>
  <li>Started a Wireshark capture on Wi-Fi.</li>
  <li>Visited <code class="language-plaintext highlighter-rouge">http://neverssl.com</code> to trigger unencrypted HTTP traffic.</li>
  <li>Used the filter <code class="language-plaintext highlighter-rouge">http.request.method == "POST"</code> to isolate form submissions.</li>
  <li>Located the request carrying credentials in plain text.</li>
</ol>

<p>NeverSSL is a page that never redirects to HTTPS, kept so that a laptop behind a captive portal has something plain to load. The POST filter catches form submissions, where a browser login would appear. The request that turned up with credentials was a GET, though, which <code class="language-plaintext highlighter-rouge">http.request.method == "GET"</code>, or simply <code class="language-plaintext highlighter-rouge">http.request</code>, will show.</p>

<h2 id="what-the-capture-showed"><a class="anchor" href="#what-the-capture-showed">What the capture showed</a></h2>

<p>The packet went to port 80 from a background update client for a dynamic DNS service, the kind of small program that tells a DNS provider when a home connection’s address changes. Its request line carried:</p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">username=&lt;account&gt;</code> and <code class="language-plaintext highlighter-rouge">pass=HMAC%7B&lt;key&gt;%3D%7D</code> in the query string</li>
  <li>the HTTP headers, all readable, the client’s name and version among them</li>
</ul>

<p><code class="language-plaintext highlighter-rouge">%7B</code>, <code class="language-plaintext highlighter-rouge">%7D</code> and <code class="language-plaintext highlighter-rouge">%3D</code> are URL-encoded braces and an equals sign, so the password field reads <code class="language-plaintext highlighter-rouge">HMAC{...}</code>, a token rather than a plain password. Over plain HTTP that helps little. Unless the token changes with every request, whoever copies it can replay the request, and to the server a replayed token is as good as the password. A GET is worse than a POST in one more way: the query string is part of the URL, and URLs are written into server and proxy logs.</p>

<p>Anyone on the same network with a capture running could have read these credentials straight off the wire. No exploit, no tool beyond Wireshark, no decryption.</p>

<h2 id="the-point"><a class="anchor" href="#the-point">The point</a></h2>

<p>Plain HTTP forms are a solved problem. The exercise matters because the demonstration is faster than the explanation: read the capture, see the credentials in clear text, and the case for HTTPS everywhere makes itself.</p>

<p>On public Wi-Fi, or any network shared with strangers, the threat is exactly this, a passive listener with a default Wireshark filter. TLS closes the gap because it travels with the request from one end to the other. Other layers cover only part of the path. Wi-Fi encryption protects the radio hop, and on a network with a shared WPA2 password, anyone else who sees a device join can derive that device’s keys. A VPN protects the traffic as far as the VPN’s exit and no further.</p>

<p>In this capture the browser was not the leak. A program nobody was looking at was, and it would have sent a request like this one every time it had an address to report.</p>

<h2 id="sources"><a class="anchor" href="#sources">Sources</a></h2>

<ul>
  <li>Butler, Eric. “Firesheep.” Presented at ToorCon 12, San Diego, October 2010.</li>
  <li>Schechter, Emily. “A secure web is here to stay.” Chromium Blog, February 2018.</li>
  <li>Fielding, R., M. Nottingham and J. Reschke, eds. RFC 9110, “HTTP Semantics.” June 2022.</li>
</ul>]]></content><author><name>Securus</name></author><category term="Portfolio" /><category term="Wireshark" /><category term="http" /><category term="wireshark" /><category term="cleartext" /><category term="network-analysis" /><category term="networking" /><category term="packets" /><category term="project" /><category term="portfolio" /><summary type="html"><![CDATA[A Wireshark capture on Wi-Fi that turned up a username and password token sent over plain HTTP, and why TLS is the only defence that travels with the request.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://securus.pages.dev/assets/img/social-preview.png" /><media:content medium="image" url="https://securus.pages.dev/assets/img/social-preview.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">The TCP handshake, read off the wire</title><link href="https://securus.pages.dev/posts/tcp-handshake/" rel="alternate" type="text/html" title="The TCP handshake, read off the wire" /><published>2025-05-07T00:00:00-04:00</published><updated>2025-05-07T00:00:00-04:00</updated><id>https://securus.pages.dev/posts/tcp-handshake</id><content type="html" xml:base="https://securus.pages.dev/posts/tcp-handshake/"><![CDATA[<p>The handshake was written down in September 1981, in RFC 793, the Transmission Control Protocol specification edited by Jon Postel. When RFC 9293 replaced that document in 2022, gathering forty years of corrections, the handshake came through unchanged.</p>

<p>It takes three packets because each side picks a starting sequence number and each has to hear the other acknowledge it. RFC 793 gives the main reason for the third: without it, an old, delayed request to connect could be mistaken for a new one.</p>

<p><a class="img-link" href="/assets/img/Wireshark-SYN.webp"><img src="/assets/img/Wireshark-SYN.webp" alt="Wireshark TCP Handshake" width="1442" height="506" loading="lazy" decoding="async"></a>
<em>A captured SYN → SYN-ACK → ACK sequence completing a TCP connection, followed by an HTTP request and a redirect.</em></p>

<h2 id="the-capture"><a class="anchor" href="#the-capture">The capture</a></h2>

<p>The capture was taken on Wi-Fi, filtered with <code class="language-plaintext highlighter-rouge">tcp.stream eq 10</code> to show one connection.</p>

<table>
  <thead>
    <tr>
      <th>Packet #</th>
      <th>Type</th>
      <th>Description</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>SYN</td>
      <td>Client initiates connection</td>
    </tr>
    <tr>
      <td>2</td>
      <td>SYN-ACK</td>
      <td>Server acknowledges and replies</td>
    </tr>
    <tr>
      <td>3</td>
      <td>ACK</td>
      <td>Client acknowledges, connection ready</td>
    </tr>
  </tbody>
</table>

<p>Destination: a Google web server, reached over IPv6<br />
Port Used: 80 (HTTP)</p>

<p>The client sends SYN from port 50715, the server answers SYN-ACK, the client answers ACK, and the connection is open. No data moves during the handshake; it is strictly session setup. The first data is the next packet, a <code class="language-plaintext highlighter-rouge">GET / HTTP/1.1</code>, answered with a <code class="language-plaintext highlighter-rouge">301 Moved Permanently</code> redirect.</p>

<p>The packets carry more than flags. Both sides advertise a maximum segment size of 1440 bytes, a 1500-byte frame less 40 bytes of IPv6 header and 20 of TCP header, plus a window scale of 256 and permission for selective acknowledgement. Wireshark shows sequence numbers 0 and 1 because it displays them relative to the connection. The real ones are random 32-bit values, because predictable ones let an attacker forge packets into someone else’s connection.</p>

<h2 id="when-it-goes-wrong"><a class="anchor" href="#when-it-goes-wrong">When it goes wrong</a></h2>

<p>Reading a handshake at the packet level is the difference between knowing the theory and recognising what is wrong on a network. A SYN with no SYN-ACK back is a connectivity problem or a firewall dropping the packet. A SYN answered by a reset means the host is up and nothing is listening on that port.</p>

<p>A storm of SYNs with no completions is the start of a SYN flood. In September 1996 one took the New York provider Panix off the air for days: each half-open connection held a slot until it timed out, and forged SYNs filled the table. Daniel J. Bernstein’s answer, SYN cookies, encodes the connection’s details in the server’s initial sequence number so nothing is stored until the ACK arrives. Linux still ships it as <code class="language-plaintext highlighter-rouge">net.ipv4.tcp_syncookies</code>.</p>

<p>A handshake that completes, then no data, then a RST: something accepted the connection and then refused it, an application or a proxy deciding after the fact.</p>

<p>None of that reads off cleanly from logs. A log records what an application decided. The capture records what was said.</p>

<h2 id="sources"><a class="anchor" href="#sources">Sources</a></h2>

<ul>
  <li>Postel, Jon, ed. RFC 793, “Transmission Control Protocol.” September 1981.</li>
  <li>Eddy, Wesley, ed. RFC 9293, “Transmission Control Protocol (TCP).” August 2022.</li>
  <li>Bernstein, D. J. “SYN cookies.” cr.yp.to, 1996.</li>
</ul>]]></content><author><name>Securus</name></author><category term="Portfolio" /><category term="Wireshark" /><category term="tcp" /><category term="wireshark" /><category term="packets" /><category term="networking" /><category term="project" /><category term="portfolio" /><summary type="html"><![CDATA[Capturing a TCP three-way handshake in Wireshark, reading what each packet carries, and what a broken handshake tells you about a network.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://securus.pages.dev/assets/img/social-preview.png" /><media:content medium="image" url="https://securus.pages.dev/assets/img/social-preview.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">SSH and DNS in a quiet capture</title><link href="https://securus.pages.dev/posts/ssh-dns/" rel="alternate" type="text/html" title="SSH and DNS in a quiet capture" /><published>2025-05-06T00:00:00-04:00</published><updated>2025-05-06T00:00:00-04:00</updated><id>https://securus.pages.dev/posts/ssh-dns</id><content type="html" xml:base="https://securus.pages.dev/posts/ssh-dns/"><![CDATA[<p>When Paul Mockapetris defined the Domain Name System in 1983, in RFCs 882 and 883, it sent questions and answers in the clear, like nearly everything on the network then. Twelve years later Tatu Ylönen found a password sniffer on the Helsinki University of Technology’s network and wrote SSH so that logins would stop crossing the wire readable. A single capture can hold both designs side by side. This one does.</p>

<p><a class="img-link" href="/assets/img/Wireshark-Packet-Capture.webp"><img src="/assets/img/Wireshark-Packet-Capture.webp" alt="Wireshark Screen Capture" class="normal shadow" width="1908" height="722" loading="lazy" decoding="async"></a>
<em>The first fifteen of the capture’s 200 packets in Wireshark.</em></p>

<h2 id="what-the-capture-holds"><a class="anchor" href="#what-the-capture-holds">What the capture holds</a></h2>

<p>The file, <code class="language-plaintext highlighter-rouge">sample.pcap</code>, comes from a virtual machine at <code class="language-plaintext highlighter-rouge">172.21.224.2</code>. Most of its traffic is an SSH session with <code class="language-plaintext highlighter-rouge">35.235.244.34</code>. The VM sends from port 22, so it is the server; the client, on port 35193, sits in the range Google Cloud uses for its Identity-Aware Proxy, the service behind SSH sessions opened from a browser.</p>

<p>In among the SSH packets are DNS lookups. The VM asks for both the A (IPv4) and the AAAA (IPv6) records of <code class="language-plaintext highlighter-rouge">opensource.google.com</code>, and the answers come back with Google’s addresses, <code class="language-plaintext highlighter-rouge">142.250.1.139</code> among them. The resolver it asks is <code class="language-plaintext highlighter-rouge">169.254.169.254</code>, a link-local address; on Google Compute Engine the metadata server at that address also answers DNS. Resolution was working normally.</p>

<h2 id="what-encryption-hides-and-what-it-leaves"><a class="anchor" href="#what-encryption-hides-and-what-it-leaves">What encryption hides, and what it leaves</a></h2>

<p>Multiple TCP ACKs and payloads Wireshark can only label “Encrypted packet” confirm an active session and nothing about its content. But TCP flags and sequence numbers sit outside the encryption, and they are enough to correlate a flow even when the payload is opaque.</p>

<p>Sizes and timing leak too. In 2001 Dawn Song, David Wagner and Xuqing Tian showed that the gaps between packets in an interactive SSH session reveal enough about keystroke timing to narrow the search for a password typed inside it. OpenSSH answered only in version 9.5, in 2023, by sending keystrokes at fixed intervals mixed with decoy packets.</p>

<p>DNS has no cover at all. Every name the VM looked up is readable, and the answers with it; encrypted DNS exists, but most networks still answer in the clear on port 53.</p>

<h2 id="a-baseline"><a class="anchor" href="#a-baseline">A baseline</a></h2>

<p>This is what a quiet system looks like at the packet level: a few lookups, an encrypted session, ordinary TCP bookkeeping. Knowing that picture comes before anything else, because anomaly detection is comparing traffic against a baseline, whatever the tooling calls it.</p>

<h2 id="sources"><a class="anchor" href="#sources">Sources</a></h2>

<ul>
  <li>Mockapetris, P. RFC 882, “Domain Names: Concepts and Facilities,” and RFC 883, “Domain Names: Implementation and Specification.” November 1983.</li>
  <li>Ylönen, Tatu. “SSH: Secure Login Connections over the Internet.” <em>Proceedings of the 6th USENIX Security Symposium</em>, 1996.</li>
  <li>Song, Dawn Xiaodong, David Wagner and Xuqing Tian. “Timing Analysis of Keystrokes and Timing Attacks on SSH.” <em>Proceedings of the 10th USENIX Security Symposium</em>, 2001.</li>
  <li>OpenSSH 9.5 release notes, October 2023.</li>
  <li>Google Cloud. “Using IAP for TCP forwarding” and “Internal DNS” documentation.</li>
</ul>]]></content><author><name>Securus</name></author><category term="Portfolio" /><category term="Wireshark" /><category term="wireshark" /><category term="packets" /><category term="ssh" /><category term="dns" /><category term="portfolio" /><category term="project" /><summary type="html"><![CDATA[Reading a packet capture that holds an encrypted SSH session and plain DNS lookups side by side, and what each one leaves visible.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://securus.pages.dev/assets/img/social-preview.png" /><media:content medium="image" url="https://securus.pages.dev/assets/img/social-preview.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Nmap and the services nobody meant to run</title><link href="https://securus.pages.dev/posts/nmap-scan/" rel="alternate" type="text/html" title="Nmap and the services nobody meant to run" /><published>2025-05-05T00:00:00-04:00</published><updated>2025-05-05T00:00:00-04:00</updated><id>https://securus.pages.dev/posts/nmap-scan</id><content type="html" xml:base="https://securus.pages.dev/posts/nmap-scan/"><![CDATA[<p>In September 1997 the hacker magazine <em>Phrack</em> printed, in its fifty-first issue, “The Art of Port Scanning” by Fyodor, the handle of Gordon Lyon, with the source code of a scanner he called Nmap. Earlier scanners each knew one trick. Nmap put the tricks in one program, and it is still the first thing most people reach for to learn what a machine offers the network.</p>

<p>A service listening on a port is a door, and machines collect doors without anyone deciding to. The scan below was run against a Windows machine on a private network, from that same machine, to see what it had collected.</p>

<p><a class="img-link" href="/assets/img/nmap-scan.webp"><img src="/assets/img/nmap-scan.webp" alt="Nmap Localhost Scan" width="1914" height="984" loading="lazy" decoding="async"></a>
<em>Zenmap’s output for a SYN, version and OS scan of a Windows machine on a home network.</em></p>

<h2 id="the-scan"><a class="anchor" href="#the-scan">The scan</a></h2>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>nmap <span class="nt">-sS</span> <span class="nt">-sV</span> <span class="nt">-O</span> <span class="nt">--open</span> <span class="nt">-T4</span> 192.168.X.XX
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">-sS</code> is the SYN scan, Nmap’s default with administrator rights. It sends the first packet of a TCP handshake and never finishes it: a SYN-ACK means open, a reset means closed, silence usually means a firewall. <code class="language-plaintext highlighter-rouge">-sV</code> talks to each open service until it can name it and its version. <code class="language-plaintext highlighter-rouge">-O</code> compares how the TCP/IP stack answers a set of odd probes against Nmap’s database of known systems. <code class="language-plaintext highlighter-rouge">--open</code> shows only open ports, and <code class="language-plaintext highlighter-rouge">-T4</code> shortens the timing.</p>

<p>The run took 32.63 seconds. Of the thousand ports Nmap checks by default, 994 answered closed. Six were open.</p>

<table>
  <thead>
    <tr>
      <th>Port</th>
      <th>Nmap’s name</th>
      <th>What it is</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>135/tcp</td>
      <td>msrpc</td>
      <td>The Windows RPC endpoint mapper</td>
    </tr>
    <tr>
      <td>139/tcp</td>
      <td>netbios-ssn</td>
      <td>NetBIOS session service, SMB’s older transport</td>
    </tr>
    <tr>
      <td>445/tcp</td>
      <td>microsoft-ds</td>
      <td>SMB directly over TCP</td>
    </tr>
    <tr>
      <td>2179/tcp</td>
      <td>vmrdp</td>
      <td>Hyper-V’s Virtual Machine Connection</td>
    </tr>
    <tr>
      <td>3389/tcp</td>
      <td>ms-wbt-server</td>
      <td>Remote Desktop</td>
    </tr>
    <tr>
      <td>5357/tcp</td>
      <td>http</td>
      <td>Web Services for Devices, used by Windows network discovery</td>
    </tr>
  </tbody>
</table>

<p>Latency was about 0.00036 seconds, at zero hops: the machine was talking to itself. The service probes identified Windows, but OS detection returned only a partial fingerprint with no exact version, which filtering or suppressed replies can cause, and so can a Windows build newer than Nmap’s database.</p>

<p>A plainer scan, <code class="language-plaintext highlighter-rouge">nmap -sV [IP]</code>, against a server found the expected 22 (SSH), 80 (HTTP) and 443 (HTTPS). The view below is from scanme.nmap.org, a host the Nmap project keeps so that people can practise on something they are allowed to scan.</p>

<p><a class="img-link" href="/assets/img/nmap-ports.webp"><img src="/assets/img/nmap-ports.webp" alt="Nmap Ports/Hosts Results" width="961" height="317" loading="lazy" decoding="async"></a>
<em>Open ports on scanme.nmap.org, in Zenmap’s Ports / Hosts view.</em></p>

<h2 id="reading-the-open-ports"><a class="anchor" href="#reading-the-open-ports">Reading the open ports</a></h2>

<p>Remote Desktop on 3389 is a common remote access method and a high-value target: a full graphical login whose protocol has had wormable flaws, such as BlueKeep (CVE-2019-0708) in May 2019. If nobody connects remotely, it should be off; if someone does, it belongs behind a VPN.</p>

<p>SMB on 139 and 445 is the pair WannaCry and NotPetya used in 2017 to cross corporate networks, and the usual route for lateral movement. A <a href="/posts/port-management/">later post</a> closes 445 with a firewall rule.</p>

<p>Port 5357 is easy to miss. Nmap labelled it “Microsoft HTTPAPI httpd 2.0 (SSDP/UPnP),” which names the HTTP server built into Windows, not the service. IANA registers the port as <code class="language-plaintext highlighter-rouge">wsdapi</code>, Web Services for Devices, which Windows network discovery uses, and it can expose device metadata to whoever asks. Port 2179 was open because Hyper-V is enabled.</p>

<h2 id="why-scan-your-own-machine-first"><a class="anchor" href="#why-scan-your-own-machine-first">Why scan your own machine first</a></h2>

<p>Some of those six are needed, some are vestigial defaults, and some should be off entirely. Hardening starts with that list, because nothing can be closed until someone knows it is open.</p>

<p>On a network you are authorised to test, the same approach maps the attack surface before anything else happens. Without that authorisation a scan is a probe of someone else’s systems, which is why scanme.nmap.org exists.</p>

<p>It is the part of reconnaissance nobody skips. On your own machine it costs thirty-three seconds.</p>

<h2 id="sources"><a class="anchor" href="#sources">Sources</a></h2>

<ul>
  <li>Fyodor (Gordon Lyon). “The Art of Port Scanning.” <em>Phrack</em> 51, September 1997.</li>
  <li>Lyon, Gordon. <em>Nmap Network Scanning</em>. Nmap Project, 2009.</li>
  <li>Microsoft. Security Bulletin MS17-010, March 2017.</li>
  <li>NIST National Vulnerability Database. CVE-2019-0708 (BlueKeep).</li>
  <li>IANA. Service Name and Transport Protocol Port Number Registry.</li>
</ul>]]></content><author><name>Securus</name></author><category term="Portfolio" /><category term="Nmap" /><category term="nmap" /><category term="tcp" /><category term="scanning" /><category term="portfolio" /><category term="project" /><summary type="html"><![CDATA[A SYN, version and OS scan of a Windows machine on a home network, what Nmap found listening, and why the first machine worth scanning is your own.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://securus.pages.dev/assets/img/social-preview.png" /><media:content medium="image" url="https://securus.pages.dev/assets/img/social-preview.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry></feed>