Oracle создание файла паролей
В документации к Oracle указано, что имеется ограничение на количество пользователей включаемых в файл паролей. Оно зависит от размера блока операционной системы и кратно четырём. Так, например, для блока размером в 512 байт количество пользователей, которые могут храниться в файле паролей равно четырём. Попробуем на примере проверить так ли это на самом деле. Постепенно будем добавлять в файл паролей новых пользователей и посмотрим, что произойдёт.
Два пользователя SYS и USER1 в файле паролей у нас уже есть. Добавляем остальных:
При включении пользователя USER5 вышла ошибка, сигнализирующая о том, что файл паролей полон. Вроде все, так как и описано в документации. Правда, с пользователем SYS это уже будет 5 пользователей, но всё равно это уже ближе к истине. Так почему же именно такое количество пользователей может находиться в файле паролей по умолчанию и как можно расширить этот предел? Попробуем разобраться в этом на примерах.
Вновь создаваемый файл паролей по умолчанию всегда имеет определённый размер 1536 байт. Почему именно такой размер, а не другой? Попробуем разделить это число на 512. Получиться 3. Значит, файл паролей условно можно разделить на три блока по 512 байт. Вроде многовато места будет для хранения только 5 пользователей. Заглянем внутрь файла. Для начала выведем первые 512 байт файла:
Как видно это блок почти пуст, добавленных пользователей здесь нет. Поэтому заглянем во второй блок:
Здесь уже интереснее. Во втором блоке можно обнаружить пользователей SYS и USER1. Нетрудно догадаться так же, что остальные пользователи будут находиться в третьем блоке.
В последний блок влезли данные только о трёх пользователях. Пользователь USER5 здесь явно не поместился, хотя место для него имеется. Получается, что в документации отражены неверные сведения о четырёх пользователей в 512 байтном блоке? Проясним этот вопрос.
Ясно, что для того чтобы добавить ещё пользователей, придётся расширять файл паролей, то есть создавать его заново. Для этого в утилите ORAPWD есть опция ENTRIES, в которой, задаётся число планируемых пользователей в файле паролей. Попробуем пересоздать файл с этой опцией. В параметре укажем пять пользователей, так четыре пользователя (не считая SYS) у нас уже есть:
Посмотрим на размер файла:
Он прибавил в размере. Причём на 512 байт, один блок. Повторим добавление в файл паролей пользователей USER1 – USER4 и попробуем создать и добавить пользователя USER5:
Пользователь добавился. Попробуем добавить ещё одного:
Добавление так же прошло успешно. Почему? Ведь при создании файла было введено ограничение на 5 пользователей. Ответ на это найдём в документации Oracle. В ней сказано, что пользователи будут добавляться в файл паролей до тех пор, пока блок не будет заполнен полностью. Так как выше было выяснено, что в последнем блоке из 512 байт размещается 3 пользователя, в файл паролей можно будет добавить ещё одного пользователя USER7, после чего этот файл потребуется ещё раз пересоздать с новым значением ENTRIES:
Почему в файл паролей добавился пользователь USER8? Ведь по умолчанию в последнем блоке файла паролей помещалось только три пользователя. Оказывается, документация Oracle не соврала. В блоке из 512 байт действительно помещается 4 пользователя, правда только не в самом последнем блоке. Проверим это. Попробуем добавить ещё одного пользователя USER9:
Возникла ошибка. И так, файл паролей, состоящий из 4 блоков по 512 байт, на данный момент времени содержит восемь пользователей. Первый, из них, всегда располагается во втором блоке, четыре других в третьем и три последних пользователя в четвёртом. Такое расположение пользователей в файле паролей следует учитывать при задании опции ENTRIES. В приведённом примере можно задавать любое значение этой опции 6, 7, 8. Результат будет одинаковый. По сути, данная опция служит только для ограничения выделяемого пространства для файла паролей и лишь косвенно влияет на количество пользователей в нём.
Sharing and Disabling the Password File
NONE : Setting this parameter to NONE causes Oracle Database to behave as if the password file does not exist. That is, no privileged connections are allowed over nonsecure connections.
EXCLUSIVE : (The default) An EXCLUSIVE password file can be used with only one instance of one database. Only an EXCLUSIVE file can be modified. Using an EXCLUSIVE password file enables you to add, modify, and delete users. It also enables you to change the SYS password with the ALTER USER command.
SHARED : A SHARED password file can be used by multiple databases running on the same server, or multiple instances of an Oracle Real Application Clusters (Oracle RAC) database. A SHARED password file cannot be modified. This means that you cannot add users to a SHARED password file. Any attempt to do so or to change the password of SYS or other users with the SYSDBA or SYSOPER privileges generates an error. All users needing SYSDBA or SYSOPER system privileges must be added to the password file when REMOTE_LOGIN_PASSWORDFILE is set to EXCLUSIVE . After all users are added, you can change REMOTE_LOGIN_PASSWORDFILE to SHARED , and then share the file.
This option is useful if you are administering multiple databases or an Oracle RAC database.
If REMOTE_LOGIN_PASSWORDFILE is set to EXCLUSIVE or SHARED and the password file is missing, this is equivalent to setting REMOTE_LOGIN_PASSWORDFILE to NONE .
You cannot change the password for SYS if REMOTE_LOGIN_PASSWORDFILE is set to SHARED . An error message is issued if you attempt to do so.
Keeping Administrator Passwords Synchronized with the Data Dictionary
If you change the REMOTE_LOGIN_PASSWORDFILE initialization parameter from NONE to EXCLUSIVE or SHARED , or if you recreate the password file with a different SYS password, then you must ensure that the passwords in the data dictionary and password file for the SYS user are the same.
To synchronize the SYS passwords, use the ALTER USER statement to change the SYS password. The ALTER USER statement updates and synchronizes both the dictionary and password file passwords.
To synchronize the passwords for non- SYS users who log in using the SYSDBA or SYSOPER privilege, you must revoke and then regrant the privilege to the user, as follows:
Find all users who have been granted the SYSDBA privilege.
Revoke and then re-grant the SYSDBA privilege to these users.
Find all users who have been granted the SYSOPER privilege.
Revoke and regrant the SYSOPER privilege to these users.
Подключение с использованием файла паролей
Для того чтобы аутентифицироваться в локальной или удалённой базе данных с использованием файла паролей, пользователь при подключении должен указать этот вид аутентификации. Сделать это можно разными способами. Например, в утилите SQLPLUS для этого используются служебные слова AS SYSDBA или AS SYSOPER, которые могут быть указаны в команде CONNECT или в аргументах запуска утилиты из командной строки:
Некоторые утилиты oracle, такие как RMAN, вообще не требуют указания ключевых слов. Подключение с использованием файла паролей у них идет по умолчанию:
Что же касается сторонних утилит, то тут возможность подключения пользователя с использованием файла паролей полностью ложиться на плечи их разработчиков и зависит от целей, для которых эти утилиты предназначаются. В большинстве случаев такая поддержка, конечно, реализуется, ведь её отсутствие делает, например, невозможным подключение пользователя SYS, для которого вид аутентификации по файлу паролей является единственно возможным:
Хотя в большинстве утилит Oracle возможность аутентификации с использованием файла паролей реализована, работа пользователя в данном режиме подключения обычно не рекомендуется. Исключения здесь составляют только административные действия с базой данных и доступ к специфической служебной информации, например x$ таблицы. Стоит учитывать, что данный вид аутентификации использует совершенно другие алгоритмы подключения к базе данных, в корне отличающиеся от обычных соединений. Например, когда пользователь подключается к базе данных с привилегиями SYSDBA (SYSOPER) ему определяется схема по умолчанию SYS (PUBLIC), а вовсе не схема соответствующая его имени, как это происходит при обычном подключении:
Из-за этого несоответствия могут возникнуть ошибки при доступе к объектам расположенным в схеме пользователя, если в командах не прописана схема или в системе отсутствуют синонимы на объект.
Так как пользователь, соединяющийся с использованием файла паролей, подключается как пользователь SYS, все действия такого пользователя не попадают в основную базу стандартного аудита. Это сильно затрудняет наблюдение за ним. По той же причине триггеры на уровне базы данных не срабатывают для данного вида подключения. Об этом то же стоит не забывать.
10.6.2 Recovering from Permanent Media Failure Using a Control File Copy
If there is permanent media failure, then you can recover by using a control file copy.
This method assumes that one of the control files specified in the CONTROL_FILES parameter is inaccessible due to a permanent media failure and that you have a multiplexed copy of the control file.
- With the instance shut down, use an operating system command to copy the current copy of the control file to a new, accessible location:
If you have multiplexed control files, you can get the database started up quickly by editing the CONTROL_FILES initialization parameter. Remove the bad control file from CONTROL_FILES setting and you can restart the database immediately. Then you can perform the reconstruction of the bad control file and at some later time shut down and restart the database after editing the CONTROL_FILES initialization parameter to include the recovered control file.
10.8 Control Files Data Dictionary Views
You can query a set of data dictionary views for information about control files.
The following views display information about control files:
Displays database information from the control file
Lists the names of control files
Displays information about control file record sections
Displays the names of control files as specified in the CONTROL_FILES initialization parameter
Администратору базы данных Oracle часто приходиться выполнять специальные операции, например, такие, как завершение или запуск базы данных. Поскольку исполнять их должен только он, а никто другой, его учётная запись требует безопасной аутентификации. Существует несколько способов аутентификации. Кроме использования стандартной аутентификации по словарю, для администратора базы данных доступны ещё три способа:
- Аутентификация операционной системы
- Аутентификация на основе файла паролей
- Устойчивая аутентификация на основе сетевой службы, такой как, например Oracle Internet Directory
Все три последних метода аутентифицируют административного пользователя даже тогда, когда база данных ещё не запущена.
Как известно, административные привилегии, которые требуются для выполнения основных операций с базой данных, предоставляются через две специальных системных привилегии SYSDBA и SYSOPER. Эти привилегии дают пользователю доступ к экземпляру даже тогда, когда он остановлен, и могут рассматриваться как специальные типы соединений, позволяющие выполнять команды, привилегии на которые не могут быть выданы обычными средствами.
Для аутентификации таких привилегированных пользователей, Oracle может использоваться специально созданный файл паролей. Чтобы данный метод аутентификации заработал, необходимо выполнение трёх условий. Должен быть правильно установлен один из параметров инициализации, файл паролей должен быть создан, в файл должны быть добавлены учётные записи пользователей имеющих привилегии SYSDBA и SYSOPER.
Рассмотрим более подробно этот процесс. Так как большинство примеров будет производиться локально, от имени пользователя операционной системы oracle, временно отберём у него группу dba, чтобы его аутентификация в базе данных не происходила на основе операционной системы:
Здесь стоит упомянуть, что аутентификация операционной системы является превалирующей над аутентификацией на основе файла паролей.
Viewing Password File Members
Use the V$PWFILE_USERS view to see the users who have been granted the SYSDBA , SYSOPER , or SYSASM system privileges. The columns displayed by this view are as follows:
Column | Description |
---|---|
USERNAME | This column contains the name of the user that is recognized by the password file. |
SYSDBA | If the value of this column is TRUE , then the user can log on with the SYSDBA system privileges. |
SYSOPER | If the value of this column is TRUE , then the user can log on with the SYSOPER system privileges. |
SYSASM | If the value of this column is TRUE , then the user can log on with the SYSASM system privileges. |
SYSASM is valid only for Oracle Automatic Storage Management instances.
Creating a Password File with ORAPWD
The syntax of the ORAPWD command is as follows:
Command arguments are summarized in the following table.
Argument | Description |
---|---|
FILE | Name to assign to the password file. You must supply a complete path. If you supply only a file name, the file is written to the current directory. |
ENTRIES | (Optional) Maximum number of entries (user accounts) to permit in the file. |
FORCE | (Optional) If y , permits overwriting an existing password file. |
IGNORECASE | (Optional) If y , passwords are treated as case-insensitive. |
There are no spaces permitted around the equal-to (=) character.
The command prompts for the SYS password and stores the password in the created password file.
The following command creates a password file named orapworcl that allows up to 30 privileged users with different passwords.
10.4.2 Handling Errors During CREATE CONTROLFILE
If Oracle Database sends you an error when you attempt to mount and open the database after creating a new control file, the most likely cause is that you omitted a file from the CREATE CONTROLFILE statement or included one that should not have been listed.
Typically, the error is ORA-01173 , ORA-01176 , ORA-01177 , ORA-01215 , or ORA-01216 . In this case, you should restore the files you backed up in "Creating New Control Files" and repeat the procedure in that task, using the correct file names.
10.2 Guidelines for Control Files
You can follow guidelines to manage the control files for a database.
Expanding the Number of Password File Users
If you receive the file full error ( ORA-1996 ) when you try to grant SYSDBA or SYSOPER system privileges to a user, you must create a larger password file and regrant the privileges to the users.
Replacing a Password File
Use the following procedure to replace a password file:
Identify the users who have SYSDBA or SYSOPER privileges by querying the V$PWFILE_USERS view.
Delete the existing password file.
Follow the instructions for creating a new password file using the ORAPWD utility in "Creating a Password File with ORAPWD". Ensure that the ENTRIES parameter is set to a number larger than you think you will ever need.
10.6 Recovering a Control File Using a Current Copy
You can recover your control file from a current backup or from a multiplexed copy.
10.6.1 Recovering from Control File Corruption Using a Control File Copy
If a control file becomes corrupted, then you can recover it using a control file copy.
This method assumes that one of the control files specified in the CONTROL_FILES parameter is corrupted, that the control file directory is still accessible, and that you have a multiplexed copy of the control file.
- With the instance shut down, use an operating system command to overwrite the bad control file with a good copy:
Просмотр пользователей включённых в файл паролей
В файле паролей на данный момент времени должны присутствовать три пользователя SYS, USER1 и USER2. Как убедиться, что они действительно туда попали? Конечно, можно просто посмотреть содержимое двоичного файла, но есть и более простой путь - это системное представление V$PWFILE_USERS:
Как видно из запроса, в файле паролей присутствуют три пользователя USER1, USER2 и SYS. Представление показывает не только присутствие этих пользователей в файле, но и предоставляет информацию о том, какие из привилегий SYSDBA и SYSOPER были выданы пользователю. Эта информация может быть полезна в дальнейшем при исключении пользователя из файла паролей или пересоздании файла.
10.3.1 Creating Initial Control Files
The initial control files of an Oracle Database are created when you issue the CREATE DATABASE statement.
The names of the control files are specified by the CONTROL_FILES parameter in the initialization parameter file used during database creation. The file names specified in CONTROL_FILES should be fully specified and are operating system specific. The following is an example of a CONTROL_FILES initialization parameter:
If files with the specified names currently exist at the time of database creation, you must specify the CONTROLFILE REUSE clause in the CREATE DATABASE statement, or else an error occurs. Also, if the size of the old control file differs from the SIZE parameter of the new one, you cannot use the REUSE clause.
The size of the control file changes between some releases of Oracle Database, as well as when the number of files specified in the control file changes. Configuration parameters such as MAXLOGFILES , MAXLOGMEMBERS , MAXLOGHISTORY , MAXDATAFILES , and MAXINSTANCES affect control file size.
You can subsequently change the value of the CONTROL_FILES initialization parameter to add more control files or to change the names or locations of existing control files.
Your operating system specific Oracle documentation contains more information about specifying control files.
Maintaining a Password File
This section describes how to:
Expand the number of password file users if the password file becomes full
Remove the password file
Granting and Revoking SYSDBA and SYSOPER Privileges
If your server is using an EXCLUSIVE password file, use the GRANT statement to grant the SYSDBA or SYSOPER system privilege to a user, as shown in the following example:
Use the REVOKE statement to revoke the SYSDBA or SYSOPER system privilege from a user, as shown in the following example:
Because SYSDBA and SYSOPER are the most powerful database privileges, the WITH ADMIN OPTION is not used in the GRANT statement. That is, the grantee cannot in turn grant the SYSDBA or SYSOPER privilege to another user. Only a user currently connected as SYSDBA can grant or revoke another user's SYSDBA or SYSOPER system privileges. These privileges cannot be granted to roles, because roles are available only after database startup. Do not confuse the SYSDBA and SYSOPER database privileges with operating system roles.
Oracle Database Security Guide for more information on system privileges
10.2.2 Multiplex Control Files on Different Disks
Every Oracle Database should have at least two control files, each stored on a different physical disk.
If a control file is damaged due to a disk failure, the associated instance must be shut down. Once the disk drive is repaired, the damaged control file can be restored using the intact copy of the control file from the other disk and the instance can be restarted. In this case, no media recovery is required.
The behavior of multiplexed control files is this:
The database writes to all file names listed for the initialization parameter CONTROL_FILES in the database initialization parameter file.
The database reads only the first file listed in the CONTROL_FILES parameter during database operation.
If any of the control files become unavailable during database operation, the instance becomes inoperable and should be aborted.
Oracle strongly recommends that your database has a minimum of two control files and that they are located on separate physical disks.
One way to multiplex control files is to store a control file copy on every disk drive that stores members of redo log groups, if the redo log is multiplexed. By storing control files in these locations, you minimize the risk that all control files and all groups of the redo log will be lost in a single disk failure.
10.5 Backing Up Control Files
Use the ALTER DATABASE BACKUP CONTROLFILE statement to back up your control files.
You have two options:
Back up the control file to a binary file (duplicate of existing control file) using the following statement:
Produce SQL statements that can later be used to re-create your control file:
This command writes a SQL script to a trace file where it can be captured and edited to reproduce the control file. View the alert log to determine the name and location of the trace file.
Oracle Database Backup and Recovery User's Guide for more information on backing up your control files
Пароли чувствительные к регистру
Начиная с одиннадцатой версии, в Oracle введена возможность использовать пароли с учётом регистра. Для обычных подключений по умолчанию этот режим включен и определяется параметром инициализации SEC_CASE_SENSITIVE_LOGON:
Файл паролей по умолчанию так же использует пароли чувствительные к регистру. Причём этот режим никак не зависит от установок параметра SEC_CASE_SENSITIVE_LOGON. Продемонстрируем это на примере.
Для начала выключим зависимость паролей от регистра:
Перезагрузим экземпляр. Изменим пароль пользователя USER1 на верхний регистр:
Теперь попробуем подключиться к экземпляру в обычном режиме и с помощью файла паролей:
Как видно, при аутентификации с помощью файла паролей, пароль зависит от регистра независимо от того, что параметр SEC_CASE_SENSITIVE_LOGON выключен.
Если возникает необходимость в том, что бы пароли пользователей, включённые в файл паролей, не зависели от регистра, то необходимо, при создании файла с помощью утилиты ORAPWD, указать опцию IGNORECASE. Попробуем продемонстрировать это на примере. Для начала пересоздадим файл паролей с данной опцией:
Теперь пароли пользователей, помещаемых во вновь созданный файл, не будут зависеть от регистра. Проверим это. Так как файл был создан заново, включим в него опять пользователя USER1 и попробуем под ним подключиться:
Как видно подключение прошло успешно в не зависимости от того, в каком регистре пароль был набран.
10.2.4 Manage the Size of Control Files
The main determinants of the size of a control file are the values set for the MAXDATAFILES , MAXLOGFILES , MAXLOGMEMBERS , MAXLOGHISTORY , and MAXINSTANCES parameters in the CREATE DATABASE statement that created the associated database.
Increasing the values of these parameters increases the size of a control file of the associated database.
Your operating system specific Oracle documentation contains more information about the maximum control file size.
Oracle Database SQL Language Reference for a description of the CREATE DATABASE statement
10.2.3 Back Up Control Files
It is very important that you back up your control files. This is true initially, and every time you change the physical structure of your database.
Such structural changes include:
Adding, dropping, or renaming data files
Adding or dropping a tablespace, or altering the read/write state of the tablespace
Adding or dropping redo log files or groups
The methods for backing up control files are discussed in "Backing Up Control Files" .
Создание файла паролей
По умолчанию файл паролей создаётся в процессе установки Oracle Database помощником по конфигурированию сервера базы данных (DBCA). В системе UNIX файл имеет формат имени вида orapwORACLE_SID и располагается в каталоге ORACLE_HOME/dbs. В Windows, файл будет называться PWDORACLE_SID.ora и находится в каталоге ORACLE_HOME\database.
Ниже предоставлены различные примеры названий такого файла:
Если файл паролей, по каким то причинам отсутствует или требуется его пересоздание, то можно использовать утилиту ORAPWD. Синтаксис этой команды имеет следующий вид:
Аргумент FILE задаёт имя файла и путь файла пароля, ENTRIES – максимальное количество учётных записей в файле, FORCE – задаёт флаг, который отвечает за генерацию ошибки, если файл с таким именем уже существует, IGNORECASE – позволяет включать, выключать пароль, зависящий от регистра.
Рассмотрим более подробно на примерах создание файла паролей. Для начала определим наличие файла:
В системе присутствует файл паролей orapworcl , который был создан по умолчанию при установке. Удалим его и создадим новый:
Новый файл создан. В него добавлен пользователь SYS , пароль которого запрашивался при запуске утилиты. Если попытаться повторить процедуру создания файла снова, то будет сгенерирована ошибка о том, что такой файл присутствует, и что его надо переименовать или удалить:
Чтобы подавить такой вывод ошибки и пересоздать файл, необходимо при запуске orapwd указать опцию force=y:
Данная опция может быть полезна в пакетных командных файлах.
10.4 Troubleshooting After Creating Control Files
After issuing the CREATE CONTROLFILE statement, you may encounter some errors.
Безопасность
Если посмотреть дамп второго блока файла паролей, то среди его содержимого можно найти интересного пользователя INTERNAL. Представление V$PWFILE_USERS его не показывает, но он действительно включён в файл паролей. Данный пользователь применялся в качестве административного пользователя в предыдущих релизах Oracle (до 8.2 версии). Его предназначение в старших релизах Oracle неизвестно.
Почему данный пользователь не виден в представлении V$PWFILE_USERS? Ответ становиться очевиден, если заглянуть в исходный код представления:
Информация о пользователях, включённых в файл паролей, выводится из динамической таблицы. X$KZSRT. Пользователь INTERNAL отсекается на уровне представления.
Кстати, таким образом можно исключить вывод в представлении V$PWFILE_USERS любого пользователя включённого в файл паролей. Этим могут воспользоваться злоумышленники, оставляющие потайные входы в базу данных. Поэтому стоит время от времени делать запрос непосредственно к таблице X$KZSRT на факт выявления несанкционированных пользователей.
Пользователи, включённые в файл паролей – это пользователя обладающие очень большими возможностями, поэтому не стоит бездумно предоставлять привилегии SYSDBA и SYSOPER каждому пользователю.
Стоит так же ограничивать доступ к файлу паролей и на уровне операционной системы. Даже если файл доступен только для чтения, в нём хранятся хэши паролей, зная которые можно при наличии специальных инструментов получит пароль привилегированных пользователей.
You can create a password file using the password file creation utility, ORAPWD . For some operating systems, you can create this file as part of your standard installation.
This section contains the following topics:
10.4.1 Checking for Missing or Extra Files
After creating a new control file and using it to open the database, check the alert log to see if the database has detected inconsistencies between the data dictionary and the control file, such as a data file in the data dictionary includes that the control file does not list.
If a data file exists in the data dictionary but not in the new control file, the database creates a placeholder entry in the control file under the name MISSING nnnn , where nnnn is the file number in decimal. MISSING nnnn is flagged in the control file as being offline and requiring media recovery.
If the actual data file corresponding to MISSING nnnn is read-only or offline normal, then you can make the data file accessible by renaming MISSING nnnn to the name of the actual data file. If MISSING nnnn corresponds to a data file that was not read-only or offline normal, then you cannot use the rename operation to make the data file accessible, because the data file requires media recovery that is precluded by the results of RESETLOGS . In this case, you must drop the tablespace containing the data file.
Conversely, if a data file listed in the control file is not present in the data dictionary, then the database removes references to it from the new control file. In both cases, the database includes an explanatory message in the alert log to let you know what was found.
10.7 Dropping Control Files
You can drop control files, but the database should have at least two control files at all times.
You want to drop control files from the database, for example, if the location of a control file is no longer appropriate.
- Shut down the database.
- Edit the CONTROL_FILES parameter in the database initialization parameter file to delete the old control file name.
- Restart the database.
This operation does not physically delete the unwanted control file from the disk. Use operating system commands to delete the unnecessary file after you have dropped the control file from the database.
Установка параметра инициализации
Для того чтобы начала действовать аутентификация основанная на использовании файла пароля, параметр инициализации REMOTE_LOGIN_PASSWORDFILE должен быть установлен в значение EXCLUSIVE:
Данное значение является значением по умолчанию для данного параметра и поэтому его не требуется специально устанавливать после инсталляции. Если же параметр имеет другое значение, то стоит помнить, что он не является динамическим, поэтому для того чтобы аутентификация основанная на файле паролей заработала, придётся перезагрузить экземпляр:
Adding Users to a Password File
When you grant SYSDBA or SYSOPER privileges to a user, that user's name and privilege information are added to the password file. If the server does not have an EXCLUSIVE password file (that is, if the initialization parameter REMOTE_LOGIN_PASSWORDFILE is NONE or SHARED , or the password file is missing), Oracle Database issues an error if you attempt to grant these privileges.
A user's name remains in the password file only as long as that user has at least one of these two privileges. If you revoke both of these privileges, Oracle Database removes the user from the password file.
Creating a Password File and Adding New Users to It
Use the following procedure to create a password and add new users to it:
Follow the instructions for creating a password file as explained in "Creating a Password File with ORAPWD".
Set the REMOTE_LOGIN_PASSWORDFILE initialization parameter to EXCLUSIVE . (This is the default.)
REMOTE_LOGIN_PASSWORDFILE is a static initialization parameter and therefore cannot be changed without restarting the database.
Connect with SYSDBA privileges as shown in the following example, and enter the SYS password when prompted:
Start up the instance and create the database if necessary, or mount and open an existing database.
Create users as necessary. Grant SYSDBA or SYSOPER privileges to yourself and other users as appropriate. See "Granting and Revoking SYSDBA and SYSOPER Privileges", later in this section.
Removing a Password File
If you determine that you no longer require a password file to authenticate users, you can delete the password file and then optionally reset the REMOTE_LOGIN_PASSWORDFILE initialization parameter to NONE . After you remove this file, only those users who can be authenticated by the operating system can perform SYSDBA or SYSOPER database administration operations.
Мануал
Вопрос: Как создать файл пароля ОS с помощью команды orapwd на платформах Unix и Windows?
Каковы аргументы (значения и описание) команды orapwd?
1. Войдите в базу данных как администратор.
2. Завершите работу базы данных.
3. На Linux / UNIX: cd $ORACLE_HOME/dbs
На Windows: cd %ORACLE_HOME%\database
4. Введите команду orapwd:
- file – имя файла пароля (обязательно),
- password – пароль для SYS будет запрошен, если он не указан в командной строке,
- entries – максимальное количество отдельных DBA (необязательно),
- force – перезаписать существующий файл (необязательно),
- ignorecase – пароли не чувствительны к регистру (необязательно),
- nosysdba – отключить вход в систему SYSDBA (необязательно только Database Vault, не рекомендуется в 11.2)
Вокруг символа равенства (=) не должно быть пробелов.
Комментарии:
I. В UNIX имя файла ДОЛЖНО быть orapw [SID], [SID] – имя экземпляра. В Windows имя файла ДОЛЖНО быть pwd [SID] .ORA.
II. Пароль ДОЛЖЕН быть паролем для sys.
III. Количество записей – это максимальное количество пользователей, которые смогут запускать и останавливать базу данных. Важно помнить, что если это число слишком мало и необходимо добавить дополнительных пользователей, необходимо повторно создать файл паролей.
Если старый файл паролей существует, вы можете перезаписать его с помощью FORCE = Y или удалить его из текущего каталога, прежде чем заново создавать файл паролей.
V. IGNORECASE – это новый параметр, введенный в 11g, который контролирует чувствительность к регистру паролей, хранящихся в файле паролей.
VI. Параметр NOSYSDBA был добавлен в утилиту orapwd как часть продукта Database Vault.
Давайте посмотрим пример команды orapwd для создания нового файла паролей
Командой выше будет создан файл паролей для экземпляра с именем TEST01 в Unix с паролями с учетом регистра.
Полезно отметить, что имя экземпляра в имени файла пароля чувствительно к регистру и должно совпадать в случае фактического имени экземпляра.
5. Добавьте следующий параметр в pfile экземпляра базы данных TEST01:
6. После того, как все вышеперечисленное было сделано, запустите этот оператор:
Если этот оператор возвращает какие-либо записи, попытайтесь установить соединение sysdba с аутентификацией по паролю.
Если связь работает, все нормально.
Если инструкция не возвращает записей, экземпляр базы данных должен быть перезапущен.
Anything in here will be replaced on browsers that support the canvas element
Уязвимость Log4j является одной из самых смертоносных проблем безопасности в современных системах. Логирование является ключевой функцией в современных приложениях, и библиотека логирования Log4j является лидером в этой области. Эта библиотека используется в большинстве приложений, сервисов и систем. Следовательно, все те приложения, в которых используется Log4j, подвержены этой уязвимости Log4j, обнаруженной в прошлом году. В связи […]
Самая распространенная команда Docker также является универсальной командой. Узнайте о нескольких вариантах использования команды docker ps. Одной из первых команд Docker, которую вы используете, является команда docker ps. Она показывает запущенные контейнеры: docker ps На самом деле, выполнив эту команду, вы получите список запущенных контейнеров и их уникальный ID контейнера, имя образа, команду, которую он […]
Passbolt – это менеджер паролей с открытым исходным кодом, который позволяет безопасно хранить и передавать учетные данные для входа на сайт, пароль роутера, пароль Wi-Fi и т.д. В этом руководстве будет показано, как установить Passbolt Community Edition (CE) на Ubuntu 22.04 с сервером базы данных PostgreSQL, который обычно быстрее, чем сервер базы данных MariaDB/MySQL. Особенности […]
socialscan – это инструмент командной строки для проверки использования электронной почты и имен пользователей социальных сетей на онлайн-платформах. Если задан адрес электронной почты или имя пользователя, socialscan возвращает, доступен ли он, занят или недействителен на онлайн-платформах. Другие подобные инструменты проверяют доступность имени пользователя, запрашивая страницу профиля рассматриваемого имени пользователя и на основе такой информации, как […]
Every Oracle Database has a control file , which is a small binary file that records the physical structure of the database.
The control file includes:
The database name
Names and locations of associated data files and redo log files
The timestamp of the database creation
The current log sequence number
The control file must be available for writing by the Oracle Database server whenever the database is open. Without the control file, the database cannot be mounted and recovery is difficult.
The control file of an Oracle Database is created at the same time as the database. By default, at least one copy of the control file is created during database creation. On some operating systems the default is to create multiple copies. You should create two or more copies of the control file during database creation. You can also create control files later, if you lose control files or want to change particular settings in the control files.
ORAPWD Command Line Argument Descriptions
The following sections describe the ORAPWD command line arguments.
This argument sets the name of the password file being created. You must specify the full path name for the file. The contents of this file are encrypted, and the file cannot be read directly. This argument is mandatory.
The file name required for the password file is operating system specific. Some operating systems require the password file to adhere to a specific format and be located in a specific directory. Other operating systems allow the use of environment variables to specify the name and location of the password file.
Table 1-1 lists the required name and location for the password file on the UNIX, Linux, and Windows platforms. For other platforms, consult your platform-specific documentation.
Table 1-1 Required Password File Name and Location on UNIX, Linux, and Windows
PWD ORACLE_SID .ora
For example, for a database instance with the SID orcldw , the password file must be named orapworcldw on Linux and PWDorcldw.ora on Windows.
In an Oracle Real Application Clusters environment on a platform that requires an environment variable to be set to the path of the password file, the environment variable for each instance must point to the same password file.
It is critically important to the security of your system that you protect your password file and the environment variables that identify the location of the password file. Any user with access to these could potentially compromise the security of the connection.
This argument specifies the number of entries that you require the password file to accept. This number corresponds to the number of distinct users allowed to connect to the database as SYSDBA or SYSOPER . The actual number of allowable entries can be higher than the number of users, because the ORAPWD utility continues to assign password entries until an operating system block is filled. For example, if your operating system block size is 512 bytes, it holds four password entries. The number of password entries allocated is always a multiple of four.
Entries can be reused as users are added to and removed from the password file. If you intend to specify REMOTE_LOGIN_PASSWORDFILE=EXCLUSIVE , and to allow the granting of SYSDBA and SYSOPER privileges to users, this argument is required.
When you exceed the allocated number of password entries, you must create a new password file. To avoid this necessity, allocate a number of entries that is larger than you think you will ever need.
This argument, if set to Y , enables you to overwrite an existing password file. An error is returned if a password file of the same name already exists and this argument is omitted or set to N .
If this argument is set to y , passwords are case-insensitive. That is, case is ignored when comparing the password that the user supplies during login with the password in the password file.
Oracle Database Security Guide for more information about case-sensitivity in passwords.
Исключение пользователей из файла паролей
Со временем может понадобиться исключить того или иного пользователя из файла паролей. Если пользователь удаляется из системы, Oracle автоматически удаляет его и из файла паролей:
Если пользователю нужно только запретить аутентификацию с помощью файла паролей, то для этого достаточно отобрать у него привилегии SYSDBA и SYSOPER Пользователь будет удалён из файла пароля, когда у него не будет ни одной из этих привилегий:
Исключение пользователя из файла паролей не изменяет его размер. Информация о нём сохраняется в файле, но пространство им занимаемое становиться доступно для перезаписи другим включаемым пользователям. Продемонстрируем это. В предыдущем примере пользователи USER7 и USER 8 были «исключены» из файла паролей. Причём пользователь USER8 был удалён. В файле паролей эти пользователи находились в четвёртом последнем 512 байтном блоке. Выведем его содержимое:
Как видно информация о пользователях сохранилась. Таким образом, понятие «исключение из файла паролей» скорее логическое, чем физическое.
Исключение пользователей из файла паролей
Со временем может понадобиться исключить того или иного пользователя из файла паролей. Если пользователь удаляется из системы, Oracle автоматически удаляет его и из файла паролей:
Если пользователю нужно только запретить аутентификацию с помощью файла паролей, то для этого достаточно отобрать у него привилегии SYSDBA и SYSOPER Пользователь будет удалён из файла пароля, когда у него не будет ни одной из этих привилегий:
Исключение пользователя из файла паролей не изменяет его размер. Информация о нём сохраняется в файле, но пространство им занимаемое становиться доступно для перезаписи другим включаемым пользователям. Продемонстрируем это. В предыдущем примере пользователи USER7 и USER 8 были «исключены» из файла паролей. Причём пользователь USER8 был удалён. В файле паролей эти пользователи находились в четвёртом последнем 512 байтном блоке. Выведем его содержимое:
Как видно информация о пользователях сохранилась. Таким образом, понятие «исключение из файла паролей» скорее логическое, чем физическое.
10.3.3 Creating New Control Files
You can create new control files when all of the control files for the database have been permanently damaged and you do not have a control file backup or when you want to change the database name.
10.3.3.1 When to Create New Control Files
You must create new control files in certain situations.
It is necessary for you to create new control files in the following situations:
All control files for the database have been permanently damaged and you do not have a control file backup.
You want to change the database name.
For example, you would change a database name if it conflicted with another database name in a distributed environment.
You can change the database name and DBID (internal database identifier) using the DBNEWID utility. See Oracle Database Utilities for information about using this utility.
10.3.3.2 The CREATE CONTROLFILE Statement
You can create a new control file for a database using the CREATE CONTROLFILE statement.
The following statement creates a new control file for the prod database (a database that formerly used a different database name):
The CREATE CONTROLFILE statement can potentially damage specified data files and redo log files. Omitting a file name can cause loss of the data in that file, or loss of access to the entire database. Use caution when issuing this statement and be sure to follow the instructions in "Creating New Control Files" .
If the database had forced logging enabled before creating the new control file, and you want it to continue to be enabled, then you must specify the FORCE LOGGING clause in the CREATE CONTROLFILE statement. See "Specifying FORCE LOGGING Mode" .
Oracle Database SQL Language Reference describes the complete syntax of the CREATE CONTROLFILE statement
10.3.3.3 Creating New Control Files
You can create new control files for your database.
Complete the following steps to create a new control file.
- Make a list of all data files and redo log files of the database.
If you follow recommendations for control file backups as discussed in "Backing Up Control Files" , you will already have a list of data files and redo log files that reflect the current structure of the database. However, if you have no such list, executing the following statements will produce one.
If you have no such lists and your control file has been damaged so that the database cannot be opened, try to locate all of the data files and redo log files that constitute the database. Any files not specified in step 5 are not recoverable once a new control file has been created. Moreover, if you omit any of the files that comprise the SYSTEM tablespace, you might not be able to recover the database.
If the database is open, shut down the database normally if possible. Use the IMMEDIATE or ABORT clauses only as a last resort.
When creating a new control file, specify the RESETLOGS clause if you have lost any redo log groups in addition to control files. In this case, you will need to recover from the loss of the redo logs (step 8). You must specify the RESETLOGS clause if you have renamed the database. Otherwise, select the NORESETLOGS clause.
If you are creating the control file as part of recovery, recover the database. If the new control file was created using the NORESETLOGS clause, you can recover the database with complete, closed database recovery.
If the new control file was created using the RESETLOGS clause, you must specify USING BACKUP CONTROL FILE . If you have lost online redo logs, archived redo log files, or data files, use the procedures for recovering those files.
Oracle Database Backup and Recovery User's Guide for information about recovering your database and methods of recovering a lost control file
If you did not perform recovery, or you performed complete, closed database recovery in step 8, open the database normally.
If you specified RESETLOGS when creating the control file, use the ALTER DATABASE statement, indicating RESETLOGS .
The database is now open and available for use.
10.2.1 Provide File Names for the Control Files
You specify control file names using the CONTROL_FILES initialization parameter in the database initialization parameter file. The instance recognizes and opens all the listed file during startup, and the instance writes to and maintains all listed control files during database operation.
If you do not specify files for CONTROL_FILES before database creation:
If you are not using Oracle Managed Files, then the database creates a control file and uses a default file name. The default name is operating system specific.
If you are using Oracle Managed Files, then the initialization parameters you set to enable that feature determine the name and location of the control files.
If you are using Oracle Automatic Storage Management (Oracle ASM), you can place incomplete Oracle ASM file names in the DB_CREATE_FILE_DEST and DB_RECOVERY_FILE_DEST initialization parameters. Oracle ASM then automatically creates control files in the appropriate places.
Related Topics
10.3 Creating Control Files
You can create, copy, rename, and relocate control files.
10.3.2 Creating Additional Copies, Renaming, and Relocating Control Files
You can create an additional control file copy for multiplexing by copying an existing control file to a new location and adding the file name to the list of control files.
Similarly, you rename an existing control file by copying the file to its new name or location, and changing the file name in the control file list. In both cases, to guarantee that control files do not change during the procedure, shut down the database before copying the control file.
To add a multiplexed copy of the current control file or to rename a control file:
- Shut down the database.
- Copy an existing control file to a new location, using operating system commands.
- Edit the CONTROL_FILES parameter in the database initialization parameter file to add the new control file name, or to change the existing control file name.
- Restart the database.
Включение пользователей в файл паролей
И так, файл паролей создан. При его создании, в него был включён единственный пользователь SYS, пароль которого вводился при запуске утилиты ORAPWD. Если требуется, чтобы данный вид аутентификации использовался и для других пользователей, то необходимо их так же включить их в файл паролей. К счастью, для этого не надо использовать какие-либо дополнительные утилиты, Oracle сам об этом побеспокоится. Единственное что надо сделать, так это предоставить таким пользователям привилегии SYSDBA или SYSOPER и Oracle сам добавит их в файл паролей. В качестве примера попробуем создать пользователя USER1 и предоставим ему привилегию SYSDBA:
При выдаче пользователям привилегий SYSDBA или SYSOPER следует учитывать, что данные привилегии являются специальным видом привилегий. Они не могут предоставляться пользователю с правом их передачи другим пользователям, а так же не могут быть включены в состав ролей. Рассмотрим это на примере. Выдадим привилегию SYSDBA пользователю USER1 с опцией WITH ADMIN OPTION:
Как видим, ошибок при выдаче привилегий с опцией WITH ADMIN OPTION не возникло. Но не всё так просто как кажется. Теперь создадим пользователя USER2, подключимся пользователем USER1 и попробуем выдать привилегию SYSDBA пользователю USER2:
Возникла ошибка. Просто так предоставить другим привилегии SYSDBA и SYSOPER у простого пользователя не получится. Опция WITH ADMIN OPTION здесь не действует. Необходимо предварительно аутентифицироваться с помощью файла паролей и только тогда можно предоставить привилегии другому пользователю:
В отличие от прав передачи, при предоставлении привилегий SYSDBA или SYSOPER роли ситуация однозначная. Сразу возникает ошибка. Так как данные привилегии могут работать и при выгруженном экземпляре, а роли действуют только при запущенной базе данных, предоставление их роли не имеет никакого смысла:
Читайте также: