imsi-dataset / pseudoa.py
adulau's picture
Upload pseudoa.py
3dc9373 verified
Raw
History Blame Contribute Delete
22.7 kB
#!/usr/bin/env python3
"""
Format-preserving pseudonymisation for IMSI-catcher observation datasets.
The script keeps the original schema and value shapes:
Input:
Same as output but with the actual original dataset
Output:
{
"_table": "observations",
"stamp": "2020-05-10 15:53:19.961716",
"tmsi1": null,
"tmsi2": null,
"imsi": "734 42 8392018472",
"imsicountry": "Country-734",
"imsibrand": "Brand-128403",
"imsioperator": "Operator-991204",
"mcc": 734,
"mnc": 18,
"lac": 51902,
"cell": 12044
}
Supported input formats:
- NDJSON: one JSON object per line
- JSON array
- concatenated pretty-printed JSON objects
Usage:
export ANON_KEY="$(python3 - <<'PY'
import secrets, base64
print(base64.urlsafe_b64encode(secrets.token_bytes(32)).decode())
PY
)"
python3 fp_anonymise_imsi_catcher.py input.json output.ndjson
Optional:
python3 fp_anonymise_imsi_catcher.py input.json output.ndjson \
--release-id public-2026-01
Notes:
- This is pseudonymisation, not a mathematical guarantee of anonymisation.
- Do not release the secret key.
- Change --release-id between public releases if you do not want linkability
across releases.
Copyright 2026 Alexandre Dulaunoy - foo.be
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
from __future__ import annotations
import argparse
import base64
import hashlib
import hmac
import json
import os
import re
from collections import defaultdict
from collections.abc import Iterator
from typing import Any
SEP = "\x1f"
# ---------------------------------------------------------------------------
# Key and HMAC helpers
# ---------------------------------------------------------------------------
def load_key(env_name: str = "ANON_KEY") -> bytes:
value = os.environ.get(env_name)
if not value:
raise RuntimeError(
f"Missing secret key. Set {env_name}, for example:\n"
" export ANON_KEY=$(python3 -c 'import secrets,base64; "
"print(base64.urlsafe_b64encode(secrets.token_bytes(32)).decode())')"
)
try:
decoded = base64.urlsafe_b64decode(value + "===")
if len(decoded) >= 16:
return decoded
except Exception:
pass
return value.encode("utf-8")
def canonical(value: Any) -> str:
if value is None:
return ""
return str(value).strip()
def hmac_int(
key: bytes,
release_id: str,
domain: str,
values: list[Any],
counter: int,
) -> int:
msg = SEP.join(
[
release_id,
domain,
*[canonical(v) for v in values],
str(counter),
]
)
digest = hmac.new(key, msg.encode("utf-8"), hashlib.sha256).digest()
return int.from_bytes(digest, "big")
class PseudoContext:
"""
Deterministic format-preserving pseudonym generator.
It keeps in-memory maps to avoid collisions inside a given output domain.
"""
def __init__(self, key: bytes, release_id: str):
self.key = key
self.release_id = release_id
self.maps: dict[tuple[Any, ...], int] = {}
self.used: dict[tuple[Any, ...], set[int]] = defaultdict(set)
def int_alias(
self,
domain: str,
identity: list[Any],
min_value: int,
max_value: int,
*,
used_scope: tuple[Any, ...],
) -> int:
if min_value > max_value:
raise ValueError("min_value must be <= max_value")
map_key = (
domain,
tuple(canonical(x) for x in identity),
min_value,
max_value,
used_scope,
)
if map_key in self.maps:
return self.maps[map_key]
span = max_value - min_value + 1
used_values = self.used[(domain, used_scope)]
for counter in range(1_000_000):
candidate = min_value + (
hmac_int(
self.key,
self.release_id,
domain,
[min_value, max_value, *identity],
counter,
)
% span
)
if candidate not in used_values:
self.maps[map_key] = candidate
used_values.add(candidate)
return candidate
raise RuntimeError(
f"Could not allocate collision-free alias for domain={domain!r}"
)
def digits_alias(
self,
domain: str,
identity: list[Any],
width: int,
*,
used_scope: tuple[Any, ...],
allow_zero: bool = True,
) -> str:
min_value = 0 if allow_zero else 1
max_value = (10 ** width) - 1
n = self.int_alias(
domain,
identity,
min_value,
max_value,
used_scope=used_scope,
)
return f"{n:0{width}d}"
def hex_alias(
self,
domain: str,
identity: list[Any],
width: int,
*,
used_scope: tuple[Any, ...],
) -> str:
max_value = (16 ** width) - 1
n = self.int_alias(
domain,
identity,
0,
max_value,
used_scope=used_scope,
)
return f"{n:0{width}X}"
# ---------------------------------------------------------------------------
# Input / output parsing
# ---------------------------------------------------------------------------
def read_json_objects(path: str) -> list[dict[str, Any]]:
"""
Reads:
- JSON array
- NDJSON
- concatenated JSON objects, including pretty-printed ones
"""
with open(path, "r", encoding="utf-8") as f:
text = f.read()
stripped = text.lstrip()
if not stripped:
return []
if stripped.startswith("["):
data = json.loads(stripped)
if not isinstance(data, list):
raise ValueError("JSON root is not a list")
if not all(isinstance(x, dict) for x in data):
raise ValueError("JSON array must contain objects only")
return data
records: list[dict[str, Any]] = []
decoder = json.JSONDecoder()
idx = 0
length = len(text)
while idx < length:
while idx < length and text[idx] in " \t\r\n,":
idx += 1
if idx >= length:
break
obj, end = decoder.raw_decode(text, idx)
if not isinstance(obj, dict):
raise ValueError(f"Expected JSON object, got {type(obj)}")
records.append(obj)
idx = end
return records
def write_ndjson(path: str, records: Iterator[dict[str, Any]]) -> int:
count = 0
with open(path, "w", encoding="utf-8") as f:
for record in records:
f.write(json.dumps(record, ensure_ascii=False, sort_keys=False))
f.write("\n")
count += 1
return count
# ---------------------------------------------------------------------------
# Normalisation helpers
# ---------------------------------------------------------------------------
def clean_digits(value: Any) -> str | None:
if value is None:
return None
s = re.sub(r"\D", "", str(value))
return s or None
def clean_text(value: Any) -> str | None:
if value is None:
return None
s = str(value).strip()
return s or None
def canonical_digits(value: Any) -> str | None:
digits = clean_digits(value)
if digits is None:
return None
stripped = digits.lstrip("0")
return stripped or "0"
def int_like_max(value: Any, default_max: int) -> int:
"""
Preserve integer-like fields while allowing larger spaces if the original
field uses more digits than the default GSM-ish range.
"""
digits = clean_digits(value)
if not digits:
return default_max
try:
n = int(digits)
except ValueError:
return default_max
if n <= default_max:
return default_max
return (10 ** len(digits)) - 1
# ---------------------------------------------------------------------------
# IMSI parsing and formatting
# ---------------------------------------------------------------------------
def parse_imsi(value: Any) -> dict[str, Any]:
"""
Parses IMSI values such as:
"206 05 0004898152"
"208 20 1910430529"
"206050004898152"
For grouped IMSIs, the script preserves the grouping lengths exactly.
"""
if value is None:
return {
"raw": None,
"digits": None,
"home_mcc": None,
"home_mnc": None,
"msin": None,
"grouped": False,
"mnc_width": 2,
"msin_width": 10,
}
raw = str(value).strip()
groups = re.findall(r"\d+", raw)
if len(groups) >= 3 and len(groups[0]) == 3:
home_mcc = groups[0]
home_mnc = groups[1]
msin = "".join(groups[2:])
digits = home_mcc + home_mnc + msin
return {
"raw": raw,
"digits": digits,
"home_mcc": canonical_digits(home_mcc),
"home_mnc": canonical_digits(home_mnc),
"msin": msin,
"grouped": True,
"mnc_width": len(home_mnc),
"msin_width": len(msin),
}
digits = clean_digits(raw)
if not digits or len(digits) < 10:
return {
"raw": raw,
"digits": digits,
"home_mcc": None,
"home_mnc": None,
"msin": None,
"grouped": False,
"mnc_width": 2,
"msin_width": 10,
}
# Fallback for ungrouped IMSI: assume MCC=3 digits, MNC=2 digits.
home_mcc = digits[:3]
home_mnc = digits[3:5]
msin = digits[5:]
return {
"raw": raw,
"digits": digits,
"home_mcc": canonical_digits(home_mcc),
"home_mnc": canonical_digits(home_mnc),
"msin": msin,
"grouped": False,
"mnc_width": len(home_mnc),
"msin_width": len(msin),
}
def pseudo_mcc(ctx: PseudoContext, mcc: Any) -> int | None:
mcc_c = canonical_digits(mcc)
if mcc_c is None:
return None
return ctx.int_alias(
"mcc-v1",
[mcc_c],
100,
999,
used_scope=("mcc",),
)
def pseudo_mnc(
ctx: PseudoContext,
mcc: Any,
mnc: Any,
*,
mnc_width: int,
) -> int | None:
mcc_c = canonical_digits(mcc)
mnc_c = canonical_digits(mnc)
if mcc_c is None or mnc_c is None:
return None
p_mcc = pseudo_mcc(ctx, mcc_c)
# Public JSON mnc is an integer, but IMSI needs zero-padding.
# Most MNCs are represented as 2 or 3 digits in IMSI.
alias_width = 3 if mnc_width >= 3 else 2
return ctx.int_alias(
"mnc-v1",
[mcc_c, mnc_c],
0,
(10 ** alias_width) - 1,
used_scope=("mnc", p_mcc, alias_width),
)
def pseudo_imsi(
ctx: PseudoContext,
value: Any,
) -> str | None:
parts = parse_imsi(value)
if not parts["digits"]:
return None
home_mcc = parts["home_mcc"]
home_mnc = parts["home_mnc"]
if home_mcc is None or home_mnc is None:
# Keep same total digit length if parsing failed.
width = len(parts["digits"])
return ctx.digits_alias(
"imsi-unparsed-v1",
[parts["digits"]],
width,
used_scope=("imsi-unparsed", width),
allow_zero=False,
)
p_mcc = pseudo_mcc(ctx, home_mcc)
p_mnc = pseudo_mnc(
ctx,
home_mcc,
home_mnc,
mnc_width=parts["mnc_width"],
)
if p_mcc is None or p_mnc is None:
return None
p_msin = ctx.digits_alias(
"msin-v1",
[parts["digits"]],
parts["msin_width"],
used_scope=("msin", p_mcc, p_mnc, parts["msin_width"]),
allow_zero=True,
)
p_mcc_s = f"{p_mcc:03d}"
p_mnc_s = f"{p_mnc:0{parts['mnc_width']}d}"
if parts["grouped"]:
return f"{p_mcc_s} {p_mnc_s} {p_msin}"
return f"{p_mcc_s}{p_mnc_s}{p_msin}"
# ---------------------------------------------------------------------------
# Label pseudonyms for country / brand / operator fields
# ---------------------------------------------------------------------------
def pseudo_label(
ctx: PseudoContext,
label_type: str,
identity: list[Any],
*,
prefix: str,
) -> str:
n = ctx.int_alias(
f"{label_type}-label-v1",
identity,
1,
999_999,
used_scope=("label", label_type),
)
return f"{prefix}-{n:06d}"
def pseudo_country_label(
ctx: PseudoContext,
imsi_value: Any,
original_country: Any,
) -> str | None:
if original_country is None:
return None
parts = parse_imsi(imsi_value)
home_mcc = parts["home_mcc"]
p_mcc = pseudo_mcc(ctx, home_mcc) if home_mcc is not None else None
if p_mcc is not None:
return f"Country-{p_mcc:03d}"
return pseudo_label(
ctx,
"country",
[clean_text(original_country)],
prefix="Country",
)
def pseudo_brand_label(
ctx: PseudoContext,
imsi_value: Any,
original_brand: Any,
) -> str | None:
brand = clean_text(original_brand)
if brand is None:
return None
parts = parse_imsi(imsi_value)
return pseudo_label(
ctx,
"brand",
[parts["home_mcc"], parts["home_mnc"], brand],
prefix="Brand",
)
def pseudo_operator_label(
ctx: PseudoContext,
imsi_value: Any,
original_operator: Any,
) -> str | None:
operator = clean_text(original_operator)
if operator is None:
return None
parts = parse_imsi(imsi_value)
return pseudo_label(
ctx,
"operator",
[parts["home_mcc"], parts["home_mnc"], operator],
prefix="Operator",
)
# ---------------------------------------------------------------------------
# TMSI handling
# ---------------------------------------------------------------------------
def clean_tmsi_hex(value: Any) -> str | None:
if value is None:
return None
raw = str(value).strip()
if not raw or raw.lower() == "null":
return None
body = raw[2:] if raw.lower().startswith("0x") else raw
cleaned = re.sub(r"[^0-9A-Fa-f]", "", body).upper()
return cleaned or None
def replace_hex_body_preserving_pattern(raw_value: Any, pseudo_hex: str) -> str:
raw = str(raw_value)
prefix = ""
body = raw
if body.lower().startswith("0x"):
prefix = body[:2]
body = body[2:]
chars = iter(pseudo_hex)
out = []
for ch in body:
if ch in "0123456789abcdefABCDEF":
out.append(next(chars))
else:
out.append(ch)
return prefix + "".join(out)
def pseudo_tmsi(
ctx: PseudoContext,
value: Any,
*,
serving_mcc: Any,
serving_mnc: Any,
lac: Any,
field_name: str,
) -> Any:
if value is None:
return None
raw = str(value).strip()
if not raw or raw.lower() == "null":
return None
scope = [
canonical_digits(serving_mcc),
canonical_digits(serving_mnc),
canonical_digits(lac),
]
# Decimal-looking TMSI: keep decimal digits and width.
if re.fullmatch(r"\d+", raw):
return ctx.digits_alias(
f"{field_name}-tmsi-dec-v1",
[*scope, raw],
len(raw),
used_scope=(field_name, "tmsi-dec", *scope, len(raw)),
allow_zero=True,
)
# Otherwise treat as hex-like and preserve separators / 0x prefix.
cleaned = clean_tmsi_hex(raw)
if cleaned is None:
return None
pseudo_hex = ctx.hex_alias(
f"{field_name}-tmsi-hex-v1",
[*scope, cleaned],
len(cleaned),
used_scope=(field_name, "tmsi-hex", *scope, len(cleaned)),
)
return replace_hex_body_preserving_pattern(raw, pseudo_hex)
# ---------------------------------------------------------------------------
# Serving location pseudonymisation
# ---------------------------------------------------------------------------
def pseudo_serving_fields(
ctx: PseudoContext,
record: dict[str, Any],
) -> tuple[int | None, int | None, int | None, int | None]:
serving_mcc = canonical_digits(record.get("mcc"))
serving_mnc = canonical_digits(record.get("mnc"))
lac = canonical_digits(record.get("lac"))
cell = canonical_digits(record.get("cell"))
p_mcc = pseudo_mcc(ctx, serving_mcc) if serving_mcc is not None else None
p_mnc = (
pseudo_mnc(
ctx,
serving_mcc,
serving_mnc,
mnc_width=len(serving_mnc or "00"),
)
if serving_mcc is not None and serving_mnc is not None
else None
)
if serving_mcc is not None and serving_mnc is not None and lac is not None:
p_lac = ctx.int_alias(
"lac-v1",
[serving_mcc, serving_mnc, lac],
1,
int_like_max(record.get("lac"), 65_535),
used_scope=("lac", p_mcc, p_mnc),
)
else:
p_lac = None
if (
serving_mcc is not None
and serving_mnc is not None
and lac is not None
and cell is not None
):
p_cell = ctx.int_alias(
"cell-v1",
[serving_mcc, serving_mnc, lac, cell],
1,
int_like_max(record.get("cell"), 65_535),
used_scope=("cell", p_mcc, p_mnc, p_lac),
)
else:
p_cell = None
return p_mcc, p_mnc, p_lac, p_cell
# ---------------------------------------------------------------------------
# Main record transformation
# ---------------------------------------------------------------------------
def anonymise_record(
ctx: PseudoContext,
record: dict[str, Any],
*,
keep_home_labels: bool,
) -> dict[str, Any]:
# Copy original record to keep the same schema, ordering, and extra fields.
out = dict(record)
# Do not alter stamp.
# out["stamp"] remains unchanged.
original_imsi = record.get("imsi")
if "imsi" in out:
out["imsi"] = pseudo_imsi(ctx, original_imsi)
if not keep_home_labels:
if "imsicountry" in out:
out["imsicountry"] = pseudo_country_label(
ctx,
original_imsi,
record.get("imsicountry"),
)
if "imsibrand" in out:
out["imsibrand"] = pseudo_brand_label(
ctx,
original_imsi,
record.get("imsibrand"),
)
if "imsioperator" in out:
out["imsioperator"] = pseudo_operator_label(
ctx,
original_imsi,
record.get("imsioperator"),
)
p_mcc, p_mnc, p_lac, p_cell = pseudo_serving_fields(ctx, record)
if "mcc" in out:
out["mcc"] = p_mcc
if "mnc" in out:
out["mnc"] = p_mnc
if "lac" in out:
out["lac"] = p_lac
if "cell" in out:
out["cell"] = p_cell
if "tmsi1" in out:
out["tmsi1"] = pseudo_tmsi(
ctx,
record.get("tmsi1"),
serving_mcc=record.get("mcc"),
serving_mnc=record.get("mnc"),
lac=record.get("lac"),
field_name="tmsi1",
)
if "tmsi2" in out:
out["tmsi2"] = pseudo_tmsi(
ctx,
record.get("tmsi2"),
serving_mcc=record.get("mcc"),
serving_mnc=record.get("mnc"),
lac=record.get("lac"),
field_name="tmsi2",
)
return out
def anonymise_records(
records: list[dict[str, Any]],
*,
key: bytes,
release_id: str,
keep_home_labels: bool,
) -> Iterator[dict[str, Any]]:
ctx = PseudoContext(key, release_id)
for record in records:
yield anonymise_record(
ctx,
record,
keep_home_labels=keep_home_labels,
)
# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------
def main() -> int:
parser = argparse.ArgumentParser(
description=(
"Format-preserving pseudonymisation for IMSI-catcher observations."
)
)
parser.add_argument("input", help="Input JSON / NDJSON file")
parser.add_argument("output", help="Output NDJSON file")
parser.add_argument(
"--release-id",
default="default-release",
help=(
"Domain identifier. Change this between releases if you do not "
"want pseudonyms to be linkable across releases."
),
)
parser.add_argument(
"--keep-home-labels",
action="store_true",
help=(
"Keep imsicountry, imsibrand and imsioperator unchanged. "
"Not recommended for public releases."
),
)
args = parser.parse_args()
key = load_key("ANON_KEY")
records = read_json_objects(args.input)
anonymised = anonymise_records(
records,
key=key,
release_id=args.release_id,
keep_home_labels=args.keep_home_labels,
)
count = write_ndjson(args.output, anonymised)
print(f"Wrote {count} records to {args.output}")
return 0
if __name__ == "__main__":
raise SystemExit(main())