MaskDump is a powerful tool for database anonymization and data masking designed to protect Personally Identifiable Information (PII) in database dumps. It provides secure PII obfuscation while maintaining data structure and format integrity.
Key features:
- Email and phone number masking with configurable algorithms
- White-list support for preserving specific values
- Caching system for consistent masking across multiple runs
- Regular expression customization for different data formats
- Pipeline-friendly design for integration with existing workflows
Use cases:
- Creating safe development/test environments from production data
- GDPR/CCPA compliance for data sharing
- Database sanitization before analytics processing
- Data masking for non-production environments
Comments on the project can be left here
1. Two Operation Modes:
- Full File Processing - works with any text files (SQL dumps, CSV, logs, etc.)
- Selective Processing - masks only specified tables and fields (configured in
masking_tables)
2. Table Filtering
skip_table_data_listdrops data rows of the listed tables from the output entirely (e.g., logs or system data).no_masking_table_listpasses data rows of the listed tables through without any masking.
3. Email & Phone Whitelist
Settings email_white_list and phone_white_list preserve specific emails and numbers from masking.
4. Flexible Masking Rules
- Partial email masking (e.g.,
user@domain.com→us****@domain.com) - Phone number obfuscation (e.g.,
+7 (123) 456-78-90→+7 (***) ***-**-90)
You can download a ready-to-use maskdump binary from the Releases page
- Ensure you have Go installed (version 1.26.0+ recommended)
- Clone the repository:
git clone https://github.com/intaro/maskdump.git cd maskdump - Build the binary:
go build -o maskdump .
Install the pinned quality tools:
make toolsRun the full local verification flow:
make check
go test ./...mysqldump dbname | ./maskdump --mask-email=light-hash --mask-phone=light-mask > anonymized_dump.sql| Option | Description | Default |
|---|---|---|
--mask-email |
Email masking algorithm (light-hash) |
(disabled) |
--mask-phone |
Phone masking algorithm (light-mask) |
(disabled) |
--no-cache |
Disable caching of masked values | false |
--config |
Path to configuration file | (autodetect) |
--cpu-profile |
Write CPU profile for profiling runs | (disabled) |
--db-format |
Dump dialect: auto, mysql, postgresql, oracle, mssql, sqlite, firebird |
auto |
With --db-format=auto (the default) the dialect is detected from the dump content. Explicitly setting the format is recommended for production pipelines: the flag overrides the db_format config field. Table filtering (skip_table_data_list, no_masking_table_list) and selective field masking (masking_tables) work for all listed dialects, including PostgreSQL COPY ... FROM stdin blocks. Table names in the config may be plain (tst_users) or schema-qualified (public.tst_users); for Oracle dumps table and column names match case-insensitively. If the dialect cannot be detected, maskdump falls back to full-line regex masking and logs a warning; selective filtering is disabled in that mode.
The keys skip_insert_into_table_list and processing_tables are deprecated aliases of skip_table_data_list and masking_tables. They still work for at least one release cycle (with a warning on stderr), but a config must not set a key together with its alias.
Create maskdump.conf in the same directory as the binary or specify path with --config:
{
"db_format": "auto",
"cache_path": "/home/user/.cache/maskdump/cache.json",
"email_regex": "\\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}\\b",
"phone_regex": "(?:\\+7|7|8)?(?:[\\s\\-\\(\\)]*\\d){10}",
"email_white_list": "/home/user/.config/maskdump/white_list_email.txt",
"phone_white_list": "/home/user/.config/maskdump/white_list_phone.txt",
"memory_limit_mb": 1024,
"cache_flush_count": 1000,
"skip_table_data_list": "/home/user/.config/maskdump/skip_table_list.txt",
"no_masking_table_list": "/home/user/.config/maskdump/no_masking_table_list.txt",
"masking": {
"email": {
"target": "username:1~1",
"value": "hash:6"
},
"phone": {
"target": "2,3,5,6,8,10",
"value": "hash"
}
},
"masking_tables": {
"b_user": {
"email": ["LOGIN", "EMAIL"],
"phone": ["PERSONAL_PHONE", "PERSONAL_MOBILE", "WORK_PHONE"]
},
"b_socialservices_user": {
"email": ["EMAIL"]
}
},
"logging": {
"path": "/var/log/maskdump.log",
"level": "info"
}
}For logging / level, the possible values are "debug", "info", "warn", and "error".
skip_table_data_list and no_masking_table_list point to text files with one table name per line, same as the white lists.
Create text files with one value per line to exclude from masking:
white_list_email.txt example:
admin@example.com
support@company.org
white_list_phone.txt example:
+79001234567
88005553535
- The characters to be replaced depend on the settings. By default, the configuration preserves only the first character and the domain, while all other characters in the email username are replaced with the first 6 characters of the MD5 hash of the entire original email string.
- Possible email masking configuration options:
target="2-5"andvalue="hash"- Numbers separated by a hyphen indicate character positions to replace; "hash" means replacement with characters from the MD5 hash of the original email. The range can be open-ended: "2-" replaces the second and all subsequent characters; "-5" replaces only the first five characters in the email.target="1~1"andvalue="hash"- Numbers separated by a tilde indicate how many characters to keep unchanged at the start and end of the string (all others are replaced); "hash" means replacement with characters from the MD5 hash of the original email. The range can be open-ended: "2~" keeps the first and second characters unchanged, replacing all subsequent characters; "~1" replaces all characters except the last one.target="1,3,5,7"andvalue="hash"- Comma-separated numbers indicate specific character positions to change; "hash" means replacement with characters from the MD5 hash of the original email.- Target can include modifiers: "username:" - modify only the left part of the email (before @) and "domain:" - modify only the right part of the email (after @). For example,
target="username:2-"means replacing the second and all subsequent characters in the left part of the email, while everything else (first character, @ symbol, and right part of the email) remains unchanged. value="*"- means replacement with asterisk characters
- Preserves the original phone number format
- Replaces specific digits with digits from the SHA256 hash. Which digits get replaced is determined by settings. By default, digits at these positions are replaced: 2, 3, 5, 6, 8, and 10.
The input is a typical database dump string. The output is the same dump, but with changed email and phone numbers:
echo "INSERT INTO users (id, email, phone) VALUES (123, 't098f6b@example.com', '+7 (904) 111-22-33'), (124, 'admin@site.org', '8-900-000-00-00');" | ./maskdump --mask-email=light-hash --mask-phone=light-mask --no-cacheResult:
INSERT INTO users (id, email, phone) VALUES (123, 'ta6f5ce@example.com', '+7 (354) 101-72-53'), (124, 'a21232f@site.org', '8-700-160-90-20');Example of working together with the mysqldump utility:
mysqldump --user=admin -p --host=localhost db_name | ./maskdump --mask-email=light-hash --mask-phone=light-mask >/tmp/maskdata_db_name.sql./maskdump --mask-email=light-hash --mask-phone=light-mask <~/tmp/dump_db_name.sql >/tmp/maskdata_db_data.sql- The CLI uses a buffered reader and writer with a
10 MiBbuffer (defaultMaxBufferSize). - Processing is line-oriented. Extremely large single-line dumps larger than the buffer budget should be split or the buffer constant should be adjusted before use.
- For profiling runs, use
--cpu-profile=/path/to/profile.outand inspect the result withgo tool pprof.
MIT — see the LICENSE file.
MaskDump — мощный инструмент для анонимизации баз данных и маскировки информации, предназначенный для защиты персональных данных (PII) в дампах БД. Обеспечивает безопасное преобразование данных с сохранением структуры и формата.
Основные возможности:
- Маскировка email и номеров телефонов с настраиваемыми алгоритмами
- Поддержка белых списков для исключения определённых значений
- Система кэширования для согласованного преобразования
- Настройка регулярных выражений для разных форматов данных
- Интеграция в существующие процессы обработки данных
Применение:
- Создание безопасных сред разработки/тестирования
- Обеспечение соответствия GDPR/CCPA
- Очистка данных перед аналитикой
- Маскировка данных для непродуктивных сред
Комментарии к проекту можно оставлять тут
1. Два режима работы:
- Обработка всего файла - подходит для любых текстовых файлов (SQL-дампы, CSV, логи и др.)
- Выборочная обработка - маскировка только указанных таблиц и полей (настраивается в атрибуте
masking_tablesконфига)
2. Фильтрация таблиц
skip_table_data_list— данные перечисленных таблиц полностью удаляются из вывода (например, логи или служебные данные).no_masking_table_list— данные перечисленных таблиц проходят в вывод без какой-либо маскировки.
3. Белый список email и телефонов
Настройки email_white_list и phone_white_list позволяют сохранить нетронутыми конкретные адреса и номера.
4. Гибкие правила маскировки
- Замена части email (например,
user@domain.com→us****@domain.com) - Частичное скрытие телефонов (например,
+7 (123) 456-78-90→+7 (***) ***-**-90)
Можно скачать готовую программу maskdump со страницы релизов
- Убедитесь, что установлен Go (версия 1.26.0+)
- Клонируйте репозиторий:
git clone https://github.com/intaro/maskdump.git cd maskdump - Соберите бинарник:
go build -o maskdump .
Установите зафиксированные версии quality tools:
make toolsЗапустите полный локальный набор проверок:
make check
go test ./...mysqldump dbname | ./maskdump --mask-email=light-hash --mask-phone=light-mask > anonymized_dump.sql| Параметр | Описание | По умолчанию |
|---|---|---|
--mask-email |
Алгоритм маскировки email (light-hash) |
(отключено) |
--mask-phone |
Алгоритм маскировки телефонов (light-mask) |
(отключено) |
--no-cache |
Отключить кэширование | false |
--config |
Путь к конфигурационному файлу | (автопоиск) |
--cpu-profile |
Записать CPU profile для профилирования | (отключено) |
--db-format |
Диалект дампа: auto, mysql, postgresql, oracle, mssql, sqlite, firebird |
auto |
При --db-format=auto (по умолчанию) диалект определяется по содержимому дампа. Для production-пайплайнов рекомендуется указывать формат явно: флаг имеет приоритет над полем db_format конфига. Фильтрация таблиц (skip_table_data_list, no_masking_table_list) и выборочная маскировка полей (masking_tables) работают для всех перечисленных диалектов, включая блоки PostgreSQL COPY ... FROM stdin. Имена таблиц в конфиге могут быть простыми (tst_users) или со схемой (public.tst_users); для Oracle-дампов имена таблиц и колонок сопоставляются без учёта регистра. Если диалект определить не удалось, maskdump переходит к полнострочной regex-маскировке с предупреждением в логе; выборочная фильтрация в этом режиме отключается.
Ключи skip_insert_into_table_list и processing_tables — устаревшие синонимы skip_table_data_list и masking_tables. Они продолжают работать как минимум один релизный цикл (с предупреждением в stderr), но задавать ключ одновременно с его синонимом нельзя.
Создайте maskdump.conf в той же директории или укажите путь через --config:
{
"db_format": "auto",
"cache_path": "/home/user/.cache/maskdump/cache.json",
"email_regex": "\\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}\\b",
"phone_regex": "(?:\\+7|7|8)?(?:[\\s\\-\\(\\)]*\\d){10}",
"email_white_list": "/home/user/.config/maskdump/white_list_email.txt",
"phone_white_list": "/home/user/.config/maskdump/white_list_phone.txt",
"memory_limit_mb": 1024,
"cache_flush_count": 1000,
"skip_table_data_list": "/home/user/.config/maskdump/skip_table_list.txt",
"no_masking_table_list": "/home/user/.config/maskdump/no_masking_table_list.txt",
"masking": {
"email": {
"target": "username:1~1",
"value": "hash:6"
},
"phone": {
"target": "2,3,5,6,8,10",
"value": "hash"
}
},
"masking_tables": {
"b_user": {
"email": ["LOGIN", "EMAIL"],
"phone": ["PERSONAL_PHONE", "PERSONAL_MOBILE", "WORK_PHONE"]
},
"b_socialservices_user": {
"email": ["EMAIL"]
}
},
"logging": {
"path": "/var/log/maskdump.log",
"level": "info"
}
}Для logging / level возможные значения: "debug", "info", "warn", "error"
skip_table_data_list и no_masking_table_list указывают на текстовые файлы с одним именем таблицы в строке — по аналогии с белыми списками.
Создайте текстовые файлы со значениями, которые не нужно маскировать:
Пример white_list_email.txt:
admin@example.com
support@company.org
Пример white_list_phone.txt:
+79001234567
88005553535
- Заменяемые символы зависят от настроек. По-умолчанию заданы настройки, при которых сохраняется только первый символ и домен, а все прочие символы имени пользователя из email заменяются на первые 6 символов MD5 хэша от всей исходной строки email
- Возможные варианты настроек макировки email:
target="2-5"иvalue="hash"— числа через дефис — это номера позиций символов, которые заменяем; "hash" — означает, что заменяем символами из MD5 хэша от исходного email. Диапазон заменяемых позиций символов может быть открытым: "2-" — замена второго и всех последующих симолов; "-5" — замена только первых пяти символов в email.target="1~1"иvalue="hash"— числа через тильду — это количество символов, которые оставляем неизменными с начала и с конца строки (а все прочие заменяются); "hash" — означает, что заменяем символами из MD5 хэша от исходного email. Диапазон может быть открытым: "2~" — первый и второй символ остаются, в все последующие символы заменяются; "~1" — замена всех символов, кроме последнего.target="1,3,5,7"иvalue="hash"— числа через запятую — это номера поиций символов, которые изменям; "hash" — означает, что заменяем символами из MD5 хэша от исходного email.- для target могут быть модификаторы: "username:" — изменять только левую часть email и "domain:" — изменять только правую часть email. Например,
target="username:2-"означает замену второго и всех последующих символов левой части email, а всё остальное (первый символ, знак "@" и правая часть email) остаётся неизменным value="*"— означает замену на символ звёздочки
- Сохраняет исходный формат номера
- Заменяет определённые цифры на цифры из SHA256 хэша. Что попадает под замену — определяется настройками. По-умолчанию, заменяются цифры на этих номерах позиций: 2, 3, 5, 6, 8 и 10.
На вход подаём строку типичного дампа базы данных. На выходе получаем этот же дамп, но с изменёнными email и телефонами:
echo "INSERT INTO users (id, email, phone) VALUES (123, 't098f6b@example.com', '+7 (904) 111-22-33'), (124, 'admin@site.org', '8-900-000-00-00');" | ./maskdump --mask-email=light-hash --mask-phone=light-mask --no-cacheРезультат:
INSERT INTO users (id, email, phone) VALUES (123, 'ta6f5ce@example.com', '+7 (354) 101-72-53'), (124, 'a21232f@site.org', '8-700-160-90-20');Пример совместной работы с утилитой mysqldump:
mysqldump --user=admin -p --host=localhost db_name | ./maskdump --mask-email=light-hash --mask-phone=light-mask >/tmp/maskdata_db_name.sql./maskdump --mask-email=light-hash --mask-phone=light-mask <~/tmp/dump_db_name.sql >/tmp/maskdata_db_data.sql- CLI использует буферизированные reader/writer с буфером
10 MiB(defaultMaxBufferSize). - Обработка идёт построчно. Если дамп содержит очень большие одиночные строки больше доступного буфера, их нужно предварительно разбить или увеличить константу буфера в коде.
- Для профилирования используйте
--cpu-profile=/path/to/profile.out, затем анализируйте результат черезgo tool pprof.
Проект распространяется под лицензией MIT — подробности см. в файле LICENSE.