# Copyright 2026 Tailwind Resource Group # SPDX-License-Identifier: Apache-2.0 # Provided as is, with no warranty. License: https://everythingsfine.io/license/ # # emudhra_lib # # Shared procs for eMudhra CA detection on a BIG-IP egress gateway. # Attach to nothing. Other iRules call these as: call /Common/emudhra_lib:: ... # Supported: BIG-IP 17.5 and later. After changing this library, restart TMM: # on 17.5.1.9 a changed proc kept running its old body through every # config-level reload. # # Written for the BIG-IP Tcl 8.4 dialect: no lassign, no {*}, no dict, no "in". # Every parser is bounds-checked; callers still wrap calls in catch so a # malformed handshake can never break the flow (fail open). # # Data group (string, external): dg_emudhra # "cert:" := "BLOCK|label" or "WATCH|label" # "spki:" := "BLOCK|label" or "WATCH|label" # "issuer:" := "BLOCK|label" or "WATCH|label" # spki: catches every variant of a CA cert that shares the key (the weak # intermediates were also cross-signed by Sectigo AAA Certificate Services). # issuer: catches any certificate issued BY that CA, including forged leaves # minted with a recovered key. Build it with build_dg.py. # ---------------------------------------------------------------- primitives proc hexsha {data} { binary scan [sha256 $data] H* h return $h } proc u8 {buf off} { binary scan $buf @${off}c v return [expr {$v & 0xff}] } proc u16 {buf off} { binary scan $buf @${off}S v return [expr {$v & 0xffff}] } proc u24 {buf off} { binary scan $buf @${off}cS a b return [expr {(($a & 0xff) << 16) | ($b & 0xffff)}] } proc sevname {s} { if {$s >= 2} { return "BLOCK" } if {$s == 1} { return "WATCH" } return "CLEAN" } # ---------------------------------------------------------------- DER / X.509 # Returns {tag header_len content_len}; tag -1 on error. proc der_hdr {buf off} { set n [string length $buf] if {$off + 2 > $n} { return [list -1 0 -1] } set tag [call /Common/emudhra_lib::u8 $buf $off] set l0 [call /Common/emudhra_lib::u8 $buf [expr {$off + 1}]] if {$l0 < 0x80} { return [list $tag 2 $l0] } set k [expr {$l0 & 0x7f}] if {$k < 1 || $k > 3 || $off + 2 + $k > $n} { return [list -1 0 -1] } set len 0 for {set i 0} {$i < $k} {incr i} { set len [expr {($len << 8) | [call /Common/emudhra_lib::u8 $buf [expr {$off + 2 + $i}]]}] } return [list $tag [expr {2 + $k}] $len] } # Next DER element at $off that must end at or before $lim. # Returns {tag header_len content_len end}; tag -1 if it does not fit. proc der_next {buf off lim} { foreach {t h l} [call /Common/emudhra_lib::der_hdr $buf $off] break if {$t < 0 || $l < 0} { return [list -1 0 0 0] } set end [expr {$off + $h + $l}] if {$end > $lim} { return [list -1 0 0 0] } return [list $t $h $l $end] } # Raw DER (headers included) of the issuer Name and the SubjectPublicKeyInfo. # Returns {issuer spki}, or {"" ""} unless the certificate is structurally # complete: no signature or path check, but every length must add up. # Certificate ::= SEQ { tbs, signatureAlgorithm SEQ, signature BIT STRING }, nothing after # TBSCertificate ::= SEQ { [0] version?, serial INT, sigAlg SEQ, issuer SEQ (non-empty), # validity SEQ, subject SEQ, spki SEQ (non-empty), [1]? [2]? [3]? } proc tbs_parts {der} { set bad [list "" ""] set n [string length $der] foreach {t h l e} [call /Common/emudhra_lib::der_next $der 0 $n] break if {$t != 0x30 || $e != $n} { return $bad } foreach {t h l tend} [call /Common/emudhra_lib::der_next $der [expr {$h}] $n] break if {$t != 0x30} { return $bad } set off [expr {$tend - $l}] foreach {t h l e} [call /Common/emudhra_lib::der_next $der $off $tend] break if {$t == 0xa0} { set off $e foreach {t h l e} [call /Common/emudhra_lib::der_next $der $off $tend] break } if {$t != 0x02} { return $bad } set off $e foreach {t h l e} [call /Common/emudhra_lib::der_next $der $off $tend] break if {$t != 0x30} { return $bad } set off $e foreach {t h l e} [call /Common/emudhra_lib::der_next $der $off $tend] break if {$t != 0x30 || $l == 0} { return $bad } set issuer [string range $der $off [expr {$e - 1}]] # validity, subject for {set i 0} {$i < 2} {incr i} { set off $e foreach {t h l e} [call /Common/emudhra_lib::der_next $der $off $tend] break if {$t != 0x30} { return $bad } } set off $e foreach {t h l e} [call /Common/emudhra_lib::der_next $der $off $tend] break if {$t != 0x30 || $l == 0} { return $bad } set spki [string range $der $off [expr {$e - 1}]] # Optional issuerUniqueID [1], subjectUniqueID [2], extensions [3]; must end exactly at tend. set off $e while {$off < $tend} { foreach {t h l e} [call /Common/emudhra_lib::der_next $der $off $tend] break if {$t != 0x81 && $t != 0x82 && $t != 0xa1 && $t != 0xa2 && $t != 0xa3} { return $bad } set off $e } # signatureAlgorithm, then signature, ending exactly at the end of the input foreach {t h l e} [call /Common/emudhra_lib::der_next $der $tend $n] break if {$t != 0x30} { return $bad } foreach {t h l e} [call /Common/emudhra_lib::der_next $der $e $n] break if {$t != 0x03 || $e != $n} { return $bad } return [list $issuer $spki] } proc issuer_der {der} { return [lindex [call /Common/emudhra_lib::tbs_parts $der] 0] } # PEM (as returned by X509::whole) to DER. proc der_from_pem {pem} { # "--" is required: a pattern starting with "-" is otherwise read as an option. if {![regexp -- {-----BEGIN CERTIFICATE-----(.*?)-----END CERTIFICATE-----} $pem -> b64]} { return "" } return [b64decode [string map {"\n" "" "\r" "" " " ""} $b64]] } # ---------------------------------------------------------------- matching # Returns {sev label}: 0 none, 1 WATCH, 2 BLOCK. proc dg_tier {key} { set v [class lookup $key /Common/dg_emudhra] if {$v eq ""} { return [list 0 ""] } set p [split $v "|"] set tier [lindex $p 0] set lbl [lindex $p 1] if {$tier eq "BLOCK"} { return [list 2 $lbl] } if {$tier eq "WATCH"} { return [list 1 $lbl] } return [list 0 ""] } # Returns {sev label fp how ok}. how = cert | spki | issuer | "". # ok = 1 when the TBSCertificate walk found both the issuer and the key. proc classify_der {der} { set fp [call /Common/emudhra_lib::hexsha $der] set best 0 set lbl "" set how "" foreach {s l} [call /Common/emudhra_lib::dg_tier "cert:$fp"] break if {$s > $best} { set best $s ; set lbl $l ; set how "cert" } foreach {iss spki} [call /Common/emudhra_lib::tbs_parts $der] break if {$spki ne ""} { foreach {s l} [call /Common/emudhra_lib::dg_tier "spki:[call /Common/emudhra_lib::hexsha $spki]"] break if {$s > $best} { set best $s ; set lbl $l ; set how "spki" } } if {$iss ne ""} { foreach {s l} [call /Common/emudhra_lib::dg_tier "issuer:[call /Common/emudhra_lib::hexsha $iss]"] break if {$s > $best} { set best $s ; set lbl $l ; set how "issuer" } } return [list $best $lbl $fp $how [expr {$iss ne "" && $spki ne ""}]] } # Worst result across a chain (list of DER certs, leaf first). # Data-group matches win. The string backstop ("emSign" or "eMudhra" anywhere in # a cert) only applies when nothing matched the data group: it flags an eMudhra # CA nobody has listed yet, and is never stronger than WATCH. # CLEAN means "every certificate parsed and no configured indicator matched". # An empty chain or an unparseable certificate with no match is UNKNOWN. # Returns: " label= depth= match= fp= certs=" # UNKNOWN adds " reason=" proc classify_chain {ders} { set best 0 set bl "-" set bfp "-" set bd -1 set bhow "-" set sd -1 set sfp "-" set bad 0 set d 0 foreach der $ders { foreach {s l fp how ok} [call /Common/emudhra_lib::classify_der $der] break if {$s > $best} { set best $s ; set bl $l ; set bfp $fp ; set bd $d ; set bhow $how } if {$sd < 0 && ([string first "emSign" $der] >= 0 || [string first "eMudhra" $der] >= 0)} { set sd $d ; set sfp $fp } if {!$ok} { set bad 1 } incr d } if {$best == 0 && $sd >= 0} { set best 1 ; set bl "emudhra-string" ; set bfp $sfp ; set bd $sd ; set bhow "string" } if {$best == 0 && ($d == 0 || $bad)} { if {$d == 0} { set why "empty_chain" } else { set why "bad_cert" } return "UNKNOWN label=- depth=-1 match=- fp=- certs=$d reason=$why" } return "[call /Common/emudhra_lib::sevname $best] label=$bl depth=$bd match=$bhow fp=$bfp certs=$d" } # ---------------------------------------------------------------- TLS parsing # Reassemble the ClientHello handshake message from the client's first bytes. # A valid ClientHello may span several TLS records, so record payloads are # joined until the whole message (4-byte handshake header included) is present. # Returns {OK }, {MORE ""} when more bytes are needed, or {BAD ""}. proc clienthello_msg {p} { set n [string length $p] set hs "" set off 0 while {$off + 5 <= $n} { if {[call /Common/emudhra_lib::u8 $p $off] != 22} { return [list BAD ""] } set rl [call /Common/emudhra_lib::u16 $p [expr {$off + 3}]] if {$off + 5 + $rl > $n} { break } append hs [string range $p [expr {$off + 5}] [expr {$off + 4 + $rl}]] set off [expr {$off + 5 + $rl}] if {[string length $hs] >= 4} { if {[call /Common/emudhra_lib::u8 $hs 0] != 1} { return [list BAD ""] } set need [expr {4 + [call /Common/emudhra_lib::u24 $hs 1]}] if {[string length $hs] >= $need} { return [list OK [string range $hs 0 [expr {$need - 1}]]] } } } return [list MORE ""] } # SNI from the client's first bytes (record headers included), reassembling a # ClientHello split across records. Returns "" when the message is incomplete. proc sni_from_clienthello {p} { foreach {st msg} [call /Common/emudhra_lib::clienthello_msg $p] break if {$st ne "OK"} { return "" } return [call /Common/emudhra_lib::sni_from_hello $msg] } # SNI from a whole ClientHello handshake message (4-byte header included). # Returns a lowercase hostname restricted to [a-z0-9._-], or "". # The restriction matters: the name goes into a sideband request and logs. proc sni_from_hello {p} { set lim [string length $p] if {$lim < 4 || [call /Common/emudhra_lib::u8 $p 0] != 1} { return "" } set o 38 if {$o + 1 > $lim} { return "" } set o [expr {$o + 1 + [call /Common/emudhra_lib::u8 $p $o]}] if {$o + 2 > $lim} { return "" } set o [expr {$o + 2 + [call /Common/emudhra_lib::u16 $p $o]}] if {$o + 1 > $lim} { return "" } set o [expr {$o + 1 + [call /Common/emudhra_lib::u8 $p $o]}] if {$o + 2 > $lim} { return "" } set end [expr {$o + 2 + [call /Common/emudhra_lib::u16 $p $o]}] set o [expr {$o + 2}] if {$end > $lim} { set end $lim } while {$o + 4 <= $end} { set et [call /Common/emudhra_lib::u16 $p $o] set el [call /Common/emudhra_lib::u16 $p [expr {$o + 2}]] if {$et == 0} { if {$o + 9 > $end} { return "" } set nl [call /Common/emudhra_lib::u16 $p [expr {$o + 7}]] if {[call /Common/emudhra_lib::u8 $p [expr {$o + 6}]] != 0 || $o + 9 + $nl > $end} { return "" } set sni [string tolower [string range $p [expr {$o + 9}] [expr {$o + 8 + $nl}]]] if {![regexp {^[a-z0-9._-]{1,253}$} $sni]} { return "" } return $sni } set o [expr {$o + 4 + $el}] } return "" } # 1 if a ServerHello body selects TLS 1.3 (supported_versions = 0x0304). proc sh_is_tls13 {body} { set n [string length $body] set o 34 if {$o + 1 > $n} { return 0 } set o [expr {$o + 1 + [call /Common/emudhra_lib::u8 $body $o] + 3}] if {$o + 2 > $n} { return 0 } set end [expr {$o + 2 + [call /Common/emudhra_lib::u16 $body $o]}] set o [expr {$o + 2}] if {$end > $n} { set end $n } while {$o + 4 <= $end} { set et [call /Common/emudhra_lib::u16 $body $o] set el [call /Common/emudhra_lib::u16 $body [expr {$o + 2}]] if {$et == 43 && $el == 2 && $o + 6 <= $end} { if {[call /Common/emudhra_lib::u16 $body [expr {$o + 4}]] == 0x0304} { return 1 } } set o [expr {$o + 4 + $el}] } return 0 } # List of DER certs from a TLS 1.2 Certificate handshake body. # A malformed list (lengths that do not add up) gets an empty element appended, # so classify_chain cannot call a partial chain CLEAN. proc cert_msg_ders {body} { set ders [list] set n [string length $body] if {$n < 3} { return [list ""] } set end [expr {3 + [call /Common/emudhra_lib::u24 $body 0]}] set ok [expr {$end == $n}] if {$end > $n} { set end $n } set o 3 while {$o + 3 <= $end} { set cl [call /Common/emudhra_lib::u24 $body $o] if {$o + 3 + $cl > $end} { break } lappend ders [string range $body [expr {$o + 3}] [expr {$o + 2 + $cl}]] set o [expr {$o + 3 + $cl}] } if {!$ok || $o != $end} { lappend ders "" } return $ders } # Walks the server's first flight (record headers included). Returns one of: # MORE need more bytes # NOTTLS first record is not a handshake # TLS13 server chose TLS 1.3; the chain is encrypted # NOCERT resumption, PSK or anonymous; no Certificate message # CERT classify_chain result for the chain the server sent proc parse_server_flight {p} { set n [string length $p] if {$n < 5} { return "MORE" } if {[call /Common/emudhra_lib::u8 $p 0] != 22} { return "NOTTLS" } set hs "" set off 0 set other 0 while {$off + 5 <= $n} { set rt [call /Common/emudhra_lib::u8 $p $off] set rl [call /Common/emudhra_lib::u16 $p [expr {$off + 3}]] if {$rt != 22} { set other 1 ; break } if {$off + 5 + $rl > $n} { break } append hs [string range $p [expr {$off + 5}] [expr {$off + 4 + $rl}]] set off [expr {$off + 5 + $rl}] } set ho 0 set hn [string length $hs] while {$ho + 4 <= $hn} { set ht [call /Common/emudhra_lib::u8 $hs $ho] set hl [call /Common/emudhra_lib::u24 $hs [expr {$ho + 1}]] if {$ho + 4 + $hl > $hn} { break } set body [string range $hs [expr {$ho + 4}] [expr {$ho + 3 + $hl}]] if {$ht == 2 && [call /Common/emudhra_lib::sh_is_tls13 $body]} { return "TLS13" } if {$ht == 11} { return "CERT [call /Common/emudhra_lib::classify_chain [call /Common/emudhra_lib::cert_msg_ders $body]]" } if {$ht == 14} { return "NOCERT" } set ho [expr {$ho + 4 + $hl}] } if {$other} { return "NOCERT" } return "MORE" } # ---------------------------------------------------------------- verdicts # Passive and probe observations are separate evidence and are cached separately: # subtable emudhra, key "|passive" or "|probe" # value " label=... depth=... match=... fp=... certs=... [reason=...] ts=" # passive = the chain this gateway saw in a client's own TLS 1.2 handshake. # probe = the chain the destination sent to the BIG-IP's own handshake. It says # what the destination serves, not what a given client received. # Log priority for a severity. proc pri {sev} { if {$sev eq "BLOCK"} { return "<132>" } if {$sev eq "WATCH"} { return "<133>" } return "<134>" } # Cache life of a verdict in seconds. UNKNOWN is short: it only stops a broken # destination from being re-probed on every connection. proc ttl_for {sev} { if {$sev eq "CLEAN"} { return $static::emu_ttl_clean } if {$sev eq "UNKNOWN"} { return $static::emu_ttl_unknown } return $static::emu_ttl_hit } # Cache one observation and log what is new. # event=verdict a non-CLEAN result, once per destination, source, severity and cert # event=change the same source now sees a different severity than before # event=disagree passive and probe disagree for this destination (once per hour) # An UNKNOWN never replaces an earlier real result from the same source. proc record {key verdict src hsl dst port sni} { set sev [lindex $verdict 0] set k "$key|$src" set prev [table lookup -notouch -subtable emudhra $k] set psev [lindex $prev 0] set base "key=$key dst=$dst dport=$port sni=$sni" if {$sev eq "UNKNOWN" && $psev ne "" && $psev ne "UNKNOWN"} { if {[call /Common/emudhra_lib::first_in emudhra_vlog "$k|UNKNOWN" 300]} { HSL::send $hsl "<134>emudhra event=verdict src=$src sev=UNKNOWN mode=$static::emu_mode $base [lrange $verdict 1 end] kept=$psev" } return } set ttl [call /Common/emudhra_lib::ttl_for $sev] table set -subtable emudhra $k "$verdict ts=[clock seconds]" $ttl $ttl if {$psev ne "" && $psev ne $sev} { HSL::send $hsl "[call /Common/emudhra_lib::pri $sev]emudhra event=change src=$src from=$psev to=$sev mode=$static::emu_mode $base [lrange $verdict 1 end]" } elseif {$sev ne "CLEAN"} { set fp "" regexp {fp=([0-9a-f-]+)} $verdict -> fp if {[call /Common/emudhra_lib::first_in emudhra_vlog "$k|$sev|$fp" $ttl]} { HSL::send $hsl "[call /Common/emudhra_lib::pri $sev]emudhra event=verdict src=$src sev=$sev mode=$static::emu_mode $base [lrange $verdict 1 end]" } } if {$src eq "passive"} { set other "probe" } else { set other "passive" } set ov [table lookup -notouch -subtable emudhra "$key|$other"] set osev [lindex $ov 0] if {$osev ne "" && $osev ne "UNKNOWN" && $sev ne "UNKNOWN" && $osev ne $sev} { if {[call /Common/emudhra_lib::first_in emudhra_dislog $key 3600]} { HSL::send $hsl "<132>emudhra event=disagree $src=$sev $other=$osev mode=$static::emu_mode $base" } } } # Effective verdict for a destination. Returns {sev passive probe}. # The worse real observation wins (BLOCK > WATCH > CLEAN), so a probe can never # hide a BLOCK the gateway saw directly. UNKNOWN only when there is nothing else; # "" when nothing is cached. proc verdict_get {key} { set pv [table lookup -notouch -subtable emudhra "$key|passive"] set rv [table lookup -notouch -subtable emudhra "$key|probe"] set best -1 set sev "" foreach v [list $pv $rv] { set s [lindex $v 0] switch -- $s { "BLOCK" { set r 3 } "WATCH" { set r 2 } "CLEAN" { set r 1 } "UNKNOWN" { set r 0 } default { continue } } if {$r > $best} { set best $r ; set sev $s } } return [list $sev $pv $rv] } # Client attribution for the exposure inventory, for anything that is not CLEAN. # Deduplicated per client, destination, severity and evidence class per hour, so # a stronger or more direct observation for the same client is never hidden: # evidence=direct passive: this client's own handshake showed the chain # evidence=indirect cache or probe: the destination is known to serve it proc seen {hsl client key sev src dst port sni} { if {$sev eq "" || $sev eq "CLEAN"} { return } if {$src eq "passive"} { set ev "direct" } else { set ev "indirect" } if {[call /Common/emudhra_lib::first_in emudhra_seen "$client|$key|$sev|$ev" 3600]} { HSL::send $hsl "[call /Common/emudhra_lib::pri $sev]emudhra event=seen client=$client sev=$sev src=$src evidence=$ev mode=$static::emu_mode key=$key dst=$dst dport=$port sni=$sni" } } # Clients that reached a destination while its first probe was in flight. They # are attributed when the probe result (or failure) arrives. At most # emu_pend_max per destination; the rest are counted and logged as a number. proc pend_add {key client} { set sub "emudhra_pend:$key" if {[table keys -count -subtable $sub] >= $static::emu_pend_max} { table incr -subtable emudhra_pendover $key table timeout -subtable emudhra_pendover $key 60 return } table set -subtable $sub $client 1 60 60 } proc pend_flush {hsl key sev src dst port sni} { set sub "emudhra_pend:$key" foreach c [table keys -subtable $sub] { call /Common/emudhra_lib::seen $hsl $c $key $sev $src $dst $port $sni } table delete -subtable $sub -all set over [table lookup -notouch -subtable emudhra_pendover $key] if {$over ne "" && $over > 0 && $sev ne "CLEAN"} { HSL::send $hsl "[call /Common/emudhra_lib::pri $sev]emudhra event=seen_overflow count=$over sev=$sev src=$src mode=$static::emu_mode key=$key dst=$dst dport=$port sni=$sni" } table delete -subtable emudhra_pendover $key } # One probe outcome for a destination: cache it, attribute the initiating client # and any pending clients. Used by the probe virtual and, for local sideband # failures, by the gateway. proc probe_done {key verdict hsl client dst port sni} { call /Common/emudhra_lib::record $key $verdict "probe" $hsl $dst $port $sni # Attribute the probe's own result; a failed probe attributes whatever is # already known about the destination, or UNKNOWN. set sev [lindex $verdict 0] if {$sev eq "UNKNOWN"} { set known [lindex [call /Common/emudhra_lib::verdict_get $key] 0] if {$known ne ""} { set sev $known } } if {$client ne ""} { call /Common/emudhra_lib::seen $hsl $client $key $sev "probe" $dst $port $sni } call /Common/emudhra_lib::pend_flush $hsl $key $sev "probe" $dst $port $sni } # Cache key for a destination: ":::". # $ip may carry "%" as IP::local_addr returns it. The gateway and the probe # virtual must agree. proc dest_key {sni ip port} { set rd 0 set i [string first "%" $ip] if {$i >= 0} { set rd [string range $ip [expr {$i + 1}] end] set ip [string range $ip 0 [expr {$i - 1}]] } if {$sni eq ""} { set sni "-" } return "$rd:$ip:$port:$sni" } # Atomic "first caller wins" across TMMs: 1 for the first caller within # $secs seconds, 0 for everyone else. proc first_in {subtable key secs} { if {[table incr -subtable $subtable $key] == 1} { table timeout -subtable $subtable $key $secs table lifetime -subtable $subtable $key $secs return 1 } return 0 } # Ask the probe virtual to handshake with ip:port (SNI optional). # The probe virtual records and logs the verdict itself (table subtables are # shared across virtuals), so the gateway never has to wait for it. # wait 0: fire and forget. connect + send only; -idle reaps the connection. # wait 1: also read the reply line. Returns the verdict, or "" on any error. # $client is the address of the connection that triggered the probe, so the # probe can attribute its verdict (event=seen) even in async mode. # Returns one of: # SENT async: request delivered; the probe virtual records the result # OK hold: the probe virtual's verdict # REMOTE hold: the probe virtual failed and has recorded UNKNOWN itself # ERR local delivery failure; nothing was recorded, the caller must: # probe_unreachable, probe_send_failed, probe_timeout proc probe {vs ip port sni client tmo wait} { if {$sni eq ""} { set sni "-" } if {[catch {connect -timeout $tmo -idle 15 -status cst $vs} conn] || $conn eq ""} { return "ERR probe_unreachable" } if {[catch {send -timeout $tmo -status sst $conn "PROBE $ip $port $sni $client\n"}]} { catch {close $conn} return "ERR probe_send_failed" } if {!$wait} { return "SENT" } if {[catch {recv -eol -timeout $tmo $conn} resp]} { set resp "" } catch {close $conn} set resp [string trim $resp] if {[string range $resp 0 2] eq "OK "} { return $resp } if {[string range $resp 0 3] eq "ERR "} { return "REMOTE [string range $resp 4 end]" } return "ERR probe_timeout" }