pgpro_scout
pgpro_scout — обнаружение чувствительной информации в базе данных
Синтаксис
pgpro_scout config [параметр...]
pgpro_scout inspect [параметр...]
Описание #
pgpro_scout — утилита командной строки, предназначенная для обнаружения чувствительной (конфиденциальной) информации в базе данных. В поисках такой информации pgpro_scout просматривает названия столбцов и значения полей в таблицах базы данных. Для выполнения поиска требуется специализированный словарь поиска, который можно сформировать данной утилитой.
Задача pgpro_scout провести разведку данных на предмет наличия чувствительной информации и привести примеры.
Утилита pgpro_scout поставляется вместе с Postgres Pro Standard в отдельном пакете pgpro_scout (подробные инструкции по установке приведены в Главе 16).
Словарь поиска представляет собой текстовый файл, в котором каждая строка имеет формат ключ-значение-комментарий, где:
Ключ — строка, содержащая условное имя параметра поиска.
Значение — условие, которому должно соответствовать поле базы данных, чтобы его можно было отнести к чувствительной информации. Может быть регулярным выражением или массивом строковых значений.
Комментарий — текстовое описание условия поиска, которое будет отображаться в результатах поиска.
pgpro_scout формирует файл отчёта с информацией о найденных вхождениях чувствительной информации. За подробностями обратитесь к Разделу «Отчёт pgpro_scout».
Использование pgpro_scout #
Чтобы проверить, содержится ли в базе данных конфиденциальная информация, сформируйте словарь поиска и запустите поиск, указав объекты базы данных, которые необходимо проверить.
Создание словаря поиска pgpro_scout #
Чтобы сформировать базовый словарь поиска, выполните команду config. При необходимости его можно обновить или дополнить новыми условиями поиска. Ниже приведён пример словаря:
scout:
column_names:
matchers:
- key: phones
match_values: ["phones", "phone"]
comment: "Поля номеров телефона"
column_values:
disabled: true # опционально
case_sensitive: false # опционально
matchers:
- key: surnames
disabled: false # опционально
case_sensitive: true # опционально
match_values: ["Иванов", "Петров"]
- key: phones_data
pattern: ^((8|\+7)[\- ]?)?(\(?\d{3}\)?[\- ]?)?[\d\- ]{7,10}$
comment: "Российские номера телефонов"
exclude:
schemas: ['pgpro_sfile_data', 'dbms_lob', 'profile', 'information_schema', 'pg_catalog', 'pg_toast']
column_types: ['timestamp with time zone']Структура словаря поиска #
Словарь поиска состоит из следующих разделов:
scout— описание условий поиска.exclude— список схем баз данных и типов полей, которые будут исключены из поиска.
Условия поиска могут быть двух типов:
column_names— имена полей.column_values— значения полей.
Элемент matchers содержит список условий поиска. Каждый элемент matchers может содержать следующие параметры:
key— ключ поиска.match_values— список строк для поиска в полях базы данных. Не может быть указан вместе сpattern.pattern— регулярное выражение для поиска в полях базы данных. Не может быть указан вместе сmatch_values.case_sensitive— логическое значение, которое определяет, будет ли учитываться регистр при поиске вхождений, если параметрmatch_valuesзадан.disabled— логическое значение, которое определяет, необходимо ли исключить условие из поиска.comment— комментарий, который будет отображаться в файле отчёта.
Определение объектов базы данных, среди которых будет осуществляться поиск #
Чтобы определить объекты, по которым будет выполняться поиск, при его запуске задайте параметр --search-path. В параметре --search-path можно передать строку со списком объектов базы данных, перечисленных через запятую, которыми будет ограничен поиск:
Чтобы ограничить поиск схемой базы данных, задайте подстроку с именем схемы.
Чтобы ограничить поиск отдельной таблицей или таблицами, добавьте запись в формате:
СХЕМА.ТАБЛИЦАилиСХЕМА.{ТАБЛИЦА1, ТАБЛИЦА2}.Чтобы ограничить поиск отдельным столбцом или столбцами таблицы, задайте подстроку в формате:
СХЕМА.ТАБЛИЦА.СТОЛБЕЦилиСХЕМА.ТАБЛИЦА.{СТОЛБЕЦ1, СТОЛБЕЦ2}.
Таблица I.1. Примеры определения области поиска
Значение --search-path | Область поиска |
|---|---|
public | Все таблицы (со всеми столбцами) в схеме public. |
public.{products, sales} | Таблицы products и sales (со всеми столбцами) в схеме public. |
public.products.{id, email} | Столбцы id и email из таблицы products в схеме public. |
public.products | Только таблица public.products. |
public.products,events,holds.card.id | Таблица public.products, все таблицы в схеме events и столбец id из таблицы holds.card. |
Запуск поиска конфиденциальной информации #
Чтобы запустить поиск конфиденциальной информации с доступным словарем поиска, выполните команду inspect, задав значение параметру --search-path, как описано в Подразделе «Определение объектов базы данных, среди которых будет осуществляться поиск».
Ограничения использования #
При использовании pgpro_scout имейте в виду следующие ограничения:
При поиске данных типа
json/jsonbдолжны использоваться условияpattern, а неmatch_values.В настоящее время pgpro_scout не поддерживает схемы, таблицы и поля с именами, чувствительными к регистру.
Поиск значений в полях большого объёма может существенно увеличить время проверки, что может выглядеть как зависание приложения. Если известно, что имеются поля с большим объёмом данных, исключите их из поиска, отредактировав значение параметра
--search-path.При использовании составного первичного ключа проверяемой таблицы не рекомендуется исключать из поиска отдельные поля, входящие в первичный ключ.
pgpro_scout поддерживает таблицы с первичными ключами следующих типов:
Числовые типы:
smallint,integer,bigint,decimal,numeric,real,double,smallserial,serial,bigserial.Денежный тип:
money.Символьные типы:
text,bpchar,character,character(n).Типы даты и времени:
timestamp,timestampz,date,time,time with time zone,interval.Типы, описывающие сетевые адреса:
inet,cidr,macaddr,macaddr8.Логический тип.
Тип
UUID.Диапазонные типы:
int4range,int8range,daterange.Типы массивов: поддерживаются массивы, имеющие типы с поддерживаемыми одиночными типами элементов.
Использование других типов данных в качестве первичных ключей может приводить к ошибкам.
Справка по командной строке #
В этом разделе описаны команды pgpro_scout. Необязательные параметры заключены в квадратные скобки.
config #
pgpro_scout config [--out|-o строка] [--override|-O] [--help|-h]Формирует базовый словарь поиска pgpro_scout. Параметры означают следующее:
--h--helpВыводит справку по команде.
-O--overrideПереопределить файл словаря поиска, если он существует.
-oпуть_к_файлу--outпуть_к_файлуЗадаёт путь к файлу словаря поиска.
inspect #
pgpro_scout inspect [--batch-size|-buint] [--config-file|-fstring] [--dbname|-dstring] [--disable-comment] [--hidden-sample] [--host|-Hstring] [--order|-Ostring] [--output|-ostring] [--password|-Wstring] [--port|-puint16] [--report-bufferuint16] [--rows-number|-nuint16] [--sample-sizeuint16] [--search-path|-sstring] [--threads|-jint] [--username|-Ustring] [--help|-h]
Запускает поиск конфиденциальной информации. Параметры означают следующее:
-bразмер--batch-size#размерКоличество строк в базе данных, которые необходимо обработать в рамках одного запроса для каждой задачи.
Значение по умолчанию:
1000.-fпуть_к_файлу--config-file#путь_к_файлуЗадаёт путь к файлу словаря поиска.
-dимя--dbname#имяИмя базы данных, к которой необходимо подключиться.
--disable-comment#Создавать файл отчёта без комментариев.
-hстрока--help#строкаВыводит справку по команде.
--hidden-sample#Маскирует найденные примеры в отчёте. Например: вместо
Смирновав отчёте будет отображатьсяСм****ва.-Hимя--host#имяИмя базы данных или IP-адрес.
Значение по умолчанию:
localhost.-Oпорядок_поиска--orderпорядок_поиска#Порядок проверки строк. Возможные значения:
tail— брать строки с конца;head— брать строки с начала;random— взять случайные строки.
Значение по умолчанию:
head.-oпуть_к_файлу--outputпуть_к_файлу#Задаёт путь к файлу отчёта.
-Wстрока--password#строкаПароль для подключения к базе данных.
-pимя--port#имяПорт для подключения к базе данных.
Значение по умолчанию:
5432.--report-bufferразмер#Размер буфера отчёта.
Значение по умолчанию:
64-nколичество--rows-numberколичество#Количество строк для проверки в каждой таблице.
Значение по умолчанию:
10000.--sample-sizeколичество#Количество найденных строк, которые необходимо включить в отчёт для каждой таблицы. Если значение равно 0, найденные строки не будут добавлены в отчёт.
Значение по умолчанию:
5.-sпуть_к_файлу--search-pathпуть_к_файлу#Список схем, таблиц и полей для проверки. За подробной информацией обратитесь к Подразделу «Определение объектов базы данных, среди которых будет осуществляться поиск».
Значение по умолчанию:
5.-jпуть_к_файлу--threadsпуть_к_файлу#Количество потоков, задействованных утилитой.
Значение по умолчанию:
14.-Uимя--username#имяИмя пользователя для подключения к базе данных.
Отчёт pgpro_scout #
В результате поиска pgpro_scout создаётся файл CSV. Этот файл содержит следующую информацию:
Дату и время завершения поиска.
Заголовки полей отчёта.
Результаты поиска.
Структура отчёта #
Результаты поиска содержат следующие поля:
Таблица I.2. Поля отчёта
| Имя | Описание |
|---|---|
location | Полное имя таблицы в формате <имя_схемы>.<имя_таблицы>, где было найдено вхождение. |
column | Столбец таблицы. |
key | Ключ условия поиска из словаря поиска. |
comment | Комментарий к условию поиска из словаря поиска. |
sample | Пример найденного вхождения. Если поиск выполняется с параметром --sample-size, равным 0, это поле не будет включено в отчёт. Чтобы замаскировать содержимое этого поля, при запуске поиска добавьте параметр --hidden-sample. |
В отчёт будет включено не больше полей из каждый таблицы, чем указано в параметре --sample-size.
Пример #
Ниже приведён пример файла отчёта:
#report time: 2025-06-16T11:10:58+03:00 location,column,key,comment, sample public.expected,phone,phones,Российские номера телефонов, events.holds,user_surname,surname,Русские фамилии, Иванов events.holds,user_surname,surname,Русские фамилии, Петров
pgpro_scout
pgpro_scout — detect sensitive information in a database
Synopsis
pgpro_scout config [option...]
pgpro_scout inspect [option...]
Description #
pgpro_scout is a command-line utility to detect sensitive (confidential) information in a database. pgpro_scout looks for sensitive information in database column names and field values. The search requires a specialized dictionary that the utility allows you to create.
pgpro_scout does not aim to find all the sensitive information, but only performs data intelligence to determine whether such information exists and show sensitive data samples.
pgpro_scout is provided with Postgres Pro Standard as a separate pre-built package pgpro_scout (for the detailed installation instructions, see Chapter 16).
The dictionary is a text file whose lines have the key-value-comment format. Where:
key is a string with the conventional name of a search parameter.
value defines a condition that a database field must meet to be considered sensitive. Can be a regular expression or an array of string values.
comment is a text description of the search condition to be visible in search results.
pgpro_scout generates a report file with information on sample occurrences of the sensitive information found. Refer to the section called “pgpro_scout Report” for details.
pgpro_scout Usage #
To perform the database inspection for occurrences of sensitive information, you need to create the dictionary and launch the search passing a list of database objects to look through.
Creating the pgpro_scout Dictionary #
To create a base dictionary, run the config command. You can update this dictionary and extend it with new search conditions if needed. Here is an example of the dictionary:
scout:
column_names:
matchers:
- key: phones
match_values: ["phones", "phone"]
comment: "Phone number fields"
column_values:
disabled: true # optional
case_sensitive: false # optional
matchers:
- key: surnames
disabled: false # optional
case_sensitive: true # optional
match_values: ["Holmes", "Watson"]
- key: phones_data
pattern: ^((8|\+7)[\- ]?)?(\(?\d{3}\)?[\- ]?)?[\d\- ]{7,10}$
comment: "Phone numbers"
exclude:
schemas: ['pgpro_sfile_data', 'dbms_lob', 'profile', 'information_schema', 'pg_catalog', 'pg_toast']
column_types: ['timestamp with time zone']
Dictionary Structure #
The dictionary consists of the following sections:
scout— contains the description of search conditions.exclude— lists database schemas and field types to be excluded from the search.
These types of search conditions can be specified:
column_names— field names.column_values— field values.
A matchers element contains a list of search conditions. Each matchers element may contain the following parameters:
key— the search key.match_values— the list of strings to look for in the database fields. Do not specify together withpattern.pattern— a regular expression for search in the database fields. Do not specify together withmatch_values.case_sensitive— a boolean value to define whether the search is case-sensitive ifmatch_valuesis specified.disabled— a boolean value to define whether to exclude the condition from the search.comment— the comment to be shown in the report file.
Specifying Database Objects to Look through #
To specify the objects to look through, use the --search-path option when launching the search. --search-path takes a string that contains comma-separated substrings with database objects to restrict the search to:
To restrict the search to a database schema, specify a substring with the schema name.
To restrict the search to an individual table or tables, specify a substring like this:
SCHEMA.TABLEorSCHEMA.{TABLE1, TABLE2}.To restrict the search to an individual column or columns of a certain table, specify a substring like this:
SCHEMA.TABLE.COLUMNorSCHEMA.TABLE.{COLUMN1, COLUMN2}.
Table I.1. Examples of Specifying Search Objects
--search-path Value | Search Range |
|---|---|
public | All tables (with all columns) in the public schema. |
public.{products, sales} | products and sales tables (with all columns) in the public schema. |
public.products.{id, email} | id and email columns of the products table in the public schema. |
public.products | Only the public.products table. |
public.products,events,holds.card.id | The public.products table, all tables in the events schema, and the id column of the holds.card table. |
Launching the Search of Sensitive Information #
To launch the search of sensitive information with the available dictionary, run the inspect command specifying --search-path as explained in the section called “Specifying Database Objects to Look through”.
Usage Limitations #
Take into account the following limitations when using pgpro_scout:
When looking for data of the
json/jsonbtype,patternconditions must be used rather thanmatch_values.pgpro_scout does not currently support schemas, tables, and fields with case-sensitive names.
Search for values in large-volume fields can greatly increase the search time, so that this can even look like the application hanging. If you are aware of fields containing considerable volume of data, exclude these fields from the search by editing
--search-path.When looking for data in a table with a composite primary key, avoid excluding single fields contained in the primary key from search.
pgpro_scout supports tables with primary keys of the following types:
Numeric:
smallint,integer,bigint,decimal,numeric,real,double,smallserial,serial,bigserial.Monetary:
money.Character:
text,bpchar,character,character(n).Date and time:
timestamp,timestampz,date,time,time with time zone,interval.Describing network addresses:
inet,cidr,macaddr,macaddr8.Boolean.
UUID.Range:
int4range,int8range,daterange.Array: arrays of types are supported whose element types are supported.
Use of primary keys of types different from those listed above can result in errors.
Command-Line Reference #
This section describes pgpro_scout commands. Optional parameters are enclosed in square brackets.
config #
pgpro_scout config [--out|-o string] [--override|-O] [--help|-h]
Generates a base pgpro_scout dictionary. The meaning of the options is as follows:
--h--helpOutput the command reference information.
-O--overrideOverride the dictionary file if it exists.
-ofilepath--outfilepathPath to the dictionary file.
inspect #
pgpro_scout inspect [--batch-size|-buint] [--config-file|-fstring] [--dbname|-dstring] [--disable-comment] [--hidden-sample] [--host|-Hstring] [--order|-Ostring] [--output|-ostring] [--password|-Wstring] [--port|-puint16] [--report-bufferuint16] [--rows-number|-nuint16] [--sample-sizeuint16] [--search-path|-sstring] [--threads|-jint] [--username|-Ustring] [--help|-h]
Launches the search of sensitive information. The meaning of the options is as follows:
-bsize--batch-size#sizeNumber of database rows to be processed by one query for each task.
Default:
1000.-ffilepath--config-file#filepathPath to the dictionary file.
-dname--dbname#nameDatabase name to connect to.
--disable-comment#Create the report file without comments.
-hstring--help#stringOutput the command reference information.
--hidden-sample#Mask found samples in the report. For example:
Br**tewill be output instead ofBronte.-Hname--host#nameDatabase host name or IP address.
Default:
localhost.-Osearch_order--ordersearch_order#The order of looking through rows. Possible values:
tail— get last rowshead— get first rowsrandom— get random rows
Default:
head.-ofilepath--outputfilepath#Path to the report file.
-Wstring--password#stringPassword to connect to the database.
-pname--port#nameDatabase port.
Default:
5432.--report-buffersize#Size of the report buffer.
Default:
64-nnumber--rows-numbernumber#Number of rows to look through in each table.
Default:
10000.--sample-sizenumber#Number of found samples to be included in the report for each table. If set to 0, samples of found rows will not be included in the report.
Default:
5.-sfilepath--search-pathfilepath#List of schemas, tables, and fields to look through. See the section called “Specifying Database Objects to Look through” for details.
Default:
5.-jfilepath--threadsfilepath#Number of threads used to run the utility.
Default:
14.-Uname--username#nameUsername to connect to the database.
pgpro_scout Report #
A csv file is created as a result of pgpro_scout search. This file provides the following information:
Date and time of the search completion.
Report field headings.
Search results.
Report Structure #
The search results contain the following fields:
Table I.2. Report Fields
| Name | Description |
|---|---|
location | Full name of a table, that is <schema name>.<table_name>, with the occurrence found. |
column | Column of the table. |
key | Key of the search condition from the dictionary. |
comment | Comment of the search condition from the dictionary. |
sample | Sample occurrence found. If the search is run with --sample-size = 0, this field is not included in the report. To mask the contents of this field, enable --hidden-sample when launching the search. |
The report will contain not more than --sample-size lines for each table.
Example #
The following is an example of the report file:
#report time: 2025-06-16T11:10:58+03:00 location,column,key,comment, sample public.expected,phone,phones,Phone numbers, events.holds,user_surname,surname,Last names, Holmes events.holds,user_surname,surname,Last names, Watson