Exempt access policy что это

Exempt access policy что это

Фирма Oracle не считает для себя направление VPD случайным, о чем свидетельствует непрекрывное развитие этого средства от одной версии СУБД к другой. Так, в числе новшеств VPD в версии 9 – собственная GUI-программа администрирования Policy Manager и поддержка синонимов, а в версии 10.1 – отбор строк (и даже значений в строках) с учетом указанных столбцов и возможность выбора между статическим и динамическим вычислением заданного предикатом отбора критерия видимости.

Именно первая из указанных двух новых возможностей VPD версии 10.1 и будет продемонстрирована в этой статье.

Подготовка примера

Хотя формально этого не требуется, при использовании VPD методологически правильно завести специального пользователя-администратора. Ниже ему предоставляется минимум полномочий, достаточных для примеров из этой статьи. Выдаем в SQL*Plus:

Избирательность строк и значений с учетом столбцов

Сначала воспроизведем пример из упомянутой выше по тексту первой статьи с тою разницей, что теперь функция политики доступа к таблице SCOTT.EMP и вспомогательная таблица, регулирующая доступ, создаются в отдельной схеме VPD_ADMIN «администратора политик» (что в методологически более правильно): CONNECT vpd_admin/vpd_admin

Таблица с данными, параметризующими доступ:

(Полагаем, что пользователь SCOTT будет работать с сотрудниками 10-го и 30-го отделов, а пользователь ADAM – с сотрудниками только 10-го).

Функция, служащая предикатом доступа, задающая фильтр для строк при обращении к таблице SCOTT.EMP:

Политику доступа к таблице SCOTT.EMP по-прежнему назовем EPOLICY:

Новые параметры политики доступа в версии 10

В версии 10.1 у процедуры DBMS_RLS.ADD_POLICY появились новые необязательные (умолчательное значение – NULL) параметры:

Здесь через запятую указываются столбцы таблицы, содержащие, по нашему хотению, данные ограниченного доступа. Если при обращении к таблице мы обратимся к этим столбцам, значений в них не увидим. Пример:

(Файл drop_policy.sql я создал ради удобства, чтобы более экономно удалить политику во второй раз, ниже по тексту). Проверка:

А вот что получим, если не обратимся к «секретному» столбцу с зарплатой:

В любом случае защищенных данных мы не увидим, но способ достижения этого своеобразен: как только мы обращаемся к «секретным» столбцам, политика препятствует показу некоторых строк (как и раньше), но если мы к «секретным» столбцам не обращаемся, то пожалуйста – нам даются все строки, словно бы никакой политики и не было.

Довольно необычно: количество доступных строк при запросе к таблице зависит от того, запросили мы «секретный» столбец, или же нет. Более традиционного поведения можно достичь употреблением еще одного нового параметра.

Если для него указать константу DBMS_RLS.ALL_ROWS, то при операции SELECT будут выдаваться все строки, но значения в «секретных» столбцах некоторых строк (защищенных политикой) мы не увидим: Проверка:

Обратите внимание, что различить в столбцах пропуски значений, обязанные применению политики, от пропусков в исходных данных в Oracle нельзя. Это контрастирует с возможностью аналогичного различения «исходных» и «благоприобретенных» пропусков, существующей, например, в SELECT с использованием GROUP BY ROLLUP/CUBE.

Некоторые замечания по употреблению

Во-первых, создать отдельную таблицу, наподобие того, как это сделано выше, и перенести в нее нужные данные из EMP.

Во-вторых, создать не новую таблицу, а materialized view на основе EMP, и в функции-предикате обращаться именно к materialized view. Это будет технологичнее, так как снимет проблему синхронизации данных во вспомогательной таблице с изменениями в EMP. Materialized view в этом случае удобно создать со свойством REFRESH ON COMMIT.

К сожалению, в любом случае придется дублировать часть данных из основной таблицы EMP.

Ну, и наконец, в реальной практике эффективно использовать контекст сеанса, хотя это и усложнит программирование.

1. Формально не эквивалент, так как документация по Oracle считает, что VPD = FGAC + контекст приложения. По существу же мне разницы не видится.

Источник

Oracle. Безопасность на уровне строк

Введение в проблему

В настоящее время в любой организации действует разграничение доступа к информации на основе определенных знаний о пользователе. Такими знаниями могут служить роль пользователя в организации, его должность либо структурное подразделение, в котором работает пользователь. Многим известно, что проблема ограничения доступа может быть решена с помощью простейших механизмов на основе имени пользователя, таблиц, представлений и триггеров.

Рассмотрим пример:
Предоставить менеджеру информацию о клиентах организации. При этом, менеджер может видеть только клиентов своего структурного подразделения, но не всей компании:

Решением «в лоб» является создание отдельного представления для каждого отдела компании. Например:

Решение, бесспорно, более интересное, но что же делать, когда одному пользователю необходимо «видеть» клиентов нескольких подразделений? Также часто возникает ситуация, когда одному пользователю разрешается только запрашивать данные из одной таблицы, в другой он может еще редактировать, но не удалять, а в третьей просматривать и удалять. Городить несметное количество представлений, триггеров и настоечных таблиц становится уж очень неудобно…

Технология RLS

Технология RLS (row-level security или безопасность на уровне строк) предоставляет возможность создания политик безопасности, которые ограничивают доступ пользователям к информации в БД. Как уже упоминалось выше, политики безопасности позволяют либо «закрыть» информацию полностью или частично, либо разрешить лишь определенные операции над ней. Технология была впервые представлена в Oracle 8i, но в последующих версиях ее возможности были значительно расширены.
При связи объекта БД с политикой безопасности контроль доступа осуществляется через логику, занесенную в специальную PL/SQL-функцию. Согласитесь, что гораздо проще поддерживать несколько программных функций, нежели десятки представлений, разнесенных по N-ому количеству схем.
При непосредственном или косвенном доступе пользователя к объекту БД (таблице, представлению) сервер динамически модифицирует оператор SQL, добавляя к нему предикат WHERE, который возвращается функцией безопасности.

Функция безопасности

Итак, теперь пришло время рассмотреть пример простейшей функции безопасности. Как уже отмечалось, задача функции – формирование предиката, который будет автоматически добавлен к запросу пользователя.

Приведенная выше функция будет добавлять предикат WHERE clientoffice = office_no к SQL запросу пользователя, где office_no – номер подразделения, в котором работает пользователь. Для пользователя с логином MGR_10_20_30 будет добавляться предикат WHERE clientoffice in (10, 20, 30). Таким образом, этот пользователь будет иметь доступ к информации о клиентах трех подразделений.

Процедуры пакета DBMS_RLS

Add_policy

Ну что ж, к данному моменту мы проделали всю необходимую подготовительную работу, и нам осталось лишь добавить политику безопасности в нашу БД. Политика безопасности регистрируется процедурой пакета DBMS_RLS add_policy:

Добавим политику безопасности для таблицы clients:

Теперь вкратце об использованных нами параметрах процедуры:
object_schema и object_name – таблица, представление или синоним, для которого добавляется политика, и схема БД, в которой находится объект.
policy_name – имя добавляемой политики безопасности. Имя должно быть уникально для каждой таблицы или представления в отдельности.
function_schema и policy_function – имя функции безопасности, которая генерирует предикат, и схема БД, в которой находится функция.
statement_types – операторы, к которым применяется политика безопасности.
update_check – опция предотвращает операции INSERT или UPDATE, если INSERT или UPDATE нарушает условия поиска определенные в предикате.
Теперь мы можем посмотреть политику безопасности в действии:

Exempt access policy что это. Смотреть фото Exempt access policy что это. Смотреть картинку Exempt access policy что это. Картинка про Exempt access policy что это. Фото Exempt access policy что это

Для пользователя MGR_10:

Exempt access policy что это. Смотреть фото Exempt access policy что это. Смотреть картинку Exempt access policy что это. Картинка про Exempt access policy что это. Фото Exempt access policy что это

Exempt access policy что это. Смотреть фото Exempt access policy что это. Смотреть картинку Exempt access policy что это. Картинка про Exempt access policy что это. Фото Exempt access policy что это

Для пользователя MGR_20:

Exempt access policy что это. Смотреть фото Exempt access policy что это. Смотреть картинку Exempt access policy что это. Картинка про Exempt access policy что это. Фото Exempt access policy что это

Exempt access policy что это. Смотреть фото Exempt access policy что это. Смотреть картинку Exempt access policy что это. Картинка про Exempt access policy что это. Фото Exempt access policy что это

Для пользователя MGR_10_20_30:

Exempt access policy что это. Смотреть фото Exempt access policy что это. Смотреть картинку Exempt access policy что это. Картинка про Exempt access policy что это. Фото Exempt access policy что это

Exempt access policy что это. Смотреть фото Exempt access policy что это. Смотреть картинку Exempt access policy что это. Картинка про Exempt access policy что это. Фото Exempt access policy что это

Информация о представлениях в БД хранится в представлениях user_policies, all_policies, dba_policies. Выполним запрос из-под пользователя с правами DBA:

Exempt access policy что это. Смотреть фото Exempt access policy что это. Смотреть картинку Exempt access policy что это. Картинка про Exempt access policy что это. Фото Exempt access policy что это

Drop_policy

Соответственно, раз есть процедура создания политики безопасности, то есть и процедура удаления ее:

Попробуем удалить нашу политику безопасности:

Проверим теперь наличие политик в БД юзером с правами DBA:

Exempt access policy что это. Смотреть фото Exempt access policy что это. Смотреть картинку Exempt access policy что это. Картинка про Exempt access policy что это. Фото Exempt access policy что это

Enable_policy

Кроме операций добавления/удаления политик безопасности существует возможность временно приостановить действие существующих политик. Для этого служит процедура enable_policy, которая переводит политику в неактивное состояние (enable => false) или возобновляет действие политики (enable => true):

Exempt access policy что это. Смотреть фото Exempt access policy что это. Смотреть картинку Exempt access policy что это. Картинка про Exempt access policy что это. Фото Exempt access policy что это

Exempt access policy что это. Смотреть фото Exempt access policy что это. Смотреть картинку Exempt access policy что это. Картинка про Exempt access policy что это. Фото Exempt access policy что это

Exempt access policy что это. Смотреть фото Exempt access policy что это. Смотреть картинку Exempt access policy что это. Картинка про Exempt access policy что это. Фото Exempt access policy что это

Самые внимательные, я думаю, заметили параметр enable процедуры add_policy пакета dbms_rls. Этот параметр указывает на то, будет ли политика активной или неактивной сразу после создания. По умолчанию значение true.

Refresh_policy

Процедура позволяет обновить предикат политики RLS. Если политика безопасности определена с типом, отличным от DYNAMIC, предикат политики может некоторое время не обновляться, т.к. он кэширован в памяти. Поэтому если есть необходимость обновить политику немедленно, то нужно выполнить процедуру REFRESH_POLICY, которая заново выполнит функцию политики и обновит в кэше предикат.

Заключение

В настоящей статье рассмотрен простейший пример, как говорится, «на пальцах». В следующей статье мы рассмотрим безопасность с использованием контекстов и групп политик.

Источник

PL/SQL: безопасность уровня строк (RLS) с пакетом DBMS_RLS

Exempt access policy что это. Смотреть фото Exempt access policy что это. Смотреть картинку Exempt access policy что это. Картинка про Exempt access policy что это. Фото Exempt access policy что это

Стас Белков

Автор статьи. Известный специалист в мире IT. Консультант по продуктам и решениям Oracle. Практикующий программист и администратор баз данных. Подробнее.

Проблему можно решить созданием представления на базе таблицы, но что если пользователь должен иметь доступ к самой таблице? В некоторых случаях доступ к таблице может быть оправданным — например, если пользователю потребуется создавать хранимые программные блоки для работы с таблицей. Реализация с представлением для этого просто не подойдет.

В документации Oracle RLS также иногда обозначается сокращениями VPD ( Virtual Private Database ) и FGAC ( Fine-Grained Vccess Control ).

Например, если активизировать RLS для таблицы EMP с описанным выше правилом, то при вводе запроса

пользователь Lora увидит только четыре строки (а не 14!), хотя сам запрос не включает секцию WHERE :

Аналогичным образом, при обновлении таблицы без условия WHERE будут обновлены только видимые пользователю записи:

Итак, на верхнем уровне абстракции RLS состоит из трех основных компонентов:

На концептуальном уровне схема действия RLS показана на рис. 1. Политика представляет собой «фильтр» для отбора строк таблицы. Если строка удовлетворяет предикату, она проходит через фильтр; в противном случае строка остается невидимой для пользователя.

Exempt access policy что это. Смотреть фото Exempt access policy что это. Смотреть картинку Exempt access policy что это. Картинка про Exempt access policy что это. Фото Exempt access policy что это

Рис. 1. Инфраструктура безопасности уровня строк

Зачем изучать RLS?

На первый взгляд тема безопасности уровня строк представляет интерес для администраторов баз данных и администраторов безопасности, а не для разработчиков PL/ SQL и даже проектировщиков архитектуры приложений. Зачем разработчику PL/SQL изучать ее?

Простой пример использования RLS

В нашем примере предикат выглядит так:

При выполнении эта функция возвращает строку SAL RLS будет объяснен позднее.

Наконец, мы создаем политику при помощи функции ADD_P0LICY из встроенного пакета DBMS RLS :

В зависимости от потребностей приложения функция политики может определяться произвольно, но она должна удовлетворять некоторым правилам:

Чтобы снять все ограничения доступа, укажите функцию политики, которая возвращает в качестве предиката один из следующих вариантов:

Аналогичным образом устанавливается ограничение для всех строк: выбирается предикат, результат которого всегда равен FALSE — например, 1=2.

Допустим, вы хотите создать индекс по ключу-функции для столбца SAL ; сценарию создания индекса для этого понадобятся все значения столбца, то есть фактически система безопасности будет обойдена. Пример включения значения INDEX в параметр:

При попытке создания индекса по ключу-функции будет выдана ошибка:

Обратите внимание: политики не являются объектами схемы базы данных, то есть у них нет объекта-владельца. Любой пользователь с привилегией EXECUTE для пакета DBMS_RLS может создать политику. Аналогичным образом, любой пользователь с привилегией EXECUTE может удалить политику. Следовательно, привилегии EXECUTE для этого пакета должны предоставляться только тем пользователям, которым они действительно необходимы.

Как и ожидалось, обновляются только семь строк. Теперь давайте изменим обновляемое значение:

После того как данная политика будет установлена для таблицы, при выполнении того же обновления пользователь Lora получит сообщение об ошибке:

Так как с новым значением столбца SAL — 1200 — все семь строк по-прежнему остаются видимыми, такое обновление разрешается.

Присвойте параметру update_check значение TRUE при определении политики, чтобы избежать непредсказуемого (по крайней мере на первый взгляд) поведения приложения.

Статические и динамические политики

В первом случае функцию политики изменять не нужно — администратор базы данных может предоставить пользователю HR необходимые привилегии:

Во втором способе проблема решается посредством изменения функции политики. Вот как может выглядеть соответствующая функция:

Рассмотрим этот код более подробно.

Приведенный пример демонстрирует крайний случай динамической политики. При возвращении каждой строки политика выполняет функцию, проверяет предикат и решает, стоит или нет пропускать строку. Несомненно, такой подход сопряжен со значительными затратами, потому что базе данных приходится каждый раз проходить полный цикл «разбор — выполнение — выборка».

В следующих разделах будут представлены другие типы политик, появившиеся в Oracle10g и выше.

Новые политики заметно превосходят стандартный динамический тип по производительности. Тем не менее следует учитывать возможные побочные эффекты этих видов политик. Например, поскольку статические политики не выполняют функцию заново, их результаты порой оказываются неожиданными.

Общая статическая политика

Объявляя одну политику для обеих таблиц, мы приказываем базе данных кэшировать результат функции политики, а затем использовать его при последующих вызовах.

Контекстная политика

Как говорилось ранее, статические политики при всей своей эффективности сопряжены с определенным риском; так как функция не выполняется заново при каждой проверке, результаты могут оказаться неожиданными. По этой причине Oracle предоставляет другую разновидность политик — контекстные политики, которые выполняют функцию политики только при изменении контекста приложения в сеансе (см. далее раздел «Контексты приложений»). Пример использования таких политик:

Разность между возвращаемыми значениями функции для конечного и начального момента составляет время в сотых долях секунды. В следующей таблице приведены значения времени отклика для разных типов политик.

Тип политикиВремя отклика (1/100 секунды)
Динамическая133
Контекстная84
Статическая37

Общая контекстная политика

Общие контекстные политики сходны с контекстными политиками, но с ними одна политика используется для нескольких объектов, как было показано ранее для общих статических политик.

Exempt access policy что это. Смотреть фото Exempt access policy что это. Смотреть картинку Exempt access policy что это. Картинка про Exempt access policy что это. Фото Exempt access policy что это

Использование столбцовой модели RLS

Вернемся к примеру приложения отдела кадров из предыдущих разделов. При проектировании политики я руководствовался требованием, согласно которому каждый пользователь может видеть только данные работников своего отдела. Тем не менее в некоторых ситуациях ограничения этой политики могут оказаться слишком жесткими. Предположим, вы хотите защитить данные, чтобы посторонние не интересовались информацией о чужих окладах. Возьмем следующие два запроса:

Первый запрос выводит оклады работников — ту самую информацию, которую вы пытаетесь защитить. В данном случае должны выводиться только данные работников из отдела пользователя. Второй запрос выводит только коды работников. Нужно ли отфильтровать и их, чтобы запрос выводил только коды работников того же отдела? Ответ зависит от политики безопасности, действующей в вашей организации. Возможно, имеются веские причины для вывода вторым запросом всех работников независимо от того, какому отделу они принадлежат. Будет ли механизм RLS эффективным в таких ситуациях?

После назначения этой политики запросы к HR.EMP будут выдавать разные результаты:

Столбцовая модель распространяется не только на список выборки, но и на любые обращения к столбцам, прямые или косвенные. Возьмем следующий запрос:

Теперь рассмотрим несколько иную ситуацию: в предыдущем случае я защитил значения столбцов SAL от отображения в строках, просмотр которых не разрешен пользователю. Однако при этом был отключен вывод всей строки, не только этого конкретного столбца. Теперь допустим, что в соответствии с новыми требованиями маскироваться должен только столбец, а не вся строка, а все остальные столбцы, не содержащие конфиденциальной информации, должны отображаться. Возможно ли это?

Если выдать тот же запрос сейчас, результаты будут другими:

Будьте внимательны при использовании этой возможности, потому что в некоторых случаях она приводит к неожиданным результатам. Допустим, что запрос был выдан пользователем MARTIN :

Так как результаты могут изменяться в зависимости от того, какой пользователь выдал запрос, будьте осторожны с интерпретацией результатов; в противном случае в вашем приложении могут появиться трудноуловимые ошибки.

Здесь RLS позволяет справиться с ситуациями, в которых требуется вывести все строки, но скрыть конфиденциальные значения. До выхода Oracle Database 10g того же результата можно было добиться при помощи представлений, но операции получались куда более сложными.

Отладка RLS

Интерпретация ошибок

Самая распространенная ошибка, с которой вы будете сталкиваться (и одновременно самая простая), — ORA-28110 (ошибка в функции политики или пакете). Исправление ошибок и перекомпиляция функции (или пакета, содержащего функцию) должны решить проблему.

Похоже, данные содержат более одного работника с именем MARTIN : количество выбранных строк превышает 1. Проблема решается либо обработкой ошибки через исключение, либо использованием другого условия в качестве предиката для получения номера отдела.

Исключение ORA-28113 (ошибка в предикате политики) возникает при некорректном построении предиката. Фрагмент файла трассировки с этой ошибкой:

Из этого фрагмента видно, что функция политики возвращает следующий предикат:

Условие синтаксически неверно, поэтому при попытке применения политики происходит сбой и запрос MARTIN не работает. Проблема решается исправлением логики функции политики и возвращением правильного предиката.

Выполнение прямых операций

Экспортирование выполняется успешно, но как видно из выходных данных, при выводе используется традиционный, а не прямой режим. А в процессе выполнения операции к таблице применяются политики RLS — то есть пользователь сможет экспортировать не все строки, а только те, которые ему разрешено видеть.

Из-за успешного завершения операции экспортирования таблицы с RLS может возникнуть ложное впечатление, будто были экспортированы все строки. Однако следует помнить, что экспортируются только те строки, которые пользователю разрешено видеть. Кроме того, хотя экспортирование вроде бы должно было выполняться в прямом режиме, оно выполняется в традиционном режиме.

Теперь при попытке выполнить прямую загрузку/вставку в SQL*Loader выдается сообщение об ошибке:

Exempt access policy что это. Смотреть фото Exempt access policy что это. Смотреть картинку Exempt access policy что это. Картинка про Exempt access policy что это. Фото Exempt access policy что это

Просмотр команд SQL

Представления VPD

Назначение события

Второй способ — назначение события в сеансе:

Любой из этих двух способов позволит вам увидеть точную команду, полученную в результате замены пользовательского запроса.

Источник

14 Using Virtual Private Database to Implement Application Security Policies

Oracle Database provides the necessary tools to build secure applications. One such tool is Virtual Private Database (VPD), which is the combination of the following:

Fine-grained access control, which enables you to associate security policies to database objects

Application context, which enables you to define and access application or database session attributes

VPD combines these two features, enabling you to enforce security policies to control access at the row level. This control is based on application or session attributes, which can be made available during execution.

The following topics introduce these features and explain how and why you would use them:

About Virtual Private Database, Fine-Grained Access Control, and Application Context

Virtual Private Database (VPD) combines server-enforced fine-grained access control with a secure storage of application context values in the Oracle database server. VPD enables you to build applications that enforce row-level security policies at the object level. Policy execution dynamically appends predicates ( WHERE clauses) to any SQL statements that query data you have identified as requiring protection.

The application context feature enables application developers to define, set, and access variable-length application attributes and their values. These attributes can then be used as predicate values for fine-grained access control policies. Two types of application contexts exist:

Local (session-based) application context, stored in the UGA and invoked each time an application user connects to the database

Global application context (non-session-based), stored in the SGA and used for multitiered environment users accessing databases through connection pools.

Although application context is an integral part of VPD, it can be implemented alone, without fine-grained access control. When implemented alone, application context can be used to access session information, such as the client identifier, to preserve user identity across multitiered environments.

The remainder of this chapter discusses how VPD works and introduces its main components, fine-grained access control and application context.

Chapter 15, «Implementing Application Context and Fine-Grained Access Control» for information about using local application context and global application context with or without VPD fine-grained access control policies

«Using the CLIENT_IDENTIFIER Attribute to Preserve User Identity» for information about using the client identifier attribute to preserve user identity across multitiered environments

Introduction to VPD

Virtual private database (VPD) enables you to enforce security, to a fine level of granularity, directly on tables, views, or synonyms. Because security policies are attached directly to tables, views, or synonyms and automatically applied whenever a user accesses data, there is no way to bypass security.

Users need full table access to create table indexes. Consequently, users with privileges to maintain an index can see all the row data even if they do not have full table access under a regular query. To prevent this, apply VPD policies to INDEX statements.

Functions that return predicates can also include calls to other functions. Within your PL/SQL package, you can embed C or Java calls to access operating system information or to return WHERE clauses from an operating system file or central policy store. A policy function can return different predicates for each user, for each group of users, or for each application. Using policy functions over synonyms can substitute for maintaining a separate view for each user or class of users, saving substantial overhead in memory and processing resources.

Consider an HR clerk who is only allowed to see employee records in the Retail Division who initiates the following query:

Column-Level VPD

Column-level VPD enables you to enforce row-level security when a security-relevant column is referenced in a query. You can apply column-level VPD to tables and views, but not to synonyms. By specifying the security-relevant column name with the sec_relevant_cols parameter of the DBMS_RLS.ADD_POLICY procedure, the security policy is applied whenever the column is referenced, explicitly or implicitly, in a query.

For example, users outside of the HR department typically are allowed to view only their own Social Security numbers. When a sales clerk initiates the following query:

The function implementing the security policy returns the predicate ssn=’my_ssn ‘ and the database rewrites the query and executes the following:

«Adding Policies for Column-Level VPD» for information about how to add column-level VPD policies

Column-Level VPD with Column-masking Behavior

If a query references a sensitive column, then the default behavior of column-level VPD restricts the number of rows returned. With column-masking behavior, which can be enabled by using the sec_relevant_cols_opt parameter of the DBMS_RLS.ADD_POLICY procedure, all rows display, even those that reference sensitive columns. However, the sensitive columns display as NULL values.

«Column-masking Behavior» for information about how to add column-level VPD policies with column-masking behavior.

VPD Security Policies and Applications

The security policy is applied within the database itself, rather than within an application. This means that the use of a different application will not bypass the security policy. Security can thus be built once, in the database, instead of being implemented again in multiple applications. VPD therefore provides far stronger security than application-based security, at a lower cost of ownership.

It may be desirable to enforce different security policies depending on which application is accessing data. Consider a situation in which two applications, Order Entry and Inventory, both access the ORDERS table. You may want to have the Inventory application use a policy that limits access based on type of product. At the same time, you may want to have the Order Entry application use a policy that limits access based on customer number.

In this case, you must partition the use of fine-grained access by application. Otherwise, both policies would be automatically AND ed together, which is not the desired result. You can specify one or more policy groups, and a driving application context that determines which policy group is in effect for a given transaction. You can also designate default policies that always apply to data access. In a hosted application, for example, data access should always be limited by subscriber ID.

Introduction to Fine-Grained Access Control

Fine-grained access control enables you to build applications that enforce security policies at a low level of granularity. These policies are also referred to as VPD policies. You can use it, for example, to restrict customers accessing an Oracle database server to see only their own accounts. A physician could be limited to seeing only the records of her own patients, or a manager to seeing only the records of employees who work for him.

Features of Fine-Grained Access Control

Fine-grained access control provides the following capabilities:

Security Policies Based on Tables, Views, and Synonyms

Attaching security policies to tables, views, or synonyms rather than to applications provides greater security, simplicity, and flexibility.

Security

Associating a policy with a table, view, or synonym overcomes a potentially serious application security problem. Suppose a user is authorized to use an application, and then drawing on the privileges associated with that application, wrongfully modifies the database by using an ad hoc query tool, such as SQL*Plus. By attaching security policies to tables, views, or synonyms, fine-grained access control ensures that the same security is in force, no matter how a user accesses the data.

Simplicity

Adding the security policy to the table, view, or synonym means that you make the addition only once, rather than repeatedly adding it to each of your table-based, view-based, or synonym-based applications.

Flexibility

Although you can define a policy against a table, you cannot select that table from within the policy that was defined against the table.

Multiple Policies for Each Table, View, or Synonym

You can establish several policies for the same table, view, or synonym. Suppose, for example, you have a base application for Order Entry, and each division of your company has its own special rules for data access. You can add a division-specific policy function to a table without having to rewrite the policy function of the base application.

Note that all policies applied to a table are enforced with AND syntax. If you have three policies applied to the CUSTOMERS table, then each policy is applied to any access of the table. You can use policy groups and a driving application context to partition fine-grained access control enforcement so that different policies apply, depending upon which application is accessing data. This eliminates the requirement for development groups to collaborate on policies and simplifies application development. You can also have a default policy group that is always applicable (for example, to enforce data separated by subscriber in a hosting environment).

Grouping of Security Policies

Because multiple applications with multiple security policies, can share the same table, view, or synonym, it is important to identify those policies that should be in effect when the table, view, or synonym is accessed.

For example, in a hosting environment, Company A can host the BENEFIT table for Company B and Company C. The table is accessed by two different applications, Human Resources and Finance, with two different security policies. The Human Resources application authorizes users based on ranking in the company, and the Finance application authorizes users based on department. To integrate these two policies into the BENEFIT table would require joint development of policies between the two companies, which is not a feasible option. By defining an application context to drive the enforcement of a particular set of policies to the base objects, each application can implement a private set of security policies.

To do this, you can organize security policies into groups. By referring to the application context, the Oracle Database server determines which group of policies should be in effect at run time. The server enforces all the policies that belong to that policy group.

High Performance

With fine-grained access control, each policy function for a given query is evaluated only once, at statement parse time. Also, the entire dynamically modified query is optimized and the parsed statement can be shared and reused. This means that rewritten queries can take advantage of the high performance features of Oracle Database, such as dictionary caching and shared cursors.

Default Security Policies

The following topics for information about how to implement fine-grained access control:

    About Creating a VPD Policy with Oracle Policy Manager

    To implement VPD, developers can use the DBMS_RLS package to apply security policies to tables and views. They can also use the CREATE CONTEXT command to create application contexts.

    Alternatively, developers can use the Oracle Policy Manager graphical user interface (GUI), accessed from Oracle Enterprise Manager, to apply security policies to schema objects, such as tables and views, and to create application contexts. Oracle Policy Manager provides an easy-to-use interface to manage security policies and application contexts, and therefore makes VPD easier to develop.

    Oracle Policy Manager is also the administration tool for Oracle Label Security. Oracle Label Security provides a functional, out-of-the-box VPD policy that enhances your ability to implement row-level security. It supplies an infrastructure, which is a label-based access control framework, whereby you can specify labels for users and data. It also enables you to create one or more custom security policies to be used for label access decisions. You can implement these policies without any knowledge of a programming language. There is no need to write additional code, but in a single step you can apply a security policy to a given table.

    In this way, Oracle Label Security provides a straightforward, efficient way to implement row-level security policies using data labeling technology. Finally, the structure of Oracle Label Security labels provides a degree of granularity and flexibility that cannot easily be derived from the application data alone. Oracle Label Security is thus a generic solution that can be used in many different circumstances.

    Oracle Label Security Administrator’s Guide for information about using Oracle Policy Manager

    Introduction to Application Context

    Application context enables you to define, set, and access variable-length application attributes and values in a secure data cache available in User Global Area (UGA) and System Global Area (SGA).

    Most applications contain the kind of information that can be used for access control. For example, in an order entry application, the ORDER_NUMBER and the CUSTOMER_NUMBER of the customer can be used as security attributes to restrict his access to his own orders.

    As another example, consider a user running a human resources application. Part of the application initialization process is to determine the kind of responsibility that the user can assume based on user identity. This ID becomes part of the human resource application context. It affects what data the user can access throughout the session.

    You configure application context by using the SQL function SYS_CONTEXT with the following syntax:

    The following subsections describe application context and how to use it:

    Oracle Database SQL Reference for detailed information about using SYS_CONTEXT

    Features of Application Context

    A pplication context provides the following important security features:

    Specifying Attributes for Each Application

    Each application can have its own context with its own attributes. Suppose, for example, you have three applications: General Ledger, Order Entry, and Human Resources. You can specify different attributes for each application:

    For the General Ledger application context, you can specify the attributes SET_OF_BOOKS and TITLE.

    For the Order Entry application context, you can specify the attribute CUSTOMER_NUMBER.

    In each case, you can adapt the application context to your precise security needs.

    Providing Access to Predefined Attributes Through the USERENV Namespace

    Oracle database server provides a built-in application context namespace ( USERENV ) that provides access to predefined attributes. These attributes are session primitives, which is information that the database captures regarding a user session. Examples include the user name, the IP address from which the user connected, and a proxy user name if the user connection is proxied through a middle tier.

    You can use the PROXY_USER attribute within VPD to ensure that users only access data through a particular middle-tier application. As a different approach, you can develop a secure application role to enforce your policy that users access the database only through a specific proxy.

    You can access predefined attributes through the USERENV application context, but you cannot change them. They are listed in Table 14-1.

    Use the following syntax to obtain information about the current session.

    The USERENV application context namespace replaces the USERENV function provided in earlier database releases.

    SYS_CONTEXT in the Oracle Database SQL Reference for complete details about the USERENV namespace and its predefined attributes

    Table 14-1 Key to Predefined Attributes in USERENV Namespace

    Returns the fine-grained auditing cursor ID.

    Returns the identity used in authentication. In the list that follows, the type of user is followed by the value returned:

    Kerberos-authenticated enterprise user: kerberos principal name

    Kerberos-authenticated external user: kerberos principal name, same as the schema name

    SSL authenticated enterprise user: the DN in the user’s PKI certificate

    SSL authenticated external user: the DN in the user’s PKI certificate

    Password authenticated enterprise user: nickname, same as the login name

    Password authenticated database user: the database user name, same as the schema name

    OS authenticated external user: the external operating system user name

    Radius authenticated external user: the schema name

    Proxy with DN: Oracle Internet Directory DN of the client

    Proxy with certificate: certificated DN of the client

    Proxy with username: database user name if client is a local database user, nickname if the client is an enterprise user

    SYSDBA/SYSOPER using password file: login name

    SYSDBA/SYSOPER using OS authentication: operating system user name

    Returns the data being used to authenticate the login user. If the user has been authenticated through SSL, or if the user certificate was proxied to the database, then this includes the X.509 certificate of the user.

    Returns the method of authentication. In the list that follows, the type of user is followed by the method returned:

    Password authenticated enterprise user, local database user, SYSDBA/SYSOPER using password file, proxy with username using password: PASSWORD

    Kerberos authenticated enterprise or external user: KERBEROS

    SSL authenticated enterprise or external user: SSL

    Radius authenticated external user: RADIUS

    OS authenticated external user or SYSDBA/SYSOPER: OS

    Proxy with certificate, DN, or username without using password: NONE

    You can use IDENTIFICATION_TYPE to distinguish between external and enterprise users when the authentication method is PASSWORD, KERBEROS OR SSL.

    Returns the background job ID.

    User-defined client identifier for the session.

    Returns up to 64 bytes of user session information that can be stored by an application using the DBMS_APPLICATION_INFO package.

    Returns the bind variables for fine-grained auditing. Maximum length is 4K.

    Returns the name of the default schema being used in the current session. This can be changed with an ALTER SESSION SET SCHEMA statement.

    Returns the identifier of the default schema being used in the current session. This can be changed with an ALTER SESSION SET SCHEMAID statement.

    Returns the SQL text of the query that triggers fine-grained audit or row-level security (RLS) policy functions or event handlers. Only valid inside the function or event handler.

    CURRENT_SQL1 to CURRENT_SQL7

    Returns 4K length substrings of the SQL query text that triggers fine-grained audit or row-level security (RLS) policy functions or audit event handlers. This is valid only inside the RLS policy function or event handler. Maximum length is 32K. For example, if a user issued a 32 K length SQL statement, then CURRENT_SQL returns 0 to 4K, CURRENT_SQL1 returns 5K to 8K, CURRENT_SQL2 returns 9K to 12K, and so on.

    Returns the length of the current SQL statement that triggers fine-grained audit or row-level security (RLS) policy functions or event handlers. Only valid inside the function or event handler.

    Returns the domain of the database as specified in the DB_DOMAIN initialization parameter

    Returns the name of the database as specified in the DB_NAME initialization parameter

    Returns available auditing entry identifier. Incremented for every audit record for a SQL statement. Note that there can be more than one audit record for the same SQL statement.

    Returns the user’s enterprise-wide identity:

    For enterprise users: Oracle Internet Directory DN

    For external users: the external identity (kerberos principal name, Radius schema name, OS user name, certificate DN)

    For local users and SYSDBA/SYSOPER logins: NULL

    The value of the attribute differs by proxy method:

    For a proxy with DN: Oracle Internet Directory DN of the client

    For a proxy with certificate: certificate DN of the client for external users, Oracle Internet Directory DN for global users

    For a proxy with username: Oracle Internet Directory DN if the client is an enterprise user, NULL if the client is a local database user

    Returns the foreground job ID.

    Amount of shared memory used by global application context, in bytes.

    Returns the user login name from Oracle Internet Directory.

    Returns the name of the host machine on which the database is running.

    Returns the way the user’s schema was created in the database. Specifically, it reflects the IDENTIFIED clause in the CREATE/ALTER USER syntax. In the list that follows, the syntax used during schema creation is followed by the IDENTIFICATION_TYPE returned:

    IDENTIFIED BY password : LOCAL

    IDENTIFIED EXTERNALLY : EXTERNAL

    IDENTIFIED GLOBALLY : GLOBAL SHARED

    IDENTIFIED GLOBALLY AS DN : GLOBAL PRIVATE

    Returns instance identification number of the current instance.

    Returns the name of the instance.

    Returns the IP address (when available) of the machine from which the client is connected.

    Returns TRUE if you currently have the DBA role enabled and FALSE if not.

    Returns the abbreviation for the language name

    Returns the language and territory currently used by the session, along with the database character set in the form: language_territory.characterset

    Returns the protocol named in the connect string ( PROTOCOL = protocol ).

    Returns the territory of the current session.

    Returns the currency symbol of the current session.

    Returns the calendar used for dates in the current session.

    Returns the current date format of the current session.

    Returns language used to express dates in the current session.

    Indicates whether the sort base is binary or linguistic.

    Returns the operating system user name of the client process that initiated the database session.

    Returns the invoker of row-level security policy functions.

    Returns the name of the database user (typically middle tier) who opened the current session on behalf of SESSION_USER.

    Returns the host name of machine on which the instance is running.

    Returns the database user name by which the current user is authenticated.

    Returns the identifier of the database user name by which the current user is authenticated.

    Returns the auditing session identifier.

    Returns the session number (different from the session ID).

    Returns available auditing statement identifier. Incremented once for every SQL statement audited in a session.

    Returns the operating system identifier for the client of the current session. Virtual in TCP/IP.

    Table 14-2 lists the attributes of namespace USERENV that have been deprecated. Oracle suggests that you use the alternatives suggested in the Comments column.

    Table 14-2 Deprecated Attributes of Namespace USERENV

    Predefined AttributeFunction

    Use the SESSION_USER parameter instead.

    Use the SESSION_USERID parameter instead.

    This parameter returned the external name of the user. More complete information can now be obtained from the AUTHENTICATED_IDENTITY and ENTERPRISE_IDENTITY parameter.

    Externalized Application Contexts

    Many applications store attributes used for fine-grained access control within a database metadata table. For example, an EMPLOYEES table could include cost center, title, signing authority, and other information useful for fine-grained access control. Organizations also centralize user information for user management and access control in LDAP-based directories, such as Oracle Internet Directory. Application context attributes can be stored in Oracle Internet Directory and assigned to one or more enterprise users. They can be retrieved automatically upon login for an enterprise user and then used to initialize an application context.

    Enterprise User Security is a feature of Oracle Advanced Security.

    «Initializing Secure Application Context Externally» for information about initializing local application context through external resources such as an OCI interface, a job queue process, or a database link

    «Initializing Secure Application Context Globally» for information about initializing local application context through a centralized resource, such as Oracle Internet Directory

    Ways to Use Application Context with Fine-Grained Access Control

    To simplify security policy implementation, you can use application context within a fine-grained access control function.

    Application context can be used in the following ways with fine-grained access control:

    Secure Data Caching

    Accessing an application context inside your fine-grained access control policy function is like writing down an often-used phone number and posting it next to your phone, where you can find it easily rather than looking it up every time you need it.

    For example, suppose you base access to the ORDERS_TAB table on customer number. Rather than querying the customer number for a logged-in user each time you need it, you could store the number in the application context. In this way, the customer number is available in the session when you need it.

    Application context is especially helpful if your security policy is based on multiple security attributes. For example, if a policy function bases a predicate on four attributes (such as employee number, cost center, position, spending limit), then multiple subqueries must execute to retrieve this information. Instead, if this data is available through application context, then performance is much faster.

    Returning a Specific Predicate (Security Policy)

    You can use application context to return the correct security policy, enforced through a predicate.

    Consider an order entry application that enforces the following rules: customers only see their own orders, and clerks see all orders for all customers. These are two different policies. You could define an application context with a Position attribute, and this attribute could be accessed within the policy function to return the correct predicate, depending on the value of the attribute. Thus, you can enable a user in the Clerk position to retrieve all orders, but a user in the Customer position to see only those records associated with that particular user.

    To design a fine-grained access control policy to return a specific predicate for an attribute, access the application context within the function that implements the policy. For example, to limit customers to seeing only their own records, use fine-grained access control to dynamically modify user queries as from this:

    to the following query:

    Providing Attributes Similar to Bind Variables in a Predicate

    Continuing with the preceding example, suppose you have 50,000 customers, and you do not want to have a different predicate returned for each customer. Customers all share the same predicate, which prescribes that they can only see their own orders. It is merely their customer numbers that are different.

    Using application context, you can return one predicate within a policy function that applies to 50,000 customers. As a result, there is one shared cursor that executes differently for each customer, because the customer number is evaluated at execution time. This value is different for every customer. Use of application context in this case provides optimum performance, as well as row-level security.

    Note that the SYS_CONTEXT function works much like a bind variable, only if the SYS_CONTEXT arguments are constants.

    Introduction to Global Application Context

    In many application architectures, the middle-tier application is responsible for managing session pooling for application users. Users authenticate themselves to the application, which uses a single identity to log in to the database and maintains all the connections. In this environment, it is not possible to maintain application attributes using session-dependent application context (local application context) because of the sessionless model of the application.

    Another scenario is when a user is connected to the database through an application (such as Oracle Forms), which then spawns other applications (such as Oracle Reports) to connect to the database. These applications may need to share the session attributes such that they appear to be sharing the same database session.

    Global application context is a type of secure application context that can be shared among trusted sessions. In addition to driving the enforcement of the fine-grained access control policies, applications (especially middle-tier products) can use this support to manage application attributes securely and globally.

    Global application context is not available in Real Application Clusters.

    Oracle Connection Manager, a router provided with Oracle Net Services, cannot be used with global application context.

    Enforcing Application Security

    This section contains information about enforcing application security. This section consists of the following topics:

    Use of Ad Hoc Tools: A Potential Security Problem

    Prebuilt database applications explicitly control the potential actions of a user, including the enabling and disabling of user roles while using the application. By contrast, ad hoc query tools such as SQL*Plus, allow a user to submit any SQL statement (which may or may not succeed), including the enabling and disabling of any granted role.

    Potentially, an application user can exercise the privileges attached to that application to issue destructive SQL statements against database tables by using an ad hoc tool.

    For example, consider the following scenario:

    The Vacation application has a corresponding VACATION role.

    The Vacation application controls the use of privileges obtained through the VACATION role.

    Now, consider a user who has been granted the VACATION role. Suppose that, instead of using the Vacation application, the user executes SQL*Plus. At this point, the user is restricted only by the privileges granted to him explicitly or through roles, including the VACATION role. Because SQL*Plus is an ad hoc query tool, the user is not restricted to a set of predefined actions, as with designed database applications. The user can query or modify data in the EMP_TAB table as he or she chooses.

    Restricting SQL*Plus Users from Using Database Roles

    This section presents features that you may use in order to restrict SQL*Plus users from using database roles and thus, prevent serious security problems. These features include the following:

    Limiting Roles Through PRODUCT_USER_PROFILE

    For example, you could create an entry in the PRODUCT_USER_PROFILE table to:

    Disallow the use of the CLERK and MANAGER roles with SQL*Plus

    Disallow the use of SET ROLE with SQL*Plus

    Use of the PRODUCT_USER_PROFILE table does not completely guarantee security, for multiple reasons. In the preceding example, while SET ROLE is disallowed with SQL*Plus, if Jane had other privileges granted to her directly, then she could exercise these using SQL*Plus.

    SQL*Plus User’s Guide and Reference for more information about the PRODUCT_USER_PROFILE table

    Using Stored Procedures to Encapsulate Business Logic

    Stored procedures encapsulate use of privileges with business logic so that privileges are only exercised in the context of a well-formed business transaction. For example, an application developer might create a procedure to update employee name and address in the EMPLOYEES table, which enforces that the data can only be updated in normal business hours. Also, rather than grant a human resources clerk the UPDATE privilege on the EMPLOYEES table, a developer (or application administrator) may grant the privilege on the procedure only. Then, the human resources clerk can exercise the privilege only in the context of the procedures, and cannot update the EMPLOYEES table directly.

    Using VPD for Highest Security

    Virtual Private Database (VPD) provides the benefit of strong security policies, which apply directly to data. When you use VPD, you can enforce security no matter how a user gets to the data: whether through an application, through a query, or by using a report-writing tool.

    «How to Add a Policy to a Table, View, or Synonym» for information about using the DBMS_RLS.ADD_POLICY procedure to add policies for VPD.

    VPD and Oracle Label Security Exceptions and Exemptions

    VPD and Oracle Label Security are not enforced during DIRECT path export. Also, VPD policies and Oracle Label Security policies cannot be applied to objects in the SYS schema. As a consequence, the SYS user and users making a DBA-privileged connection to the database (for example, CONNECT/AS SYSDBA ) do not have VPD or Oracle Label Security policies applied to their actions. The database user SYS is thus always exempt from VPD or Oracle Label Security enforcement, regardless of the export mode, application, or utility used to extract data from the database. However, SYSDBA actions can be audited by enabling such auditing upon installation and specifying that this audit trail be stored in a secure location in the operating system.

    EXEMPT ACCESS POLICY is a very powerful privilege and should be carefully managed. It is inadvisable to grant this privilege WITH ADMIN OPTION because very few users should have this exemption.

    The SYS_CONTEXT values that VPD uses are not propagated to secondary databases for failover.

    User Models and VPD

    Oracle enables applications to enforce fine-grained access control for each user, regardless of whether that user is a database user or an application user unknown to the database.

    When application users are also database users, VPD enforcement is relatively simple. Users connect to the database, and the application sets up application contexts for each session. As each session is initiated under a different user name, it is simple to enforce different fine-grained access control conditions for each such user. Even proxy authentication permits different fine-grained access control for each user, because each session (OCI or thick JDBC) is a distinct database session with its own application context.

    When proxy authentication is integrated with Enterprise User Security, user roles and other attributes can be retrieved from Oracle Internet Directory to enforce VPD. (In addition, globally initialized application context can also be retrieved from the directory.)

    Web-based applications typically have hundreds if not thousands of users. Even when there are persistent connections to the database, supporting data retrieval for many user requests, these connections are not specific to particular Web-based users. Instead, Web-based applications typically set up and reuse connections, to provide scalability, rather than having different sessions for each user. For example, when Web users Jane and Ajit connect to a middle tier application, it may establish a single database session that it uses on behalf of both users. Typically, neither Jane nor Ajit is known to the database. The application is responsible for switching the user name on the connection, so that, at any given time, it is either Jane or Ajit using the session.

    Oracle Database VPD facilitates connection pooling by allowing multiple connections to access more than one global application context. This capability makes it unnecessary to establish a separate application context for each distinct user session.

    Table 14-3 summarizes how VPD applies to various user models.

    Источник

    Добавить комментарий

    Ваш адрес email не будет опубликован. Обязательные поля помечены *

    Predefined AttributeComments