TExcelTAD

Zeek Logs with pandas

Signatures answer "did something known happen?". Many investigations start with a different question: "what happened on the network between 19:00 and 20:00, and what is unusual about it?". Zeek (formerly Bro) is built for that. It watches traffic and writes structured, protocol-aware logs: one line per connection in conn.log, one per DNS query in dns.log, plus http.log, ssl.log, files.log, notice.log and dozens more. These logs are compact enough to keep for months and rich enough to answer most "who talked to whom, how, how much" questions without the packets. This lesson reads Zeek logs with pandas, the way a threat hunter does.

The logs below are synthetic, written in Zeek's tab-separated format for the lab network; a Zeek sensor on a tap would produce the same layout (lab session: zeek -r capture.pcap or a live sensor on the server-zone uplink). Zeek can also write JSON, which loads with pd.read_json(..., lines=True).

conn.log

Field Meaning
ts start time (Unix epoch seconds)
uid connection ID, shared by all logs about this connection
id.orig_h, id.orig_p, id.resp_h, id.resp_p originator and responder address and port
proto, service transport protocol and the application protocol Zeek detected (dns, http, ssl, …)
duration, orig_bytes, resp_bytes how long, how much each side sent (payload bytes)
conn_state how the connection went: SF normal, S0 SYN with no reply, REJ rejected, RSTO/RSTR reset, SH, OTH, …
history a letter per event: S SYN, h SYN-ACK, A ACK, D data, F FIN, R RST; upper case from the originator
python · try it yourself
import io
import pandas as pd

CONN = """#separator \\x09
#fields\tts\tuid\tid.orig_h\tid.orig_p\tid.resp_h\tid.resp_p\tproto\tservice\tduration\torig_bytes\tresp_bytes\tconn_state\thistory
1770145200.10\tC1a\t10.10.3.5\t50412\t10.10.1.10\t443\ttcp\tssl\t1.20\t1800\t24000\tSF\tShADadFf
1770145230.55\tC2b\t10.10.1.10\t40111\t10.10.2.30\t5432\ttcp\t-\t0.40\t900\t5200\tSF\tShADadFf
1770145260.00\tC3c\t10.10.3.7\t51000\t10.10.3.21\t445\ttcp\t-\t0.00\t0\t0\tS0\tS
1770145260.02\tC3d\t10.10.3.7\t51001\t10.10.3.22\t445\ttcp\t-\t0.00\t0\t0\tREJ\tSr
1770145260.04\tC3e\t10.10.3.7\t51002\t10.10.3.23\t445\ttcp\t-\t0.00\t0\t0\tS0\tS
1770145260.06\tC3f\t10.10.3.7\t51003\t10.10.3.24\t445\ttcp\t-\t0.00\t0\t0\tS0\tS
1770145260.08\tC3g\t10.10.3.7\t51004\t10.10.3.25\t445\ttcp\tsmb\t0.90\t1200\t800\tSF\tShADadFf
1770145300.00\tC4h\t10.10.2.60\t44321\t198.51.100.44\t443\ttcp\tssl\t3605.00\t1850000000\t95000\tSF\tShADadFf
1770145320.00\tC5i\t10.10.3.5\t53122\t10.10.2.53\t53\tudp\tdns\t0.01\t40\t120\tSF\tDd
1770145380.00\tC6j\t10.10.1.10\t48810\t203.0.113.66\t4444\ttcp\t-\t0.00\t0\t0\tS0\tS
1770145440.00\tC6k\t10.10.1.10\t48822\t203.0.113.66\t4444\ttcp\t-\t0.00\t0\t0\tS0\tS
1770145500.00\tC6l\t10.10.1.10\t48830\t203.0.113.66\t4444\ttcp\t-\t0.00\t0\t0\tS0\tS
"""
lines = [l for l in CONN.splitlines() if not l.startswith("#") or l.startswith("#fields")]
lines[0] = lines[0].replace("#fields\t", "")
conn = pd.read_csv(io.StringIO("\n".join(lines)), sep="\t", na_values="-")
conn["ts"] = pd.to_datetime(conn["ts"], unit="s")
print(conn[["ts", "id.orig_h", "id.resp_h", "id.resp_p", "service", "conn_state"]].head(3)
      .assign(ts=lambda d: d.ts.dt.strftime("%H:%M:%S")).to_string(index=False))
print()

# 1. Scanning: one originator, many responders on one port, mostly failed connections.
scan = (conn.groupby(["id.orig_h", "id.resp_p"])
        .agg(targets=("id.resp_h", "nunique"), failed=("conn_state", lambda s: s.isin(["S0", "REJ"]).sum()))
        .query("targets >= 4"))
print("possible scanning:\n", scan.to_string(), sep="")

# 2. Big uploads: originator sent far more than it received.
conn["ratio"] = conn["orig_bytes"] / conn["resp_bytes"].clip(lower=1)
up = conn[(conn["orig_bytes"] > 100_000_000) & (conn["ratio"] > 100)]
print("\nlarge outbound transfers:")
for r in up.itertuples():
    print(f"  {r._3} -> {r._5}:{r._6} {r.orig_bytes / 1e9:.2f} GB up, {r.duration / 3600:.1f} h, service={r.service}")

# 3. Repeated failed outbound connections at a fixed interval (beaconing).
out = conn[~conn["id.resp_h"].str.startswith("10.") & (conn["conn_state"] == "S0")].sort_values("ts")
for (src, dst, port), g in out.groupby(["id.orig_h", "id.resp_h", "id.resp_p"]):
    gaps = g["ts"].diff().dt.total_seconds().dropna()
    print(f"\nbeacon candidate: {src} -> {dst}:{port}, {len(g)} attempts, intervals {sorted(set(gaps))} s")
      ts  id.orig_h  id.resp_h  id.resp_p service conn_state
19:00:00  10.10.3.5 10.10.1.10        443     ssl         SF
19:00:30 10.10.1.10 10.10.2.30       5432     NaN         SF
19:01:00  10.10.3.7 10.10.3.21        445     NaN         S0

possible scanning:
                     targets  failed
id.orig_h id.resp_p
10.10.3.7 445              5       4

large outbound transfers:
  10.10.2.60 -> 198.51.100.44:443 1.85 GB up, 1.0 h, service=ssl

beacon candidate: 10.10.1.10 -> 203.0.113.66:4444, 3 attempts, intervals [60.0] s

Three stories in twelve lines:

  • 10.10.3.7 touched five workstations on 445 within 80 milliseconds, four times without success: a worm-like scan of the staff network for SMB. (The fifth succeeded: check what it did there.)
  • 10.10.2.60, the file server, uploaded 1.85 GB to an outside address over an hour-long TLS session while receiving almost nothing back: possible exfiltration (or an unapproved cloud backup; find out which).
  • 10.10.1.10, the web server, tried 203.0.113.66:4444 every 60 seconds, the same beacon seen in the firewall drop log of Egress Filtering. Two independent sources agreeing is strong evidence.

dns.log

DNS is where a lot of malicious activity becomes visible: malware resolving its C2 domains, domain-generation algorithms (DGAs) producing many random names that mostly don't exist, and DNS tunnelling, which hides data in long query names.

python · try it yourself
import io, math
from collections import Counter
import pandas as pd

DNS = """ts\tid.orig_h\tquery\tqtype_name\trcode_name
1770145200\t10.10.3.5\twww.lab.test\tA\tNOERROR
1770145201\t10.10.3.5\tmail.lab.test\tA\tNOERROR
1770145210\t10.10.3.9\tqx7rk2vd.example\tA\tNXDOMAIN
1770145211\t10.10.3.9\tpz0ws9lm.example\tA\tNXDOMAIN
1770145212\t10.10.3.9\tbt3nn8ya.example\tA\tNXDOMAIN
1770145213\t10.10.3.9\tl4uey6qc.example\tA\tNXDOMAIN
1770145214\t10.10.3.9\tf9ka2hzo.example\tA\tNOERROR
1770145300\t10.10.1.10\tmzxw6ytboi2dqnbrgqzdgnbv.t.example\tTXT\tNOERROR
1770145302\t10.10.1.10\tgezdgnbvgy3tqojqgeztqnzw.t.example\tTXT\tNOERROR
1770145304\t10.10.1.10\tobqxg43xn5zgiidpmr2gk4tf.t.example\tTXT\tNOERROR
1770145400\t10.10.3.5\tintranet.lab.test\tA\tNOERROR
"""
dns = pd.read_csv(io.StringIO(DNS), sep="\t")

def entropy(s):
    c = Counter(s)
    return -sum(n / len(s) * math.log2(n / len(s)) for n in c.values())

dns["label"] = dns["query"].str.split(".").str[0]
dns["len"] = dns["label"].str.len()
dns["H"] = dns["label"].map(entropy).round(2)

per_host = dns.groupby("id.orig_h").agg(queries=("query", "size"),
                                         nxdomain=("rcode_name", lambda s: (s == "NXDOMAIN").sum()),
                                         max_label=("len", "max"), txt=("qtype_name", lambda s: (s == "TXT").sum()))
print(per_host.to_string())
print()
print(dns[dns["len"] >= 20][["id.orig_h", "query", "qtype_name", "len", "H"]].to_string(index=False))
            queries  nxdomain  max_label  txt
id.orig_h
10.10.1.10        3         0         24    3
10.10.3.5         3         0          8    0
10.10.3.9         5         4          8    0

 id.orig_h                              query qtype_name  len    H
10.10.1.10 mzxw6ytboi2dqnbrgqzdgnbv.t.example        TXT   24 3.97
10.10.1.10 gezdgnbvgy3tqojqgeztqnzw.t.example        TXT   24 3.61
10.10.1.10 obqxg43xn5zgiidpmr2gk4tf.t.example        TXT   24 4.14
  • 10.10.3.9: four NXDOMAIN answers for random-looking eight-character names in seconds, then one that resolves: the pattern of a DGA searching for the domain its operator registered today. The resolving name is the indicator to block and hunt for.
  • 10.10.1.10: TXT queries with 24-character labels of a base32-like alphabet under one parent domain: data encoded in DNS names, the shape of DNS tunnelling. The web server should not even be resolving external names directly.
  • Normal internal lookups are short, repetitive and low in entropy.

Entropy alone is a weak signal (CDN and cloud names look random too); combine it with length, NXDOMAIN rate, record type, the parent domain's age and reputation, and which host asks.

Why logs, not only alerts

Zeek logs let you ask questions after the fact: when a new indicator arrives (a domain, an address, a certificate hash), search months of dns.log, conn.log and ssl.log for it. The uid joins a connection across logs (conn.log + http.log + files.log for "which host downloaded which file from where"). That is threat hunting, covered in depth in the planned Defensive Security course.

Pitfalls

  • Treating orig/resp as "client"/"server" blindly: Zeek decides by who sent the first packet it saw, which can be wrong if the sensor missed the start.
  • Byte counts are payload bytes and can be missing (-) for connections without a clean handshake.
  • Sensors that drop packets under load produce misleading conn_state values; check Zeek's capture_loss.log.
  • Logs with personal data (DNS queries, URLs) need retention rules and access control.

Practice

1. What does conn_state = S0 with history = S mean?

The originator sent a SYN and nothing came back: no SYN-ACK, no RST. A dropped probe, a dead host or a firewall that silently drops (as for the beacon to 4444).

2. Extend the scan detector so it also reports how many distinct *ports* each originator tried against one host (a vertical scan).

conn.groupby(["id.orig_h", "id.resp_h"]).agg(ports=("id.resp_p", "nunique")).query("ports >= 10"). In the sample there is none; the SMB sweep is horizontal (many hosts, one port).

3. The file server's 1.85 GB upload turns out to be the nightly cloud backup. What should change?

Document it: add the destination and schedule to the approved flows (and the egress policy), so the detector can exclude exactly that flow, and alert if the volume, destination or time changes.

Test yourself

Which Zeek field links a connection's entries across conn.log, http.log and files.log?

  1. ts
  2. uid
  3. service
  4. history

What pattern did 10.10.3.9 show in dns.log?

  1. DNS tunnelling
  2. Several NXDOMAINs for random names, then one that resolves: DGA-like behaviour
  3. Normal browsing
  4. Zone transfer

Why is the file server's connection to 198.51.100.44 suspicious?

  1. It used UDP
  2. It uploaded 1.85 GB over an hour while receiving almost nothing
  3. It was rejected
  4. It was DNS

Why is high entropy in a DNS label alone a weak signal?

  1. Entropy is always low
  2. Legitimate CDN and cloud names can also look random
  3. DNS can't be logged
  4. Zeek doesn't log queries