fourfifty 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
fourfifty/__init__.py ADDED
File without changes
fourfifty/__main__.py ADDED
@@ -0,0 +1,41 @@
1
+ from collections import Counter
2
+ import argparse
3
+ from fourfifty.simulator import SimConfig, simulate
4
+ from fourfifty.baseline import recipients_per_sender
5
+
6
+ def main():
7
+ parser = argparse.ArgumentParser(description="fourfifty mail traffic simulator")
8
+ parser.add_argument("--duration", type=float, default=600.0)
9
+ parser.add_argument("--seed", type=int, default=42)
10
+ parser.add_argument("--plot", action="store_true", help="save graphs as PNG files")
11
+ args = parser.parse_args()
12
+ config = SimConfig(duration=args.duration,seed=args.seed)
13
+ events = list(simulate(config))
14
+ total = len(events)
15
+ labels = Counter(event.label for event in events)
16
+ print("TOTAL MAIL TRAFFIC BY EVENT TYPE")
17
+ print("-"*32)
18
+ print(f"{'type':<12}{'events':>10}{'share':>10}")
19
+ print("-"*32)
20
+ for label, count in labels.most_common():
21
+ print(f"{label.value:<12}{count:>10,}{count / total:>10.1%}")
22
+ print("-"*32)
23
+ print(f"{'total':<12}{total:>10,}")
24
+ print(f"\n"*3)
25
+ print("TOP SENDERS BY DIFFERENT RECIPIENTS")
26
+ print("-"*44)
27
+ print(f"{'sender':<32}{'recipients':>12}")
28
+ print("-"*44)
29
+ for sender, count in recipients_per_sender(events).most_common(5):
30
+ print(f"{sender:<32}{count:>12,}")
31
+ if args.plot:
32
+ try:
33
+ from fourfifty.plots import plot_total, plot_recipients
34
+ except ImportError:
35
+ print("plotting requires matplotlib: pip install 'fourfifty[plot]'")
36
+ return
37
+ plot_total(events, config, "total.png")
38
+ plot_recipients(events, "recipients.png")
39
+ print("saved graphs: total.png, recipients.png")
40
+ if __name__ == "__main__":
41
+ main()
fourfifty/baseline.py ADDED
@@ -0,0 +1,17 @@
1
+ from collections import Counter, defaultdict
2
+ from fourfifty.simulator import sender_address
3
+
4
+ def emails_per_sender(events):
5
+ counts = Counter(event.mail_from for event in events)
6
+ return counts
7
+
8
+ def recipients_per_sender(events):
9
+ recipients = defaultdict(set)
10
+ for event in events:
11
+ recipients[event.mail_from].add(event.rcpt_to)
12
+ counts = Counter({sender: len(rcpts) for sender, rcpts in recipients.items()})
13
+ return counts
14
+
15
+ def valid_mboxes(config):
16
+ mboxes = {sender_address(k) for k in range(config.n_mailboxes)}
17
+ return mboxes
fourfifty/bloom.py ADDED
@@ -0,0 +1,28 @@
1
+ import hashlib
2
+
3
+ class BloomFilter:
4
+ def __init__(self, m, k):
5
+ self.m = m
6
+ self.k = k
7
+ self.bits = bytearray((m + 7) // 8)
8
+
9
+ def _positions(self, item):
10
+ digest = hashlib.sha256(item.encode()).digest()
11
+ h1 = int.from_bytes(digest[:16], "big")
12
+ h2 = int.from_bytes(digest[16:], "big")
13
+ for i in range(self.k):
14
+ yield (h1+ i * h2) % self.m
15
+
16
+ def add(self, item):
17
+ for pos in self._positions(item):
18
+ byte = pos // 8
19
+ bit = pos % 8
20
+ self.bits[byte] = self.bits[byte] | (1 << bit)
21
+
22
+ def __contains__(self, item):
23
+ for pos in self._positions(item):
24
+ byte = pos // 8
25
+ bit = pos % 8
26
+ if (self.bits[byte] & (1 << bit)) == 0:
27
+ return False
28
+ return True
fourfifty/events.py ADDED
@@ -0,0 +1,19 @@
1
+ from enum import Enum
2
+ from dataclasses import dataclass
3
+
4
+ class Label(Enum):
5
+ NORMAL = "normal"
6
+ RETRY = "retry"
7
+ PROMO = "promo"
8
+ COMPROMISED = "compromised"
9
+ HARVEST = "harvest"
10
+ BOT = "bot"
11
+
12
+ @dataclass(frozen=True, slots=True)
13
+ class Event:
14
+ timestamp: float
15
+ client_ip: str
16
+ mail_from: str
17
+ rcpt_to: str
18
+ message_id: int
19
+ label: Label
fourfifty/plots.py ADDED
@@ -0,0 +1,91 @@
1
+ from collections import Counter
2
+
3
+ import matplotlib
4
+ matplotlib.use("Agg")
5
+ from matplotlib import pyplot as plt
6
+
7
+ from fourfifty.events import Label
8
+ from fourfifty.baseline import recipients_per_sender
9
+
10
+ COLORS = {
11
+ Label.NORMAL: "#2a78d6", # BLUE,
12
+ Label.RETRY: "#eda100", # YELLOW,
13
+ Label.PROMO: "#1baf7a", # AQUA
14
+ Label.COMPROMISED: "#e34948", # RED
15
+ Label.HARVEST: "#eb6834", # ORANGE
16
+ Label.BOT: "#6250d6", # VIOLET
17
+ }
18
+
19
+ def plot_total(events, config, path):
20
+ counts = Counter((event.label, int(event.timestamp / 10)) for event in events)
21
+ windows = range(int(config.duration / 10))
22
+
23
+
24
+
25
+ minutes = [w * 10 / 60 for w in windows]
26
+ shown = [label for label in Label if any(counts[(label, w)] for w in windows)]
27
+ all_ys = [[counts[(label, w)] for w in windows] for label in shown]
28
+
29
+ fig, ax = plt.subplots(figsize=(8, 4), dpi=200)
30
+ ax.stackplot(
31
+ minutes, *all_ys,
32
+ labels=[label.value for label in shown],
33
+ colors=[COLORS[label] for label in shown],
34
+ edgecolor="white", linewidth=0.8,
35
+ )
36
+
37
+ ax.set_title("Total mail traffic by type", loc="left", fontsize=12)
38
+ ax.set_xlabel("time (minutes)")
39
+ ax.set_ylabel("events per 10 s")
40
+ ax.set_xlim(0, config.duration / 60)
41
+ ax.set_ylim(bottom=0)
42
+
43
+ ax.spines[["top", "right"]].set_visible(False)
44
+ ax.grid(axis="y", color="#e5e5e5", linewidth=0.6)
45
+ ax.set_axisbelow(True)
46
+
47
+ ax.legend(frameon=False, ncol=len(shown), loc="upper left", bbox_to_anchor=(0, -0.15))
48
+
49
+ fig.tight_layout()
50
+ fig.savefig(path, bbox_inches="tight")
51
+ plt.close(fig)
52
+
53
+ def plot_recipients(events, path):
54
+ counts = recipients_per_sender(events)
55
+ ranked = counts.most_common()
56
+ harv_rank = news_rank = None
57
+ for i, (sender, count) in enumerate(ranked):
58
+ if sender == "bot@harvest.example":
59
+ harv_rank, harv_count = i + 1, count
60
+ elif sender == "news@letter.example":
61
+ news_rank, news_count = i + 1, count
62
+ else:
63
+ continue
64
+ xs = list(range(1, len(ranked) + 1))
65
+ ys = [n for sender, n in ranked]
66
+
67
+ fig, ax = plt.subplots(figsize=(8, 4), dpi=200)
68
+ ax.scatter(xs, ys, s=4)
69
+ if harv_rank:
70
+ ax.scatter([harv_rank], [harv_count], s=40, color="#eb6834", zorder=3)
71
+ ax.annotate("harvester", xy=(harv_rank, harv_count), xytext=(harv_rank * 1.5, harv_count))
72
+
73
+ if news_rank:
74
+ ax.scatter([news_rank], [news_count], s=40, color="#1baf7a", zorder=3)
75
+ ax.annotate("promo", xy=(news_rank, news_count), xytext=(news_rank * 1.5, news_count))
76
+
77
+ ax.set_yscale("log")
78
+ ax.set_xscale("log")
79
+ ax.set_title("Recipients per sender", loc="left", fontsize=12)
80
+ ax.set_xlabel("sender rank")
81
+ ax.set_ylabel("different recipients")
82
+
83
+ ax.spines[["top", "right"]].set_visible(False)
84
+ ax.grid(color="#e5e5e5", linewidth=0.6)
85
+ ax.set_axisbelow(True)
86
+
87
+ fig.tight_layout()
88
+
89
+
90
+ fig.savefig(path, bbox_inches="tight")
91
+ plt.close(fig)
fourfifty/simulator.py ADDED
@@ -0,0 +1,127 @@
1
+ import dataclasses
2
+ from dataclasses import dataclass
3
+ import random
4
+ import ipaddress
5
+ from ipaddress import IPv4Network
6
+ from itertools import accumulate
7
+ import heapq
8
+ from fourfifty.events import Event, Label
9
+
10
+ BENCHMARK_NETWORK = IPv4Network('198.18.0.0/15')
11
+ @dataclass(frozen=True)
12
+ class SimConfig:
13
+ seed: int = 42
14
+ duration: float = 3600.0
15
+ rate: float = 50.0
16
+ n_senders: int = 10_000
17
+ zipf_s: float = 1.0
18
+ n_mailboxes: int = 20_000
19
+ #alpha
20
+ circle_a: float = 1.0
21
+ #multiplier
22
+ circle_m: float = 3.0
23
+ circle_cap: float = 0.85
24
+ dunbars_n: int = 150
25
+ #harvesters
26
+ harv_speed: float = 25.0
27
+ harv_cap: int = 100_000
28
+ #retries
29
+ retry_chance: float = 0.03
30
+ retry_delay: float = 300.0
31
+ #newsletters
32
+ subscriber_count_big: int = 8_000
33
+ campaign_start: int = 180
34
+ campaign_rate: float = 50.0
35
+
36
+
37
+
38
+ @dataclass(frozen=True, slots=True)
39
+ class Sender:
40
+ ip: str
41
+ address: str
42
+ circle: tuple
43
+
44
+
45
+ def simulate(config):
46
+ rng = random.Random(config.seed)
47
+ clock = 0.0
48
+ message_id = 0
49
+ senders = list()
50
+ mbox_cum_weights = list(accumulate(zipf_weights(config.n_mailboxes, config.zipf_s)))
51
+ for k in rng.sample(range(config.n_mailboxes), config.n_senders):
52
+ circle_size = int(min(rng.paretovariate(config.circle_a) * config.circle_m, config.circle_cap * config.n_mailboxes))
53
+ if circle_size <= config.dunbars_n:
54
+ picked = set(rng.choices(range(config.n_mailboxes), cum_weights=mbox_cum_weights, k=circle_size))
55
+ else:
56
+ picked = rng.sample(range(config.n_mailboxes), k=circle_size)
57
+ sender_circle = tuple(sender_address(m) for m in picked)
58
+ senders.append(Sender(ip=sender_ip(k), address=sender_address(k), circle=sender_circle))
59
+ cum_weights = list(accumulate(zipf_weights(config.n_senders, config.zipf_s)))
60
+ promo_picked = rng.sample(range(config.n_mailboxes), k=config.subscriber_count_big)
61
+ subscriber_circle = tuple(sender_address(m) for m in promo_picked)
62
+ harvester = Sender(
63
+ ip=sender_ip(config.n_mailboxes),
64
+ address='bot@harvest.example',
65
+ circle=()
66
+ )
67
+ promo = Sender(
68
+ ip=sender_ip(config.n_mailboxes+1),
69
+ address='news@letter.example',
70
+ circle = subscriber_circle
71
+ )
72
+ scheduled = []
73
+ for i, subscriber in enumerate(subscriber_circle):
74
+ message_id += 1
75
+ promo_event = Event(
76
+ timestamp=config.campaign_start + i / config.campaign_rate,
77
+ client_ip=promo.ip,
78
+ mail_from=promo.address,
79
+ rcpt_to=subscriber,
80
+ label=Label.PROMO,
81
+ message_id=message_id
82
+ )
83
+
84
+ heapq.heappush(scheduled, (promo_event.timestamp, promo_event))
85
+ while True:
86
+ clock += rng.expovariate(config.rate+config.harv_speed)
87
+ if clock > config.duration:
88
+ return
89
+ while scheduled and scheduled[0][0] <= clock:
90
+ due_time, event = heapq.heappop(scheduled)
91
+ yield event
92
+ if rng.random() < config.harv_speed / (config.rate + config.harv_speed):
93
+ sender = harvester
94
+ rec_n = rng.randrange(0, config.harv_cap)
95
+ receiver = sender_address(rec_n)
96
+ label = Label.HARVEST
97
+ else:
98
+ sender = rng.choices(senders, cum_weights=cum_weights)[0]
99
+ receiver = rng.choice(sender.circle)
100
+ label = Label.NORMAL
101
+ message_id += 1
102
+ current_event = Event(
103
+ timestamp=clock,
104
+ client_ip= sender.ip,
105
+ mail_from= sender.address,
106
+ rcpt_to=receiver,
107
+ message_id=message_id,
108
+ label=label
109
+ )
110
+ yield current_event
111
+ if current_event.label == Label.NORMAL and rng.random() < config.retry_chance:
112
+ retry_event = dataclasses.replace(current_event, timestamp=clock+config.retry_delay, label=Label.RETRY)
113
+ heapq.heappush(scheduled, (retry_event.timestamp, retry_event))
114
+
115
+ def sender_ip(k):
116
+ if k >= BENCHMARK_NETWORK.num_addresses or k < 0:
117
+ raise ValueError(f"Sender index -{k}- doesn't fit in {BENCHMARK_NETWORK}")
118
+ return str(BENCHMARK_NETWORK[k])
119
+
120
+ def sender_address(k):
121
+ return f"user{k}@sender{k}.example"
122
+
123
+ def zipf_weights(n, s):
124
+ weights = list()
125
+ for k in range(n):
126
+ weights.append(1 / (k + 1) ** s)
127
+ return weights
@@ -0,0 +1,115 @@
1
+ Metadata-Version: 2.4
2
+ Name: fourfifty
3
+ Version: 0.1.0
4
+ Summary: Mail traffic simulator and (soon) rate limiter on probabilistic data structures
5
+ Author: AdJakub
6
+ License-Expression: MIT
7
+ Requires-Python: >=3.10
8
+ Description-Content-Type: text/markdown
9
+ Provides-Extra: plot
10
+ Requires-Dist: matplotlib; extra == "plot"
11
+
12
+ # fourfifty
13
+
14
+ ![python](https://img.shields.io/badge/python-3.10%2B-3776AB?logo=python&logoColor=white)
15
+ ![core dependencies](https://img.shields.io/badge/core%20dependencies-0-brightgreen)
16
+ ![status](https://img.shields.io/badge/status-v0.1.0%20%C2%B7%20week%201-orange)
17
+ ![hack club terra](https://img.shields.io/badge/Hack%20Club-Terra-ec3750)
18
+
19
+ ![SMTP](https://img.shields.io/badge/SMTP-450%20try%20again%20later-yellow)
20
+ ![false negatives](https://img.shields.io/badge/false%20negatives-0%20(guaranteed)-brightgreen)
21
+ ![bloom filter](https://img.shields.io/badge/is%20it%20in%20the%20set%3F-probably-blueviolet)
22
+ ![real emails sent](https://img.shields.io/badge/real%20emails%20sent-0-lightgrey)
23
+
24
+ Fourfifty is an email traffic simulator (for now) and an email rate_limiter (soon™️). It works on probabilistic data structures, bloom filter built but not set up for now.
25
+
26
+
27
+ > **Status: week 1 of 2(?).** The traffic simulator, the exact baseline and the Bloom filter is built. Count-Min sketch and HyperLogLog come next.
28
+
29
+ ## Try it
30
+
31
+ ```bash
32
+ pip install -e ".[plot]" # [plot] is optional, only needed for --plot
33
+ fourfifty # 10-minute simulation, prints traffic tables
34
+ fourfifty --duration 300 --seed 7
35
+ fourfifty --plot # also saves total.png and recipients.png
36
+ python -m pytest # run the tests
37
+ ```
38
+
39
+ ```
40
+ TOTAL MAIL TRAFFIC BY EVENT TYPE
41
+ --------------------------------
42
+ type events share
43
+ --------------------------------
44
+ normal 14,969 52.5%
45
+ harvest 7,554 26.5%
46
+ promo 6,000 21.0%
47
+ --------------------------------
48
+ total 28,523
49
+
50
+
51
+
52
+
53
+ TOP SENDERS BY DIFFERENT RECIPIENTS
54
+ --------------------------------------------
55
+ sender recipients
56
+ --------------------------------------------
57
+ bot@harvest.example 7,249
58
+ news@letter.example 6,000
59
+ user4943@sender4943.example 102
60
+ user19103@sender19103.example 54
61
+ user2816@sender2816.example 43
62
+ ```
63
+
64
+
65
+ The harvester and newsletter are the busiest senders, which makes this a challenge for the rate limiter, since it cant go off bursts alone.
66
+ ## What's in it
67
+
68
+ **A traffic simulator with hidden attacks** (`fourfifty/simulator.py`)
69
+
70
+ Real mail corpus has no answer key of which event is which. A simnulation does, so for the rate_limtier to be scored, traffic needs to be simulated.
71
+
72
+ **Features:**
73
+ * 10,000 senders from a pool of 20,000 mailboxes, Zipf-weighted activity
74
+ * every sender has a personal circle of recipients (Pareto-sized, capped at 85% of the pool)
75
+ * traffic types:
76
+ * **normal**: normal email activity
77
+ * **harvest**: guesses addresses. around one in five of them are real.
78
+ * **retry**: a random 3% of normal mail, scheduled out to be sent 5 minutes after
79
+ * **promo**: a newsletter activity burst
80
+ * reproducible
81
+ * IPs from `198.18.0.0/15` (RFC 2544 benchmarking range) and `.example` domains
82
+
83
+ **An exact baseline** (`fourfifty/baseline.py`)
84
+
85
+ the answer key for the rate_limiter
86
+ * `emails_per_sender`: what Count-Min will estimate
87
+ * `recipients_per_sender`: what HyperLogLog will estimate
88
+ * `valid_mboxes`: what the Bloom filter will approximate
89
+
90
+ **A Bloom filter** (`fourfifty/bloom.py`)
91
+
92
+ answers wether an address is real or not. works quick but has false positives.
93
+ * `bytearray` bit storage, SHA-256 and double hashing for `k` positions
94
+ * no false negatives
95
+ * false positive rate with m = 10,000 bits, k = 7, 1,000 items: **0.84%** measured vs **0.82%** expected from theory
96
+
97
+ ## What the traffic looks like
98
+
99
+ ![Total mail traffic by type](https://raw.githubusercontent.com/AdJakub/fourfifty/master/docs/total.png)
100
+
101
+
102
+ The harvesting is steady, as expected. the promotion bursts at minutes 3 to 5. and retries start at minute 5
103
+
104
+
105
+ ![Different recipients per sender](https://raw.githubusercontent.com/AdJakub/fourfifty/master/docs/recipients.png)
106
+
107
+
108
+ HyperLogLog will catch the gap between normal senders and bulk senders, but it wont differentiate between promo and harvest. thats why bloom is needed.
109
+
110
+ ## Roadmap
111
+
112
+ * Count-Min sketch (emails per sender)
113
+ * HyperLogLog (different recipients per sender)
114
+ * scoring harness: sketches vs exact baseline
115
+ * more attack types: compromised accounts & bots
@@ -0,0 +1,12 @@
1
+ fourfifty/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ fourfifty/__main__.py,sha256=Q6u0TIr3T9WBvtnlf7hlfQBCpbtZ-Mut-b6a9dr2L0k,1701
3
+ fourfifty/baseline.py,sha256=eGIF1Ew9_AXGtyggoxSRS4xvbMooYmVUxjumB277yQA,579
4
+ fourfifty/bloom.py,sha256=4khdojrC4M8jkL12_xpEBn6WXpFcEKTafwXGCkIRCrc,843
5
+ fourfifty/events.py,sha256=Ua0RR3gUGnYB5z2Tcdfclim0nIIt6zw5WdrDxEq6Rq8,392
6
+ fourfifty/plots.py,sha256=_4b7D3bY3b8JZIfgl3DVXQ9D6_Gq-hG2LXUZwXkAmBo,3043
7
+ fourfifty/simulator.py,sha256=BhHWiwbWLZF69BkLyfsIsKiY8N-0qKkcMXR2iNfbXGk,4485
8
+ fourfifty-0.1.0.dist-info/METADATA,sha256=V1bKSpIyE-d1WMmwF4P3Lp2ekkvUXsLbvj4vQ9744SE,4580
9
+ fourfifty-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
10
+ fourfifty-0.1.0.dist-info/entry_points.txt,sha256=GMuxurfsQEvgdMZW6Y_ACgenVp6lC4IBCnveQoaZoKk,54
11
+ fourfifty-0.1.0.dist-info/top_level.txt,sha256=_lLXUQQOizYy-Lv7LjkdOUKmKCTZ4SErFw_SUj00hgE,10
12
+ fourfifty-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ fourfifty = fourfifty.__main__:main
@@ -0,0 +1 @@
1
+ fourfifty