New

IT Threat Detection with Vector Search

Notebook


SingleStore Notebooks

IT Threat Detection with Vector Search

Note

This notebook can be run on a Free Starter Cluster. To create a Free Starter Cluster navigate to + using the left nav. You can also use your existing Standard or Premium cluster with this Notebook.

The story: the pen test was Thursday

You are the first security engineer Pemberton Mutual Pet Insurance has ever hired, and it is your first week. Pemberton insures 40,000 cats, dogs and one very expensive tortoise. Customers file claims through the PawPortal, a web app that nobody remembers deploying. On Tuesday you discovered it is literally DVWA, the Damn Vulnerable Web Application, a training app built to be hacked.

Three people want something from you:

  • Gwen Okafor, CFO, wants to cancel the $180,000-a-year security monitoring (SIEM) contract that comes up for renewal on Monday. "We already pay for a database. Can it watch the network?"

  • Dale, who has run IT since 2009, would like everyone to calm down. "Nobody hacks pet insurance."

  • Red Sock Security, the penetration-testing firm Gwen hired, attacked the PawPortal on Thursday and sent you a labelled capture of the day's traffic: every network flow, with the attacks marked. Their contract also says they will come back unannounced once this week. They will tell you which flows were theirs on Monday.

It is Friday morning. This notebook builds a detector from Thursday's answer key, runs it over Friday's traffic as the day unfolds, and grades it when Monday's answers arrive. Everything runs inside SingleStore: no model to train, no packages to install, no data to download into the notebook.

Friday, 7:52 AM
Gwen Okafor (CFO): Monday I either renew the SIEM or I don't. Bring me numbers, not adjectives.

What's in this notebook:

  1. Load Thursday's answer key straight from S3 with a pipeline.

  2. Turn every network flow into a vector, inside the database.

  3. Build a detector out of one SQL statement, and replay Friday through it.

  4. Grade Friday against Monday's labels, at the real attack rate.

  5. Argue with the answer key.

  6. Measure what one JOIN condition is worth.

  7. Wrap up: the memo for Gwen.

  8. Clean up.

The whole notebook runs on a Free Starter Cluster. It loads two million network flows, so the two loading cells and the Friday replay take a few minutes each.

Where the data comes from

The traffic is the CSE-CIC-IDS2018 intrusion-detection dataset from the Communications Security Establishment and the Canadian Institute for Cybersecurity. Researchers ran a small company network on AWS and attacked it, including web attacks on a DVWA server. CICFlowMeter turned the packets into flows: one row per conversation between two machines, with 78 numbers describing it (how long it lasted, how many packets went each way, how big they were, which TCP flags were set). Each row is labelled Benign or with the attack it belongs to.

We use two days of it: Thursday 22 February 2018 and Friday 23 February 2018, about a million flows each, in public files on S3. Pemberton Mutual, Gwen, Dale and Red Sock are made up. The flows are real.

Questions?

Reach out to us through our forum.

Action Required

If you have a Free Starter Cluster deployed already, select the database from the drop-down menu at the top of this notebook. It updates the connection_url to connect to that database.

Create a database for the examples below. On a Standard or Premium Cluster the cell creates pemberton_soc and switches to it. On a Free Starter Cluster it uses the database you selected, because Free Starter Clusters cannot create databases. It keeps an existing database rather than dropping it, because dropping the database a notebook session is using leaves that session with no database.

In [1]:

1shared_tier_check = %sql show variables like 'is_shared_tier'2if not shared_tier_check or shared_tier_check[0][1] == 'OFF':3    %sql CREATE DATABASE IF NOT EXISTS pemberton_soc;4    %sql USE pemberton_soc;5
6current_database = %sql SELECT DATABASE()7DATABASE = current_database[0][0]8if not DATABASE:9    raise RuntimeError('No database selected. On a Free Starter Cluster, pick your database in the '10                       'drop-down menu at the top of this notebook, then run this cell again.')11print(f'Using database {DATABASE}')

1. Load Thursday's answer key straight from S3 with a pipeline.

Red Sock's capture is public: one CSV per day in the CIC-IDS2018 S3 bucket, about 380 MB each. You never download it. A SingleStore pipeline reads the file directly from S3 into a table, and transforms every row on the way in.

First, a few helpers for running SQL from Python. The notebook uses %%sql cells where the SQL is short enough to read, and Python where it builds statements for you.

In [2]:

1import time2
3import singlestoredb as s24
5
6def connect():7    """Open a connection to the notebook's database.8
9    New connections start in whatever database the drop-down menu selects,10    which may be none, so select ``DATABASE`` explicitly.11
12    Returns13    -------14    Connection15        An open connection with ``DATABASE`` selected.16
17    """18    conn = s2.connect()19    with conn.cursor() as cur:20        cur.execute(f'USE {DATABASE}')21    return conn22
23
24def query(sql, args=None):25    """Run one statement on a fresh connection and return its rows.26
27    Parameters28    ----------29    sql : str30        The statement to run.31    args : tuple, optional32        Parameters for the statement.33
34    Returns35    -------36    list of tuple37        The result rows, or an empty list for statements without a result set.38
39    """40    with connect() as conn, conn.cursor() as cur:41        cur.execute(sql, args)42        return list(cur.fetchall()) if cur.description else []

The notebook is safe to run more than once, so start by removing anything a previous run left behind. Pipelines go first, because a table cannot be dropped while a pipeline still loads into it.

In [3]:

1%%sql2DROP PIPELINE IF EXISTS thursday_pipeline;3DROP PIPELINE IF EXISTS friday_pipeline;4DROP VIEW IF EXISTS known_attacks;5DROP TABLE IF EXISTS suspects;6DROP TABLE IF EXISTS scaler;7DROP TABLE IF EXISTS friday;8DROP TABLE IF EXISTS answer_key;

Two small functions

Each flow has 78 numbers, and they live on wildly different scales. A flow's duration is in microseconds and runs into the hundreds of millions; its count of URG flags is 0 or 1. Left alone, duration would drown out everything else. So every number is squashed: take the logarithm, keeping the sign, so a million becomes about 14 and a flag stays below 1. That is plain SQL math, SIGN(x) * LN(1 + ABS(x)), except in two columns, bytes and packets per second, where flows that lasted zero microseconds have Infinity or NaN. The squash function handles those two and turns the oddities into 0.

fix_clock exists because of something you found on Thursday afternoon. Red Sock's timestamps have no AM or PM. The XSS attack Red Sock ran after lunch is stamped 01:51:39. Nothing in the capture happens between 06:00 and 07:59, so any hour before 8 is really in the afternoon.

In [4]:

1query("""2CREATE OR REPLACE FUNCTION squash(x TEXT) RETURNS DOUBLE AS3DECLARE4    v DOUBLE;5BEGIN6    IF x IN ('Infinity', 'NaN', '') THEN7        RETURN 0;8    END IF;9    v = x :> DOUBLE;10    RETURN SIGN(v) * LN(1 + ABS(v));11END12""")13
14query("""15CREATE OR REPLACE FUNCTION fix_clock(ts TEXT) RETURNS DATETIME AS16DECLARE17    t DATETIME = STR_TO_DATE(ts, '%d/%m/%Y %H:%i:%s');18BEGIN19    IF HOUR(t) < 8 THEN20        RETURN t + INTERVAL 12 HOUR;21    END IF;22    RETURN t;23END24""")

The answer key table

One row per flow. Four of the 78 numbers are kept as ordinary columns so you can read them; all 78 go into embedding, a VECTOR(78). The table keeps no other copy of the raw numbers. A Free Starter Cluster has a storage limit, and two million flows times 78 numbers would hit it.

In [5]:

1%%sql2CREATE TABLE answer_key (3    flow_id BINARY(16) NOT NULL,4    flow_ts DATETIME NOT NULL,5    dst_port INT NOT NULL,6    protocol INT NOT NULL,7    flow_duration DOUBLE,8    tot_fwd_pkts DOUBLE,9    tot_bwd_pkts DOUBLE,10    totlen_fwd_pkts DOUBLE,11    label VARCHAR(20) NOT NULL,12    embedding VECTOR(78) NOT NULL,13    SORT KEY (flow_ts),14    SHARD KEY (flow_id)15);

The pipeline

A pipeline statement that names 80 columns is no fun to type, so the next cell builds it from the CSV's header row. Every column lands in a variable such as @flow_duration. The SET clause then gives each flow a unique id with UUID(), fixes the clock, keeps the readable columns, and packs all 78 squashed numbers into the vector.

The squash is written out as plain SQL rather than calling a function 78 times per row: a million rows times 78 calls is slow, while plain math runs in parallel across the cluster.

In [6]:

1import re2
3# The first line of every CIC-IDS2018 "TrafficForML" CSV, verbatim.4CSV_HEADER = (5    'Dst Port,Protocol,Timestamp,Flow Duration,Tot Fwd Pkts,Tot Bwd Pkts,TotLen Fwd Pkts,'6    'TotLen Bwd Pkts,Fwd Pkt Len Max,Fwd Pkt Len Min,Fwd Pkt Len Mean,Fwd Pkt Len Std,'7    'Bwd Pkt Len Max,Bwd Pkt Len Min,Bwd Pkt Len Mean,Bwd Pkt Len Std,Flow Byts/s,Flow Pkts/s,'8    'Flow IAT Mean,Flow IAT Std,Flow IAT Max,Flow IAT Min,Fwd IAT Tot,Fwd IAT Mean,Fwd IAT Std,'9    'Fwd IAT Max,Fwd IAT Min,Bwd IAT Tot,Bwd IAT Mean,Bwd IAT Std,Bwd IAT Max,Bwd IAT Min,'10    'Fwd PSH Flags,Bwd PSH Flags,Fwd URG Flags,Bwd URG Flags,Fwd Header Len,Bwd Header Len,'11    'Fwd Pkts/s,Bwd Pkts/s,Pkt Len Min,Pkt Len Max,Pkt Len Mean,Pkt Len Std,Pkt Len Var,'12    'FIN Flag Cnt,SYN Flag Cnt,RST Flag Cnt,PSH Flag Cnt,ACK Flag Cnt,URG Flag Cnt,CWE Flag Count,'13    'ECE Flag Cnt,Down/Up Ratio,Pkt Size Avg,Fwd Seg Size Avg,Bwd Seg Size Avg,Fwd Byts/b Avg,'14    'Fwd Pkts/b Avg,Fwd Blk Rate Avg,Bwd Byts/b Avg,Bwd Pkts/b Avg,Bwd Blk Rate Avg,'15    'Subflow Fwd Pkts,Subflow Fwd Byts,Subflow Bwd Pkts,Subflow Bwd Byts,Init Fwd Win Byts,'16    'Init Bwd Win Byts,Fwd Act Data Pkts,Fwd Seg Size Min,Active Mean,Active Std,Active Max,'17    'Active Min,Idle Mean,Idle Std,Idle Max,Idle Min,Label'18)19
20
21def snake(name):22    """Turn a CSV column name such as ``Flow Byts/s`` into ``flow_byts_per_s``."""23    return re.sub(r'[^a-z0-9]+', '_', name.lower().replace('/', ' per ')).strip('_')24
25
26COLUMNS = [snake(c) for c in CSV_HEADER.split(',')]27FEATURES = [c for c in COLUMNS if c not in ('timestamp', 'label')]28READABLE = ['flow_duration', 'tot_fwd_pkts', 'tot_bwd_pkts', 'totlen_fwd_pkts']29BUCKET = 'cse-cic-ids2018/Processed Traffic Data for ML Algorithms'30# The only two columns that ever contain Infinity or NaN (flows that lasted 0 microseconds).31MAY_BE_INFINITE = ('flow_byts_per_s', 'flow_pkts_per_s')32assert len(FEATURES) == 7833
34
35def pipeline_sql(name, csv_file, table):36    """Build a pipeline that loads one day of flows straight from S3.37
38    Every CSV column lands in a variable. The ``SET`` clause gives each flow39    a unique id, keeps a few readable columns, and packs all 78 numeric ones,40    squashed, into the ``embedding`` vector. The squash is plain SQL math,41    except for the two columns that can be infinite, which go through42    ``squash()``.43
44    Parameters45    ----------46    name : str47        Pipeline name.48    csv_file : str49        File name inside the public CIC-IDS2018 bucket.50    table : str51        Destination table.52
53    Returns54    -------55    str56        The ``CREATE PIPELINE`` statement.57
58    """59    variables = ', '.join('label' if c == 'label' else f'@{c}' for c in COLUMNS)60    readable = ',\n    '.join(f'{c} = @{c}' for c in READABLE)61    vector = ', '.join(f'squash(@{c})' if c in MAY_BE_INFINITE else f'SIGN(@{c}) * LN(1 + ABS(@{c}))'62                       for c in FEATURES)63    return f'''CREATE PIPELINE {name} AS64LOAD DATA S3 '{BUCKET}/{csv_file}'65CONFIG '{{"region": "ca-central-1"}}'66CREDENTIALS '{{}}'67INTO TABLE {table}68FIELDS TERMINATED BY ','69IGNORE 1 LINES70({variables})71SET flow_id = UNHEX(REPLACE(UUID(), '-', '')),72    flow_ts = fix_clock(@timestamp),73    dst_port = @dst_port,74    protocol = @protocol,75    {readable},76    embedding = CONCAT('[', CONCAT_WS(',', {vector}), ']') :> VECTOR(78)'''

In [7]:

1THURSDAY = 'Thursday-22-02-2018_TrafficForML_CICFlowMeter.csv'2FRIDAY = 'Friday-23-02-2018_TrafficForML_CICFlowMeter.csv'3
4statement = pipeline_sql('thursday_pipeline', THURSDAY, 'answer_key')5print(statement[:700], '...')6query(statement)

FOREGROUND runs the pipeline once, to the end of the file, and returns when it is done. The cell prints how long the million rows took.

Friday, 8:05 AM
Dale (IT): Coffee's on. Nobody hacks pet insurance, by the way.

In [8]:

1started = time.time()2query('START PIPELINE thursday_pipeline FOREGROUND')3print(f'Loaded Thursday in {time.time() - started:.0f} s')

What did Red Sock do on Thursday, and when?

In [9]:

1%%sql2SELECT label,3       COUNT(*) AS flows,4       DATE_FORMAT(MIN(IF(YEAR(flow_ts) = 2018, flow_ts, NULL)), '%H:%i') AS first_seen,5       DATE_FORMAT(MAX(flow_ts), '%H:%i') AS last_seen,6       ROUND(AVG(flow_duration) / 1e6, 1) AS avg_seconds,7       ROUND(AVG(tot_fwd_pkts), 1) AS avg_packets_sent8FROM answer_key9GROUP BY label10ORDER BY flows DESC;

Thursday, 6:40 PM
Red Sock Security: Today's schedule, as promised: web brute force 10:17 to 11:24, cross-site scripting 13:50 to 14:29, SQL injection 16:15 to 16:29. Please find the labelled capture attached.

Lab notes: one in 2,900

Red Sock's attacks are 362 flows out of 1,048,575, about one in 2,900. That ratio is the whole problem: a detector that is wrong about one benign flow in a thousand raises a thousand false alarms a day.

With the clock fixed, the attacks land on Red Sock's schedule to within a few minutes. A stray handful don't: one SQL Injection flow is stamped 11:09, during the brute force, and two at 13:52, during the XSS. Keep that in mind for section 5.

Two more things about Red Sock's file. Nine flows are dated January 1970, which is where computer clocks tend to land when they lose track of time. And 1,048,575 is exactly the number of rows Excel can hold, minus the header. You decide not to ask.

2. Turn every network flow into a vector, inside the database.

Each row of answer_key already holds a vector of 78 squashed numbers. Two more steps make the distance between two vectors mean something:

  1. Standardize every dimension. Subtract Thursday's average for that number and divide by its spread, so a typical flow sits near 0 on every dimension and an unusual one sits a few units away. Now packet counts and timings count equally.

  2. Scale every vector to length 1. Two flows that have the same shape end up in the same place, even if one is a little bigger.

After that, embedding <-> other.embedding (Euclidean distance) is small for flows that behave alike, and close to 0 for near-copies. That is the whole detector: an attack on Friday should land next to Thursday's attacks.

This is the step where most tutorials reach for a neural network. You don't need one here: the 78 numbers already describe a flow, and the database can do the arithmetic.

The scaler

The next cell computes each dimension's average and standard deviation over all of Thursday, and stores them as two vectors: mu and inv_sigma (1 / standard deviation). Ten of the 78 numbers never change in this capture, so their inv_sigma is 0 and they drop out.

It cross-joins the table with the numbers 0 to 77 and pulls out one element at a time with VECTOR_KTH_ELEMENT, so every average is computed in double precision. The shortcut, VECTOR_SUM(embedding), accumulates in 32-bit floats. Over a million rows that drifts in the third digit, and the drift changes from run to run.

In [10]:

1%%sql2CREATE TABLE scaler AS3SELECT CONCAT('[', GROUP_CONCAT(mu ORDER BY i SEPARATOR ','), ']') :> VECTOR(78) AS mu,4       CONCAT('[', GROUP_CONCAT(IF(sigma > 1e-9, 1 / sigma, 0) ORDER BY i SEPARATOR ','), ']') :> VECTOR(78) AS inv_sigma5FROM (6    SELECT d.i,7           AVG(VECTOR_KTH_ELEMENT(a.embedding, d.i)) AS mu,8           STDDEV_POP(VECTOR_KTH_ELEMENT(a.embedding, d.i)) AS sigma9    FROM answer_key a10    CROSS JOIN (SELECT ROW_NUMBER() OVER () - 1 AS i FROM answer_key LIMIT 78) d11    GROUP BY d.i12) per_dimension;

standardize applies both steps to one vector, with the vector functions VECTOR_SUB, VECTOR_MUL and SCALAR_VECTOR_MUL. v <*> v is the dot product of a vector with itself, its length squared.

In [11]:

1query("""2CREATE OR REPLACE FUNCTION standardize(v VECTOR(78), mu VECTOR(78), inv_sigma VECTOR(78)) RETURNS VECTOR(78) AS3DECLARE4    z VECTOR(78) = VECTOR_MUL(VECTOR_SUB(v, mu), inv_sigma);5BEGIN6    RETURN SCALAR_VECTOR_MUL(1 / SQRT(z <*> z), z);7END8""")

In [12]:

1%%sql2UPDATE answer_key JOIN scaler3SET answer_key.embedding = standardize(answer_key.embedding, scaler.mu, scaler.inv_sigma);

Does it work?

Take the first cross-site scripting flow Red Sock sent on Thursday (two went out in the same second; this is the bigger one) and ask for its five nearest neighbours among all 1,048,575 flows. Nothing in the query mentions labels; they are only printed so you can check the answer.

In [13]:

1%%sql2SELECT k.flow_ts, k.dst_port, k.label, ROUND(k.embedding <-> q.embedding, 4) AS distance3FROM answer_key k,4     (SELECT flow_id, embedding FROM answer_key5      WHERE label = 'Brute Force -XSS' ORDER BY flow_ts, tot_fwd_pkts DESC LIMIT 1) q6WHERE k.flow_id <> q.flow_id7ORDER BY distance8LIMIT 5;

Lab notes: five out of a million

All five neighbours are other XSS flows from the same attack, at distances of about 0.01 to 0.05. The query compares the flow with every one of the million rows. There is no index, and on a table this size there doesn't need to be one.

The smaller flow sent in the same second has a different neighbourhood: one XSS flow, then brute force and SQL injection. Every neighbour is still an attack. Change DESC to ASC to see it.

3. Build a detector out of one SQL statement, and replay Friday through it.

Friday's traffic is the second file in the bucket. Load it the same way, into a table shaped like the answer key, and standardize it with Thursday's scaler: on Friday morning, Thursday is all you know.

Friday's file has a label column too, because Red Sock's Monday email is already in it. The detector never reads that column. Section 4 uses it to grade the detector.

In [14]:

1%%sql2CREATE TABLE friday LIKE answer_key;

In [15]:

1query(pipeline_sql('friday_pipeline', FRIDAY, 'friday'))2
3started = time.time()4query('START PIPELINE friday_pipeline FOREGROUND')5print(f'Loaded Friday in {time.time() - started:.0f} s')

In [16]:

1%%sql2UPDATE friday JOIN scaler3SET friday.embedding = standardize(friday.embedding, scaler.mu, scaler.inv_sigma);

The detector

Checking each new flow against a million old ones would work, but it wastes effort: almost every flow is nowhere near an attack. So the detector works in two stages, in one statement:

  1. Is this flow near any known attack? Compare each new flow with Thursday's 362 attacks only, and keep the ones within THRESHOLD of one. These are the suspects. It is a brute-force CROSS JOIN, and cheap, because one side has only 362 rows.

  2. Do its neighbours agree? For each suspect, find its K nearest flows in the whole answer key and count how many are attacks. VOTES or more raises an alert. Only neighbours on the same destination port are compared (k.dst_port = c.dst_port), for a reason section 6 measures.

known_attacks is a view, so it costs no storage. suspects records every suspect with its vote count, and looks_like: the attack type of its closest attacking neighbour.

In [17]:

1%%sql2CREATE VIEW known_attacks AS3SELECT flow_id, flow_ts, dst_port, label, embedding FROM answer_key WHERE label <> 'Benign';4
5CREATE TABLE suspects (6    flow_id BINARY(16) NOT NULL,7    flow_ts DATETIME NOT NULL,8    dst_port INT NOT NULL,9    nearest_attack DOUBLE NOT NULL,10    attack_votes INT NOT NULL,11    looks_like VARCHAR(20),12    SORT KEY (flow_ts),13    SHARD KEY (flow_id)14);

In [18]:

1THRESHOLD = 0.05  # how close a flow must be to a known attack to become a suspect2K = 5             # how many neighbours vote on each suspect3VOTES = 3         # attack votes needed to raise an alert4
5DETECTOR = f'''6INSERT INTO suspects7WITH near AS (8    SELECT f.flow_id, MIN(f.embedding <-> a.embedding) AS nearest_attack9    FROM friday f CROSS JOIN known_attacks a10    WHERE f.flow_ts >= %s AND f.flow_ts < %s11    GROUP BY f.flow_id12    HAVING nearest_attack < {THRESHOLD}13), candidates AS (14    SELECT f.flow_id, f.flow_ts, f.dst_port, f.embedding, near.nearest_attack15    FROM friday f JOIN near ON f.flow_id = near.flow_id16), neighbours AS (17    SELECT c.flow_id, k.label AS neighbour_label,18           ROW_NUMBER() OVER (PARTITION BY c.flow_id ORDER BY c.embedding <-> k.embedding) AS nearness19    FROM candidates c JOIN answer_key k ON k.dst_port = c.dst_port20)21SELECT c.flow_id, c.flow_ts, c.dst_port, c.nearest_attack,22       SUM(n.neighbour_label <> 'Benign') AS attack_votes,23       SUBSTRING_INDEX(GROUP_CONCAT(IF(n.neighbour_label <> 'Benign', n.neighbour_label, NULL)24                                    ORDER BY n.nearness SEPARATOR ','), ',', 1) AS looks_like25FROM candidates c JOIN neighbours n ON n.flow_id = c.flow_id26WHERE n.nearness <= {K}27GROUP BY c.flow_id, c.flow_ts, c.dst_port, c.nearest_attack28'''

Friday, live

A real security operations center (SOC) runs its detector every few minutes on whatever traffic just arrived. The next cell does the same with Friday's capture: it steps a clock through the day in 10-minute slices and runs DETECTOR on each slice as its time comes. Every line is one slice. Alerts show what the suspect flows look like, which is all the SOC knows on Friday.

It takes a few minutes, about as long as a coffee with Dale.

In [19]:

1from datetime import datetime, timedelta2
3SLICE = timedelta(minutes=10)4clock = datetime(2018, 2, 23, 8, 10)5closing_time = datetime(2018, 2, 23, 17, 40)6
7query('TRUNCATE TABLE suspects')8started = time.time()9with connect() as conn, conn.cursor() as cur:10    while clock < closing_time:11        until = clock + SLICE12        cur.execute(DETECTOR, (clock, until))13        cur.execute('SELECT COUNT(*) FROM friday WHERE flow_ts >= %s AND flow_ts < %s', (clock, until))14        flows = cur.fetchone()[0]15        cur.execute(16            'SELECT COUNT(*), COALESCE(SUM(attack_votes >= %s), 0), '17            'GROUP_CONCAT(DISTINCT IF(attack_votes >= %s, looks_like, NULL)) '18            'FROM suspects WHERE flow_ts >= %s AND flow_ts < %s',19            (VOTES, VOTES, clock, until),20        )21        suspects, alerts, kinds = cur.fetchone()22        flag = f'   ALERT: {kinds}' if alerts else ''23        print(f'{clock:%H:%M}  {flows:>7,} flows  {suspects:>3} suspects  {alerts:>3} alerts{flag}', flush=True)24        clock = until25print(f'Replayed Friday in {time.time() - started:.0f} s')

The same day as a picture: alerts per 10 minutes, coloured by what they look like. Hover over a bar for the count.

In [20]:

1import pandas as pd2import plotly.graph_objects as go3
4alerts_by_slot = pd.DataFrame(5    query(f"""6        SELECT FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(flow_ts) / 600) * 600) AS slot, looks_like, COUNT(*) AS alerts7        FROM suspects8        WHERE attack_votes >= {VOTES}9        GROUP BY slot, looks_like10        ORDER BY slot11    """),12    columns=['slot', 'looks_like', 'alerts'],13)14
15COLORS = {'Brute Force -Web': '#2a78d6', 'Brute Force -XSS': '#eb6834', 'SQL Injection': '#1baf7a'}16fig = go.Figure([17    go.Bar(x=rows.slot, y=rows.alerts, name=kind, marker_color=COLORS[kind],18           hovertemplate='%{x|%H:%M}: %{y} alerts<extra>' + kind + '</extra>')19    for kind, rows in alerts_by_slot.groupby('looks_like')20])21fig.update_layout(barmode='stack', bargap=0.15, title='Friday: alerts per 10 minutes',22                  xaxis_title='Friday 23 February 2018', yaxis_title='Alerts', legend_title='Looks like')23fig.show()

Friday, 10:14 AM
Dale (IT): Is something wrong with the PawPortal login page? My mother-in-law says it's slow.

Lab notes: Friday, as it happened

The day is quiet until 10 AM, when brute-force alerts arrive by the dozen for an hour. A second wave runs from 1 PM to just after 2, and a short third one starts at 3 PM. Those are Red Sock's unannounced attacks: the detector found them without being told when they would happen. A handful of single alerts are scattered through the rest of the day. Section 4 finds out which of those were real.

4. Grade Friday against Monday's labels, at the real attack rate.

Monday, 9:02 AM
Red Sock Security: As agreed, we visited on Friday. Labels for the day's capture attached. Did you notice us?

Join every Friday flow to the detector's verdict and count. This is the whole day, every one of 1,048,575 flows, not a sample. That matters: the old way to grade a detector like this is on a test set where a fifth of the rows are attacks, which hides how many false alarms a real day produces.

In [21]:

1%%sql2SELECT f.label,3       COUNT(*) AS flows,4       COALESCE(SUM(s.attack_votes >= 3), 0) AS alerts,5       COUNT(*) - COALESCE(SUM(s.attack_votes >= 3), 0) AS no_alert6FROM friday f LEFT JOIN suspects s ON s.flow_id = f.flow_id7GROUP BY f.label8ORDER BY flows DESC;

In [22]:

1attacks, caught, false_alarms = query(f"""2    SELECT SUM(f.label <> 'Benign'),3           SUM(f.label <> 'Benign' AND s.attack_votes >= {VOTES}),4           SUM(f.label = 'Benign' AND s.attack_votes >= {VOTES})5    FROM friday f LEFT JOIN suspects s ON s.flow_id = f.flow_id6""")[0]7attacks, caught, false_alarms = int(attacks), int(caught or 0), int(false_alarms or 0)8
9print(f'Attacks Red Sock sent:   {attacks}')10print(f'Attacks caught:          {caught}  ({caught / attacks:.0%} recall)')11print(f'False alarms all day:    {false_alarms}')12print(f'Alerts that were real:   {caught / (caught + false_alarms):.1%} precision')

High precision: almost every alert was real, and the false alarms fit on one screen. Recall is another story, and section 5 is about it.

The threshold dial

Why bother with stage 2's vote? Try alerting on nearness alone: any flow within some distance of a known attack. The next query scores every Friday flow against all 362 known attacks in one pass, and counts what three settings of the dial would have flagged.

In [23]:

1%%sql2SELECT IF(f.label = 'Benign', 'benign flows', 'attack flows') AS flows,3       COUNT(*) AS total,4       SUM(d < 0.02) AS within_0_02,5       SUM(d < 0.05) AS within_0_05,6       SUM(d < 0.10) AS within_0_107FROM (8    SELECT f.flow_id, MIN(f.embedding <-> a.embedding) AS d9    FROM friday f CROSS JOIN known_attacks a10    GROUP BY f.flow_id11) nearest12JOIN friday f ON f.flow_id = nearest.flow_id13GROUP BY 1;

Lab notes: alert fatigue

At 0.05, nearness alone flags about a hundred benign flows. At 0.10 it flags tens of thousands. A SOC that gets nearly 50,000 alerts on a Friday doesn't triage them; it turns the detector off. The vote is what turns 100 suspects into a handful of false alarms without losing many real attacks.

The one-pass query compares a million flows with 362 attacks, about 380 million distances, and still finishes in seconds on a Free Starter Cluster.

5. Argue with the answer key.

The detector caught most of Friday's attacks and missed the rest. Before telling Gwen it misses about a third of attacks, look at which ones it missed.

In [24]:

1%%sql2SELECT f.dst_port,3       COUNT(*) AS missed,4       GROUP_CONCAT(DISTINCT f.label) AS labelled_as,5       DATE_FORMAT(MIN(f.flow_ts), '%H:%i') AS first_seen,6       DATE_FORMAT(MAX(f.flow_ts), '%H:%i') AS last_seen7FROM friday f LEFT JOIN suspects s ON s.flow_id = f.flow_id8WHERE f.label <> 'Benign' AND (s.flow_id IS NULL OR s.attack_votes < 3)9GROUP BY f.dst_port10ORDER BY missed DESC;

Every attack Red Sock ran was against the PawPortal, a web server on port 80. Most of the "missed web attacks" never went near port 80:

  • Port 500 is IKE, the key exchange that sets up a VPN tunnel.

  • Port 67 is DHCP, a machine asking for an IP address.

  • Port 22 is SSH. Port 0 is not a real destination port at all.

These look like an attacker's laptop doing ordinary network housekeeping during the test window. The most likely story is that the labels were assigned by machine and time ("everything from the attack laptop between 10:00 and 11:00 is a brute-force attack"), so the laptop's VPN chatter was labelled as a web attack. The detector didn't flag it, because it isn't one.

Monday, 9:31 AM
You: Quick question about Friday: why are 130 of your web-attack flows on port 500?

Monday, 9:48 AM
Red Sock Security: Ah. Our labelling script tags everything from the test laptop during the attack window. That would include its VPN. We'll fix that for next quarter.

So grade the detector on the attacks it could have seen, the ones aimed at the web server:

In [25]:

1web_attacks, web_caught = query(f"""2    SELECT SUM(f.label <> 'Benign'), SUM(f.label <> 'Benign' AND s.attack_votes >= {VOTES})3    FROM friday f LEFT JOIN suspects s ON s.flow_id = f.flow_id4    WHERE f.dst_port = 805""")[0]6web_attacks, web_caught = int(web_attacks), int(web_caught or 0)7print(f'Web attacks (port 80):   {web_attacks}')8print(f'Caught:                  {web_caught}  ({web_caught / web_attacks:.0%} recall)')

And the false alarms: what do they look like?

In [26]:

1%%sql2SELECT s.dst_port,3       COUNT(*) AS false_alarms,4       DATE_FORMAT(MIN(s.flow_ts), '%H:%i') AS first_seen,5       DATE_FORMAT(MAX(s.flow_ts), '%H:%i') AS last_seen,6       ROUND(AVG(f.flow_duration) / 1e6, 2) AS avg_seconds,7       ROUND(AVG(f.tot_fwd_pkts), 1) AS avg_packets_sent8FROM suspects s JOIN friday f ON f.flow_id = s.flow_id9WHERE f.label = 'Benign' AND s.attack_votes >= 310GROUP BY s.dst_port;

Tiny two-packet connections to the web server, spread across the whole day, mostly outside Red Sock's attack windows. They look like the first packets of a login attempt because that is roughly what they are. An analyst can clear them in an afternoon.

One last check: when the detector is right that something is an attack, is it right about which attack?

In [27]:

1%%sql2SELECT f.label AS actually, s.looks_like, COUNT(*) AS alerts3FROM suspects s JOIN friday f ON f.flow_id = s.flow_id4WHERE f.label <> 'Benign' AND s.attack_votes >= 35GROUP BY f.label, s.looks_like6ORDER BY f.label, alerts DESC;

Lab notes: what the detector knows

It is good at "this is an attack" and worse at "which attack". Brute force and XSS mostly look like themselves. SQL injection often looks like brute force, which is fair: both are bursts of form posts to the same login page. Remember the stray SQL injection labels in Thursday's file, too. A detector can only be as precise as its answer key.

6. Measure what one JOIN condition is worth.

Stage 2 of the detector only compares a suspect with answer-key flows on the same destination port: JOIN answer_key k ON k.dst_port = c.dst_port. Take that condition out and every suspect is compared with all million flows. Same detector, one line different: time both on Friday's busiest half hour, 10:00 to 10:30.

Each version runs three times and keeps the fastest, so the first run's query compilation doesn't count.

In [28]:

1WITHOUT_PORT = DETECTOR.replace('JOIN answer_key k ON k.dst_port = c.dst_port', 'CROSS JOIN answer_key k')2assert WITHOUT_PORT != DETECTOR3
4
5def time_detector(sql, start, end, runs=3):6    """Run the detector's SELECT on one time window, without storing anything.7
8    Parameters9    ----------10    sql : str11        A detector statement, starting with ``INSERT INTO suspects``.12    start, end : datetime13        The window of Friday traffic to score.14    runs : int15        How many times to run it; the fastest run is kept.16
17    Returns18    -------19    tuple20        Fastest time in seconds, number of suspects, number of alerts.21
22    """23    select = sql.split('INSERT INTO suspects', 1)[1]24    best = float('inf')25    with connect() as conn, conn.cursor() as cur:26        for _ in range(runs):27            t = time.perf_counter()28            cur.execute(select, (start, end))29            rows = cur.fetchall()30            best = min(best, time.perf_counter() - t)31    return best, len(rows), sum(1 for row in rows if row[4] >= VOTES)32
33
34busiest = (datetime(2018, 2, 23, 10, 0), datetime(2018, 2, 23, 10, 30))35with_port = time_detector(DETECTOR, *busiest)36without_port = time_detector(WITHOUT_PORT, *busiest)37
38for name, (seconds, suspects, alerts) in [('same port only', with_port), ('every flow', without_port)]:39    print(f'{name:15s} {seconds:6.2f} s   {suspects} suspects, {alerts} alerts')40print(f'Comparing with every flow takes {without_port[0] / with_port[0]:.1f}x as long, for the same answer.')

Lab notes: a WHERE clause is a feature

On this data the answer is identical either way: a flow aimed at the web server has web-server flows as its nearest neighbours anyway. The port condition just lets the database skip the 83% of the answer key that is on other ports, so stage 2 does a fraction of the work. In our runs that made the half hour two to four times as fast, depending on the cluster. Stage 1 costs the same either way.

Mixing a vector distance with an ordinary relational condition, in the same statement, against the same table, is the point. There is no separate vector store to keep in sync with the flow table.

The condition is also an assumption. An attack moved to port 8443 would only be compared with history on port 8443, where the answer key has no attacks, so it would never raise an alert. The fix is a better answer key, not a cleverer query.

7. Wrap up: the memo for Gwen.

The memo writes itself from this run's numbers.

In [29]:

1friday_flows = query('SELECT COUNT(*) FROM friday')[0][0]2
3print(f"""To:      Gwen Okafor, CFO4From:    Security5Re:      Can the database watch the network?6
7Red Sock attacked the PawPortal unannounced on Friday. A detector built from Thursday's8labelled capture, running inside our existing database, flagged {caught} of their {attacks} labelled flows.9Of those {attacks}, {attacks - web_attacks} were not attacks on the PawPortal at all (VPN and network housekeeping10mislabelled by Red Sock), so on the web attacks it could see it caught {web_caught} of {web_attacks} ({web_caught / web_attacks:.0%}).11It raised {false_alarms} false alarms out of {friday_flows:,} flows that day.12
13It needed no new software, no model training, and one SQL statement per ten minutes of traffic.14
15Recommendation: renew the SIEM for one year, not three. It also keeps our logs and audit trail,16which this does not. Meanwhile, run this detector alongside it and get Red Sock to label by port as well as by laptop.""")

Monday, 11:20 AM
Gwen Okafor (CFO): One year it is. Numbers, not adjectives. Thank you.

Monday, 11:24 AM
Dale (IT): Fine. Some people hack pet insurance.

What you used

| Feature | What it did here | Use it for | Watch out | |---|---|---|---| | S3 pipelines | Loaded each day's CSV straight from a public bucket, about a million rows per run | Any file feed: CSV, JSON, Parquet, Avro, from S3, GCS, Azure, Kafka | Pipelines can't fill AUTO_INCREMENT columns in parallel; generate ids with UUID() in SET instead | | SET expressions and user-defined functions | Squashed 78 numbers and fixed a broken clock while loading | Cleaning and reshaping data on the way in | A function call per value adds up over a million rows; use plain SQL where you can | | VECTOR(78) | Stored each flow as one vector instead of 78 columns | Embeddings from a model, or any fixed-length list of numbers | Raw numbers on different scales need standardizing first | | Vector functions | Standardized and normalized every vector in SQL | Feature scaling without a round trip to Python | VECTOR_SUM accumulates in 32-bit floats; average large tables per element | | <-> (Euclidean distance) | Found nearest neighbours by brute force, with no index | Exact search; tables of a few million rows | For much larger tables, add a vector index, which needs storage of its own | | Vector distance plus JOIN / WHERE | Compared suspects only with same-port flows | Filtered similarity search in one statement | Every filter is an assumption about where the matches are |

If you want to keep going: load more days of CIC-IDS2018 (the bucket has ten), give the answer key Monday's corrected labels, or swap the replay loop for a pipeline from Kafka so the detector runs on traffic as it arrives.

8. Clean up.

Drop everything the notebook created. On a Standard or Premium Cluster this also drops the pemberton_soc database. On a Free Starter Cluster the database stays, so the tables are dropped one by one.

Space freed on a Free Starter Cluster takes a few minutes to become available again. If you run the notebook again straight away and a load fails with "has reached the configured storage limit", wait a few minutes and rerun that cell.

In [30]:

1%%sql2DROP PIPELINE IF EXISTS thursday_pipeline;3DROP PIPELINE IF EXISTS friday_pipeline;4DROP VIEW IF EXISTS known_attacks;5DROP TABLE IF EXISTS suspects;6DROP TABLE IF EXISTS scaler;7DROP TABLE IF EXISTS friday;8DROP TABLE IF EXISTS answer_key;9DROP FUNCTION IF EXISTS squash;10DROP FUNCTION IF EXISTS fix_clock;11DROP FUNCTION IF EXISTS standardize;

In [31]:

1shared_tier_check = %sql show variables like 'is_shared_tier'2if not shared_tier_check or shared_tier_check[0][1] == 'OFF':3    %sql DROP DATABASE IF EXISTS pemberton_soc;

Details


About this Template

A pet insurer's first security engineer has one weekend to prove the database can watch the network. Load two days of real intrusion-detection traffic from S3 with pipelines, turn every network flow into a vector in SQL, catch a penetration test with a two-stage nearest-neighbour detector, and grade it honestly at the real attack rate.

This Notebook can be run in Shared Tier, Standard and Enterprise deployments.

Tags

starter

See Notebook in action

Launch this notebook in SingleStore and start executing queries instantly.

License

This Notebook has been released under the Apache 2.0 open source license.