www/squid: remote ACL downloads are not length-checked, so a short HTTP body silently installs a truncated blocklist

Aperta
#5,868 1 commento 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
3/5
Tempo stimato
1-2 giorni
Idoneità per principianti
55/100
Tipo di issue
Bug
Chiarezza
Abbastanza chiara
Stato di attività
Attiva
Stack tecnologico
python
Ambito
networking

Direzione di ricerca

Start in Downloader.fetch() in www/squid/src/opnsense/scripts/proxy/fetchACLs.py, where the loop reads req.raw in 10240-byte chunks and never compares the total with Content-Length. Run the issue's squid_remoteacl_truncation.py reproduction in both modes to see the silent write and the unhandled ProtocolError. Done means a short body is detected, logged via syslog, and leaves the previous ACL file in place, with the no-length case also handled.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

incomplete
Summary

www/squid Remote ACLs can write a silently truncated ACL file. When the HTTP response for a remote ACL is close-delimited (no Content-Length), fetchACLs.py treats a premature connection close as a normal EOF: it writes a partial list to /usr/local/etc/squid/acl/<name>, returns exit status 0, and logs nothing. Squid then loads a blocklist that is short by thousands of domains, and nothing in the GUI or the logs indicates it.

The symmetric case (Content-Length present) is also unhandled: urllib3 raises ProtocolError, the traceback escapes main(), no syslog line is written, and the previous ACL file is left in place and stays in use.

Both paths are "the fetch failed but the proxy keeps running with wrong data, and nobody is told".

How we hit it

Importing a generated dstdomain feed of 156,836 lines / 3,192,564 bytes through forward.acl.remoteACLs.blacklists:

source:       156836 lines / 3192564 bytes
after fetch:  155946 lines / 3176272 bytes   (twice, byte-identical -> deterministic)
last record:  ".zmzh.shr"                    <- cut mid-record
lost:         890 domains, a contiguous tail, covered by no entry or parent suffix

No error in /var/log/squid/, no proxy acl: syslog line, ACL status in the GUI looked fine. We only found it by reconstructing suffix coverage of the source against the fetched file in Python. The list is now loaded through a pre-auth include instead, where it is byte-exact.

Environment: OPNsense 26.7, os-squid 1.5_1 (Squid 7.7), amd64.

Root cause

Downloader.fetch() reads the raw stream to EOF and never cross-checks the result:

https://github.com/opnsense/plugins/blob/master/www/squid/src/opnsense/scripts/proxy/fetchACLs.py#L83-L93

req = requests.get(**req_opts)
if req.status_code == 200:
    req.raw.decode_content = True
    self._source_handle = tempfile.NamedTemporaryFile('wb+', 10240)
    while True:
        data = req.raw.read(10240)
        if not data:
            break
        else:
             self._source_handle.write(data)
    self._source_handle.seek(0)

With close-delimited framing, read() returning b'' is ambiguous — normal end of body and truncated transfer are indistinguishable — and there is no comparison against Content-Length, no req.raw.tell() check, and no sanity check on the record count before the file is replaced. DomainSorter then faithfully sorts and writes whatever arrived, including the half-written final record, which Squid loads as a real dstdomain entry.

To be precise about attribution: we initially suspected DomainSorter's temp-bucket flush, and that is not the cause. Replaying our full 156,836-line list through DomainSorter offline, and through the whole script over a clean local HTTP server, loses zero domains (only the two # header lines, correctly, as comments). The loss is entirely in the unverified download.

Reproduction

Self-contained, no OPNsense box needed — it fetches the current fetchACLs.py from master, redirects acl_config_fn / acl_target_dir into a temp dir, serves 20,000 synthetic domains over 127.0.0.1 and cuts the body short:

squid_remoteacl_truncation.py
#!/usr/bin/env python3
import socket, threading, os, re, sys, tempfile, urllib.request

URL = ('https://raw.githubusercontent.com/opnsense/plugins/master/'
       'www/squid/src/opnsense/scripts/proxy/fetchACLs.py')
MODE = sys.argv[1] if len(sys.argv) > 1 else 'no-length'

N = 20000
DOMAINS = ['host%05d.example.test' % i for i in range(N)]
BODY = ('\n'.join(DOMAINS) + '\n').encode()
CUT = len(BODY) - 16292                      # cut the tail, mid-record


def serve(sock):
    conn, _ = sock.accept()
    conn.recv(65536)
    h = 'HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n'
    if MODE == 'content-length':
        h += 'Content-Length: %d\r\n' % len(BODY)
    h += 'Connection: close\r\n\r\n'
    conn.sendall(h.encode() + BODY[:CUT])    # short body, then close
    conn.close(); sock.close()


work = tempfile.mkdtemp(prefix='squidacl-')
acl = os.path.join(work, 'acl'); os.makedirs(acl)
sock = socket.socket(); sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('127.0.0.1', 0)); port = sock.getsockname()[1]; sock.listen(1)
threading.Thread(target=serve, args=(sock,), daemon=True).start()

cfg = os.path.join(work, 'externalACLs.conf')
open(cfg, 'w').write('[testlist]\nurl=http://127.0.0.1:%d/list\nenabled=1\n' % port)

script = urllib.request.urlopen(URL).read().decode()
script = script.replace("acl_config_fn = '/usr/local/etc/squid/externalACLs.conf'",
                        "acl_config_fn = %r" % cfg)
script = script.replace("acl_target_dir = '/usr/local/etc/squid/acl'",
                        "acl_target_dir = %r" % acl)
script = re.sub(r'^main\(\)\s*$', '', script, flags=re.M)

logged = []
ns = {'__name__': 'under_test'}
exec(compile(script, 'fetchACLs.py', 'exec'), ns)
ns['syslog'].syslog = lambda *a, **k: logged.append(a)

outcome = 'returned normally (exit 0)'
try:
    ns['main']()
except Exception as e:
    outcome = 'UNHANDLED %s: %s' % (type(e).__name__, e)

print('mode                    :', MODE)
print('body offered/delivered  : %d / %d bytes' % (len(BODY), CUT))
print('main() outcome          :', outcome)
print('syslog messages         :', logged or 'NONE')

target = os.path.join(acl, 'testlist')
if not os.path.exists(target):
    print('ACL file                : NOT CREATED (a stale ACL would stay in use)')
    raise SystemExit(0)

lines = [l.rstrip('\n') for l in open(target, encoding='utf-8', errors='ignore') if l.strip()]
have = {l.lstrip('.') for l in lines}
lost = [d for d in DOMAINS if d not in have]
malformed = [l for l in lines if not re.fullmatch(r'\.host\d{5}\.example\.test', l)]
print('input domains           :', N)
print('ACL records written     :', len(lines))
print('domains LOST silently   :', len(lost))
print('malformed records       : %s  %r' % (len(malformed), malformed))

Output:

$ python3 squid_remoteacl_truncation.py no-length
mode                    : no-length
body offered/delivered  : 460000 / 443708 bytes
main() outcome          : returned normally (exit 0)
syslog messages         : NONE
input domains           : 20000
ACL records written     : 19292
domains LOST silently   : 709
malformed records       : 1  ['.host19291.examp']

$ python3 squid_remoteacl_truncation.py content-length
mode                    : content-length
body offered/delivered  : 460000 / 443708 bytes
main() outcome          : UNHANDLED ProtocolError: ('Connection broken: IncompleteRead(443708 bytes read, 16292 more expected)', IncompleteRead(443708 bytes read, 16292 more expected))
syslog messages         : NONE
ACL file                : NOT CREATED (a stale ACL would stay in use)

.host19291.examp is the same shape of artefact as the .zmzh.shr we saw in production.

Expected

A remote ACL fetch that did not deliver the whole list should fail loudly and leave the previous ACL untouched, rather than install a partial one.

Suggestions, in rough order of value:

  1. Compare what was read against Content-Length when the header is present, and syslog(LOG_ERR, ...) + abandon the section when it does not match (instead of the current unhandled ProtocolError). Using requests' own iter_content() rather than req.raw.read() already gets this check for free.
  2. Write to a temp file and os.replace() into acl_target_dir only on success, so a failed fetch can never replace a good list with a partial one.
  3. Log the record count actually written per section (proxy acl: <section>: N entries). Even with no other change this makes the failure visible — a list dropping from 156,836 to 155,946 would have been obvious.
  4. Optionally reject close-delimited responses for ACL downloads, or warn when no Content-Length was offered, since truncation is undetectable in that case.
Smaller things found while testing the same path

Not bugs we need fixed, but each cost us time and might be worth a line of documentation or a GUI hint:

  • A remote ACL URL whose basename extension is txt, pdf or doc is silently skipped by filename_in_ignorelist() and yields an empty ACL file. blocklist.txt is a very natural name for a domain list, and the resulting empty ACL looks exactly like a successful fetch of an empty feed.
  • file:// URLs are not supported (Downloader.fetch() handles only http/https/ftp). The "unsupported protocol" message goes to syslog, but the ACL file is still created empty, so the GUI shows no problem.
  • The filename and description field masks in ACL.xml reject hyphens, which is surprising for list names like my-blocklist.
Lingua principale
PHP
Stelle
1.2k
Fork
932
Merge medio
1g 11h
PR unite (30g)
22

Preparare l'ambiente

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di opnsense/plugins

Tutte le issue di opnsense/plugins

Issue simili

Altre issue su PHP

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.