Policy tool java как настроить

Настройка безопасности Java в Internet Explorer

Настольное приложение Internet Explorer 11 будет снято с службы поддержки 15 июня 2022 г. (список того, что имеется в области, см. в faq). Те же приложения и сайты IE11, которые вы используете сегодня, могут открываться в Microsoft Edge режиме Internet Explorer. Подробнее см. здесь.

В этой пошаговой статье описывается настройка java-безопасности в Internet Explorer. Вы можете настроить Internet Explorer с помощью параметров безопасности по умолчанию или настраиваемых параметров безопасности. Настраиваемые параметры безопасности явно определяют разрешения Java для подписанных и неподписаных яблок. Для настройки настраиваемых разрешений Java необходимо установить виртуальную машину Майкрософт.

Оригинальная версия продукта: Internet Explorer
Исходный номер КБ: 315674

Просмотр и изменение настраиваемые параметры Java для каждой зоны безопасности

Настройка java-безопасности в Internet Explorer:

Запустите Internet Explorer и нажмите кнопку Параметры Интернета в меню Tools.

В диалоговом окне Параметры Интернета щелкните вкладку Безопасность.

На странице Безопасность есть четыре зоны безопасности:

  • Интернет
  • Местная интрасеть
  • Надежные сайты
  • Ограниченные сайты

Выберите зону, в которой необходимо изменить параметры безопасности Java.

На уровне безопасности для этого кадра зоны щелкните Настраиваемый уровень. В Internet Explorer нажмите настраиваемый уровень и нажмите кнопку Параметры.

Просмотр раздела Microsoft VM (раздел Java в Internet Explorer)

В списке Разрешений Java в microsoft VM нажмите кнопку Custom.

Нажмите кнопку Java Custom Параметры.

Щелкните вкладку Разрешения просмотра, чтобы просмотреть текущие разрешения Java. Разрешения Java сгруппировали в три основные категории:

  • Разрешения, выдавлимые неподписавому контенту
    Неподписаные java-яблоки, запрашивающие эти разрешения, могут работать без запроса пользователя.
  • Разрешения, которые разрешены для подписывного контента
    Подписанные java-яблоки, запрашивающие эти разрешения, могут работать без запроса пользователя.
  • Разрешения, которые подписывал контент, отказано
    Подписанные java-яблоки не имеют этих разрешений.

Щелкните вкладку Edit Permissions. Выберите параметр, необходимый для более точного контроля над разрешениями Java для зоны. Если вы не хотите сохранить параметры, которые вы сделали, вы можете нажать кнопку Reset, чтобы сбросить разрешения на:

  • Сохраненные разрешения
  • Высокая безопасность
  • Medium Security
  • Низкая безопасность

Нажмите кнопку ОК и нажмите кнопку ОК снова.

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

Источник

Русские Блоги

Управляйте разрешениями апплета с помощью файлов политики

В этой статье описывается, как получить доступ к ограниченным ресурсам на платформе Java, таким как чтение и запись файла. Мы настраиваем файл политики, чтобы позволить неподписанному апплету получить доступ к ограниченным ресурсам системы. Эта статья состоит из следующего:

  • Ограничения на апплеты
  • Как настроить файл политики
  • Как сделать Политику эффективной

Ограничения на апплеты

Плагин Java использует Security Manager для предотвращения проникновения вирусов в вашу систему через апплеты. Если неподписанный апплет хочет получить доступ к определенному системному ресурсу, Security Manager проверяет, были ли разрешены соответствующие разрешения, и неавторизованные апплеты не могут получить доступ к системным ресурсам. Авторизация требует записи в файле политики.

Oracle официально предоставляет пример апплета.

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

Введите следующую команду в командном окне для запуска апплета:

Ожидаемое поведение — вы увидите исключение безопасности.

Как настроить файл политики

Файл политики представляет собой текстовый файл ASCII. Вы можете редактировать его с помощью текстового редактора или инструмента политики графического интерфейса. Преимущество инструмента «Политика» заключается в том, что им легко пользоваться, вам не нужно знать подробный синтаксис файла политики, и это снижает вероятность ошибок. В этом разделе инструмент «Политика» используется для создания файла политики с именем examplepolicy и добавляет в него запись для авторизации каталога, в котором хранится файл WriteFile.class, для создания / записи файла с именем writetest.

Использование инструмента политики

Перед использованием убедитесь, что на вашем компьютере установлен и настроен JDK. В инструменте командной строки выполните policytool. Если команда не существует, загляните в каталог $ JAVA_HOME / bin. Пользователи Windows могут найти исполняемый файл exe. Команда откроет графический интерфейс policytool, как показано ниже:

Как видно из рисунка, инструмент не отображает никакой информации о политике. Это связано с тем, что после запуска инструмент попытается прочитать файл политики пользователя и отобразить соответствующую информацию на интерфейсе. Файл политики пользователя по умолчанию называется .java.policy. Он будет сохранен в домашнем каталоге пользователя. Если файл политики не найден, он будет пустым, как показано выше. Затем мы создадим новый файл политики.

Авторизоваться

Вступление является носителем власти. Нажмите кнопку «Добавить запись политики», чтобы создать новую запись. Далее вы увидите диалоговое окно ввода политики, как показано ниже:

Одна запись может указывать одно или несколько разрешений. Код поступает из определенного источника кода (URL), а код подписывается определенной сущностью.

В текстовых полях CodeBase и SignedBy указано, какие коды требуют авторизации.

  • CodeBase обозначает путь к исходному коду. Код, который вы авторизуете, приходит по пути, соответствующему этому значению. Обратите внимание, что нулевое значение представляет любой код.
  • SignedBy представляет псевдоним сертификата в хранилище ключей. Открытый ключ в сертификате используется для проверки цифровой подписи кода. Код подписывается закрытым ключом, соответствующим открытому ключу. Поле SignedBy является необязательным. Если не заполнено, это означает «любой подписывающий». Система не заботится о том, подписан код или нет, и кто его подписал.

Мы продолжаем использовать пример WriteFile. Если вы хотите, чтобы этот апплет имел разрешение на создание и запись файлов, вы можете ввести его в поле CodeBase:

SignedBy не заполнен, потому что код не подписан. Давайте авторизуем это. Нажмите кнопку Добавить разрешение, вы увидите следующее диалоговое окно:

Пожалуйста, следуйте инструкциям ниже для авторизации:

1. Выберите FilePermission из раскрывающегося списка Permission.

2. Введите writetest в текстовое поле справа от выпадающего списка Target Name. Это имя файла, который вы хотите авторизовать.

3. Выберите запись в раскрывающемся списке Действия.

После завершения происходит следующее:

После нажатия кнопки ОК, интерфейс выглядит следующим образом:

Нажмите кнопку «Готово», и настройка завершена.

Сохранить файл политики

Щелкните меню «Файл», выберите «Сохранить как», введите имя файла examplepolicy, выберите путь сохранения и нажмите кнопку «Сохранить» для сохранения. Перейдите в указанный вами каталог, откройте файл политики, и вы увидите следующее утверждение:

Обратите внимание, что суффикс файла предпочтительно является .java.policy.

Как сделать Политику эффективной

Теперь, когда мы создали файл политики, мы можем снова протестировать его с помощью апплета WriteFile.

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

Примечание: jre.home = jdk.home / jre

Вы можете найти следующий код в файле java.security:

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

N — это число, и все файлы политики настроены в файл java.security в соответствии со следующими правилами.

URL обозначает путь к файлу вашей политики и должен соответствовать правилам URL.

Кроме того, мы также можем обнаружить, что уже есть некоторые файлы политик по умолчанию, загруженные системой. Первый — это java.policy, который находится в том же каталоге, что и java.security. Кроме того, в каталоге пользователя есть файлы политики.

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

Первый путь

Используйте параметр командной строки -J-Djava.security.policy следующим образом:

Обратите внимание, что между политикой и URL-адресом есть пробел.

Второй способ

Файл java.security и способ указания файла политики представлены в начале этого раздела. Этот метод более универсален, чем первый.

Найдите policy.url.2 в файле java.security и добавьте строку информации о политике ниже:

После сохранения конфигурации выполните следующую команду:

Источник

помогите разобраться с java.policy

аплет подписан
если не подключен к базе денных то запускается без проблем
если подключаю базу данных то выдается такая ошибка

see com.borland.dx.dataset.DataSetException error code: BASE+83
com.borland.dx.dataset.DataSetException: The driver: sun.jdbc.odbc.JdbcOdbcDriver could not be loaded. This could be a problem with the driver itself, or that the driver is not found on the classpath.
at com.borland.dx.dataset.DataSetException a (Unknown Source)

подскажите как прописатть в файле java.policy
или нужно сделать что-то другое?

Читайте также:  Как отремонтировать цифровой эфирный приемник

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

Помогите разобраться со статическими переменными в Java
Hi, java programmer! Я пытаюсь создать и показать окно. Текст программы такой: import.

Помогите новичку разобраться с java.
Нужно создать интернет библиотеку. Проект должен иметь 2 класса: библиотека и книга. Книга должна.

Java policy applet
Возникла проблема с апплетом, сделал программу с потоками и при запуске ловлю ошибку : .

Помогите разобраться с PHP, ASP, Java.
Проблема у меня в том, что я не знаю с какого конца начинать. Я делаю страницы на HTML, CSS и.

1. Использовать jdbc-odbc мост в апплете не удобно. Тебе нужно будет настраивать odbc на каждой машине.
2. Файл java.policy находится у клиента, ты тоже его изменять будешь?

Если ты точно уверен, что хочешь изменять java.policy, попробуй добавить в него следующее:
grant codeBase ‘http://путь/твой_апплет.jar’ <
permission java.security.AllPermission;
>;

Здравствуйте!
видимо дело не в полиси.
(а как здесь в сообщение картинку вставить?)

в общем ошибка осталась плюс появились новые
в основном ругается на com.borland.dx.dataset.DataSetException
и com.borland.dx.sql.dataset

odbc подключаю на каждой машине
и файл полиси есть на каждой машине
это не правильно?
как быть?
основные требования к программе было запуск из локального интернета.
что-то все запуталось! Помогите разобраться!

Источник

Policy File Creation and Management

Creates and modifies the external policy configuration files that define your installation’s Java security policy.

Table of Contents

Introduction

The policy for a Java runtime (specifying which permissions are available for code from various sources, when executing as various principals) is represented by a Policy object. The default Policy implementation obtains its information from static ASCII policy configuration files.

A policy file can be composed via a simple text editor, or via the graphical Policy Tool utility described in this document. Using the Policy Tool saves typing and eliminates the need for you to know the required policy file syntax thus reducing errors.

The Policy Tool Usage section describes how to use the Policy Tool to create and modify policy files.

The Examples section provides detailed examples of the use of Policy Tool.

The See Also section provides links to related documentation.

Policy Tool Usage

Starting Policy Tool

To start Policy Tool, simply type the following at the command line.

This brings up the «Policy Tool» window.

Whenever Policy Tool is started, it tries to fill in this window with policy information from what is sometimes referred to as the «user policy file». The user policy file is by default a file named .java.policy in your home directory. If Policy Tool cannot find the user policy file, it reports the situation and displays a blank «Policy Tool» window (that is, a window with headings and buttons but no data in it):

You can then proceed to either open whatever policy file you want to work on or create a new policy file, by adding policy entries, optionally specifying a keystore, and saving the file).

The first time you run the Policy Tool, there will not be a user policy file (unless you created one manually).

Creating a new Policy File

To create a new policy file, start by simply selecting the New command from the File menu. This will close the currently open policy file (if any, after first prompting you to save it if needed) and bring up a new policy tool window, that is, a window with headings and buttons but no data in it.

Please Note: this is not necessary the first time you run the Policy Tool. Since the tool tries to open the user policy file and one doesn’t exist yet (unless it was created manually), the tool will bring up a window without any data in it.

Once you have a new policy tool window, you can then create the policy entries, and specify the keystore (if any of the policy entries specify a keystore alias). At any point, you can save the policy file.

Opening a Different Policy File

To work on a different policy file than the one currently being worked on (if any), use the Open command in the File menu.

This will close the currently open policy file (if any, after first prompting you to save it if needed) and will present you with an Open dialog, which you can use to navigate the directory structure until you get to the directory containing the policy file you want to work on. Select that file, then select the OK button.

The «Policy Tool» window will then be filled in with information from the policy file, including the policy file name, the keystore URL (if any), and the CodeBase, SignedBy and Principal parts of each policy entry in the policy file.

Specifying the Keystore

To specify the keystore containing the key information for the aliases specified in the SignedBy parts of policy entries, select the Edit command in the Keystore menu.

This brings up a dialog box in which you specify the new keystore URL and optionally the keystore type.

As an example, to specify the keystore named «mykeystore» in the /tests/ directory, type the following file: URL into the text box labeled «New KeyStore URL».

To also specify that the keystore type is «JKS» (the proprietary keystore type supported by Oracle), type the following into the text box labeled «New KeyStore Type».

When you are done specifying the keystore URL and type (if any), select OK (or you can select Cancel to cancel the operation). If you didn’t cancel, the text box labeled «Keystore:» is now filled in with the keystore URL and type.

Adding a New Policy Entry

To add a new policy entry, select the Add Policy Entry button in the main «Policy Tool» window.

This brings up a «Policy Entry» dialog box:

Using this dialog box, you specify

  • an optional CodeBase entry indicating the URL location where the code originates from. For example, to indicate code from the local /TESTS/ directory, type the following file URL into the CodeBase text box:
  • an optional SignedBy entry indicating the alias name from the keystore used to reference the signer whose private key was used to sign the code. For example, to indicate the alias named «Signer», simply type the following into the SignedBy text box:
  • an optional Principals entry indicating the list of principals that the code has to be executed as in order for the permission(s) to be granted. See Adding a New Principal.
  • one or more permission entries indicating which permissions are granted to the code from the source indicated by the CodeBase and SignedBy values (or to any code if no such values are specified) when running as the specified principals in the Principals list. See Adding a New Permission.

The SignedBy value is a string alias that is mapped (using the keystore) to a set of public keys that are associated with the signers. These keys are used to verify that classes from the specified code source are really signed by these signers.

The SignedBy value can be a comma-separated string containing names of multiple signers, an example of which is «Adam,Eve,Charles», which means «signed by Adam and Eve and Charles» (i.e., the relationship is AND, not OR).

The SignedBy value is optional in that, if it is omitted, it signifies «any signer,» or in other words, it doesn’t matter whether the code is signed or not. Similarly, if there is no CodeBase entry, then it signifies «any code»; it doesn’t matter where the code originates from.

Thus, if there is no CodeBase entry, then all code signed by the specified alias(es) will be granted the specified permissions. If there is no SignedBy entry, then all code from the specified CodeBase will be granted the specified permissions, regardless of whether the code is signed or not, and by whom. If there is no CodeBase entry, and also no SignedBy entry, then all code will be granted the specified permissions.

Note: The exact meaning of a CodeBase value depends on the characters at the end. A CodeBase with a trailing «/» matches all class files (not JAR files) in the specified directory. A CodeBase with a trailing «/*» matches all files (both class and JAR files) contained in that directory. A CodeBase with a trailing «/-» matches all files (both class and JAR files) in the directory and recursively all files in subdirectories contained in that directory.

The Principals entry specifies a list of «principal values». Each principal value specifies a principal_type/principal_name pair which must be present within the executing thread’s principal set. The Principals entry is optional in that, if it is omitted, it signifies «any principals».

If there is no principal_type specified and the principal_name is a quoted string, the string is treated as a keystore alias when the policy file is processed at runtime. The keystore is consulted and queried (via the alias) for an X509 Certificate. If one is found, the principal type is automatically assumed to be javax.security.auth.x500.X500Principal, and the actual principal name is assumed to be the subject distinguished name from the certificate. If an X509 Certificate mapping is not found, the entire policy entry granting permissions to the specified principal is ignored.

Читайте также:  При включении поворотника лампочки не работают

Adding a New Principal

To add a new principal, select the Add Principal button in the «Policy Entry» dialog box. This brings up the «Principals» dialog box:

To add the principal:

    Type or select a principal type.

The drop-down list labeled «Principal Type:» contains a list of built-in principal types. If you want such a type, select it from the list, and the complete principal type name appears in the text box to the right of the drop-down list.

If you instead want to specify a principal type defined by you or others, type the principal type into the text box.

Type a principal name.

Type the principal name directly into the text box to the right of the «Principal Name:» text box. For example, to specify the principal named Signer , type

When you are done specifying the principal information, select the OK button (or Cancel to cancel). The new principal appears in a line in the «Principals» entry.

You can then add additional principals by following the same sequence of steps. Or you can edit or remove an existing principal.

Editing a Principal

To edit an existing principal, select the line for that principal in the «Principals:» entry, then select the Edit Principal button. Alternatively, you can simply double-click the line for that principal.

This brings up the same type of «Principals» dialog box as appears when you are adding a new principal, except in this case the dialog box is filled in with the existing principal information. To change the information, either make new selections from the drop-down lists or replace the information in the text boxes.

When you are done, select the OK button (or Cancel to cancel changes). The Principals:» entry now shows the principal with your modifications.

Removing a Principal

To remove an existing principal, select the line for that principal in the «Principals:» entry, then select the Remove Principal button.

Adding a New Permission

To add a new permission, select the Add Permission button in the «Policy Entry» dialog box. This brings up the «Permissions» dialog box:

To add the permission:

    Type or select a permission type.

The drop-down list labeled «Permission:» contains a list of built-in permission types. If you want such a type, select it from the list, and the complete permission type name appears in the text box to the right of the drop-down list.

If you instead want to specify a permission type defined by you or others, type the permission type into the text box.

Type or select a permission target name.

If you selected a built-in permission from the «Permission:» drop-down list, and permissions of that type have specific target name values, then the drop-down list labeled «Target Name:» contains a list of those values, from which you can choose.

In some cases, where the target name possibilities are infinite but there are some built-in target name specifications that have special meaning, such target names will appear in the drop-down list. For example, the special target name of » » will appear in the list for File Permissions.

To specify a target name not available in the drop-down list, type the target name directly into the text box to the right of the «Target Name:» drop-down list. For example, to specify the file named data in the /ptTest/ directory, type

Type or select one or more actions, if actions are relevant.

Some permissions just have a target name, but no actions. For such permissions, leave the text box to the right of the «Actions:» drop-down list blank. (It will automatically be darkened and unavailable for this type of built-in permission.)

For permissions requiring action specifications, type the comma-separated list of actions into the text box, or select them from the drop-down list. For example, to specify both read and write access to a file specified for a File Permission, first select read (or write , order doesn’t matter) from the list. The word «read» appears in the text box. Then select write , and the word «write» will be appended, preceded by a comma and a space.

  • Type a SignedBy alias into the text box to the right of the «Signed By» label, if required. The SignedBy value for a permission entry is optional. If present, it indicates a signed permission. That is, the permission class itself must be signed by the given alias(es) in order for the permission to be granted.
  • When you are done specifying the permission information, select the OK button (or Cancel to cancel). The new permission appears in a line in the «Policy Entry» dialog.

    You can then add additional permissions by following the same sequence of steps. Or you can edit an existing permission or remove a permission.

    Editing a Permission

    To edit an existing permission, select the line for that permission in the «Policy Entry» dialog box, then select the Edit Permission button. Alternatively, you can simply double-click the line for that permission.

    This brings up the same type of «Permissions» dialog box as appears when you are adding a new permission, except in this case the dialog box is filled in with the existing permission information. To change the information, either make new selections from the drop-down lists or replace the information in the text boxes.

    When you are done, select the OK button (or Cancel to cancel changes). The «Policy Entry» dialog now shows the permission with any modifications you made.

    Removing a Permission

    To remove an existing permission, select the line for that permission in the «Policy Entry» dialog box, then select the Remove Permission button.

    Completing the Addition of a Policy Entry

    Once you are done adding a policy entry, select the Done button in the «Policy Entry» dialog, or Cancel to cancel.

    If you selected Done, the «Policy Tool» window now contains a line representing the policy entry. The line contains the CodeBase, SignedBy and Principals information (if any). If none was specified in the «Policy Entry» dialog, just

    Note: a warning is displayed upon closing the policy entry if it contains any SignedBy aliases that don’t yet exist in your keystore. Select OK and make a note to create such an alias, or edit the policy entry to fix the alias if was wrong.

    Editing a Policy Entry

    To edit an existing policy entry, select the line for that entry in the main «Policy Tool» window, then select the Edit Policy Entry button. Alternatively, you can simply double-click the line for that entry.

    This brings up the same type of «Policy Entry» dialog box as appears when you are adding a new policy entry, except in this case the dialog box is filled in with the existing policy entry information. To change the information, simply retype it (for the CodeBase and SignedBy values) or use the buttons (for the Principals and Permissions values).

    When you are done, select the Done button (or Cancel to cancel).

    Removing a Policy Entry

    To delete a policy entry from the policy file, select the line for that entry in the main «Policy Tool» window, then select the Remove Policy Entry button.

    The complete policy entry is displayed, and you can then either select OK to remove the entry, or Cancel to keep it.

    Saving the Policy File

    To save changes to an existing policy file, simply select the Save command in the File menu.

    To save a new policy file you’ve been creating, or to copy an existing policy file to a new policy file with a different name, select the Save As command from the File menu. This brings up the Save As dialog box.

    Navigate the directory structure to get to the directory in which you want to save the policy file. Type the desired file name, then select the OK button. The policy file is now saved, and its name and path are shown in the text box labeled «Policy File:»

    Exiting the Policy Tool

    To exit Policy Tool, select the Exit command from the File menu.

    Viewing the Warning Log

    If Policy Tool ever reports that warnings have been stored in the Warning Log, you can view the log by selecting the View Warning Log command in the File menu.

    For example, if you have a policy file with a Keystore URL specifying a keystore that doesn’t yet exist, you will get such a warning at various times, e.g., when you open the file. You can continue to work on the policy file even if warnings exist.

    Читайте также:  Не работает dev cpp

    Examples

    The following examples show how to

    Starting Creation of the User Policy File

    Initially, there is no user policy file (unless you created one manually). So to create the user policy file, first simply start Policy Tool by typing the following at the command line.

    This brings up the «Policy Tool» window.

    Whenever Policy Tool is started, it tries to fill in this window with policy information from what is sometimes referred to as the «user policy file». The user policy file is by default a file named .java.policy in your home directory. If Policy Tool cannot find the user policy file, it reports the situation and displays a blank «Policy Tool» window (that is, a window with headings and buttons but no data in it):

    You can now create the user policy file by adding entries and saving the file.

    Adding a Policy Entry

    Suppose you want to grant all classes from the /tests/ directory permission to read the file named mydata in the /temp/data/ directory. To do so, first select the Add Policy Entry button in the main «Policy Tool» window.

    This brings up a «Policy Entry» dialog box:

    Using this dialog box, type the file URL

    into the CodeBase text box.

    Leave the SignedBy text box blank, since you aren’t requiring the code to be signed.

    Leave the Principals list blank, since you aren’t requiring the code to be authenticated.

    To add the permission, select the Add Permission button. This brings up the «Permissions» dialog box:

    To add the permission:

    1. Select «File Permission» from the «Permission:» drop-down list. The complete permission type name (java.io.FilePermission) now appears in the text box to the right of the drop-down list.
    2. Type the following in the text box to the right of the list labeled «Target Name:»:
    3. Specify read access by either selecting «read» from the «Actions:» drop-down list or directly typing «read» into the text box to the right of the «Actions:» drop-down list.

    Now the «Permission» dialog box looks like the following:

    When you are done specifying the permission information, select the OK button. The new permission appears in a line in the «Policy Entry» dialog.

    You are now done specifying this policy entry, so select the Done button. The «Policy Tool» window now contains a line representing the policy entry. The line just contains the CodeBase value:

    Specifying a Keystore

    Suppose you also want to grant any code from the URL «http://example.com/» and signed by the alias «Signer» read access to all files in the /tmp/ directory. Suppose you also want to give such code permission to initiate outgoing socket connections to any hosts. You need to do two things:

    1. Specify the keystore containing the alias, and
    2. Create the policy entry granting the permissions.

    To specify the keystore containing the key information for the aliases specified in any SignedBy parts of policy entries, select the Edit command in the Keystore menu of the main «Policy Tool» window.

    This brings up a dialog box in which you specify the new keystore URL and optionally the keystore type.

    As an example, to specify the keystore named «mykeystore» in the /tests/ directory, type the following file: URL into the text box labeled «New KeyStore URL»:

    If the keystore type is the default type, as specified by the «keystore.type» property value in the security properties file, you don’t need to type a «New KeyStore Type» value. The default value of that property is «JKS» (the proprietary keystore type supported by Oracle).

    To specify the keystore type, type its value into the text box labeled «New KeyStore Type.» For example, to indicate that the keystore type is «JKS» type

    When you are done specifying the keystore URL and type, select OK. The text box labeled «Keystore:» is now filled in with the URL and type.

    Next, you need to specify the policy entry:

    Adding a Policy Entry with a SignedBy Alias

    Select the Add Policy Entry button in the main «Policy Tool» window. This brings up the «Policy Entry» dialog box. Type the following into the CodeBase text box:

    The «*» indicates that both class and JAR files in the specified directory are to be considered to match this CodeBase.

    Now, type the following alias into the SignedBy text box:

    Leave the Principals list blank, since you aren’t requiring the code to be authenticated.

    To add the first permission, select the Add Permission button. This brings up the «Permissions» dialog box. Do the following

    1. Select «File Permission» from the «Permission:» drop-down list. The complete permission type name (java.io.FilePermission) now appears in the text box to the right of the drop-down list.
    2. Type the following in the text box to the right of the list labeled «Target Name:» to specify all files in the /tmp/ directory:
    3. Specify read access by selecting «read» from the «Actions:» drop-down list.

    Now the «Permissions» dialog box looks like the following:

    Select the OK button. The new permission appears in a line in the «Policy Entry» dialog.

    Now you need to add the other permission. Select the Add Permission button. In the «Permissions» dialog box, do the following

    1. Select «Socket Permission» from the «Permission:» drop-down list. The complete permission type name (java.net.SocketPermission) now appears in the text box to the right of the drop-down list.
    2. Type the following in the text box to the right of the list labeled «Target Name:» to specify all hosts:
    3. Specify permission to make connections by selecting «connect» from the «Actions:» drop-down list.

    Now the «Permissions» dialog box looks like the following:

    Select the OK button. The new permission appears in a line in the «Policy Entry» dialog.

    You are now done specifying this policy entry, so select the Done button in the «Policy Entry» dialog. The «Policy Tool» window now contains a line representing the policy entry, showing the CodeBase, SignedBy and Principals values.

    Adding a Policy Entry with a Principal

    Suppose you want to grant the principal whose X500 name is

    permission to write to the /tmp/ directory.

    Select the Add Policy Entry button in the main «Policy Tool» window. This brings up the «Policy Entry» dialog box.

    Leave the CodeBase text box blank since you aren’t limiting where the code comes from.

    Leave the SignedBy text box blank since you aren’t requiring the code to be signed.

    Select the Add Principal button. In the «Principals» dialog box, do the following

    1. Select «X500Principal» from the «Principal Type:» drop-down list. The complete principal type name (com.sun.security.auth.X500Principal) now appears in the text box to the right of the drop-down list.
    2. Type the following in the text box to the right of the list labeled «Principal Name:» to specify an X500 name for the X500Principal:

    Now the «Principals» dialog box looks like the following:

    Select the OK button. The new principal appears in a line in the «Principals» list.

    To add the permission, select the Add Permission button. This brings up the «Permissions» dialog box. Do the following

    1. Select «File Permission» from the «Permission:» drop-down list. The complete permission type name (java.io.FilePermission) now appears in the text box to the right of the drop-down list.
    2. Type the following in the text box to the right of the list labeled «Target Name:» to specify all files in the /tmp/ directory:
    3. Specify write access by first selecting «write» from the «Actions:» drop-down list.

    Select the OK button. The new permission appears in a line in the «Policy Entry» dialog.

    You are now done specifying this policy entry, so select the Done button in the «Policy Entry» dialog. The «Policy Tool» window now contains a line representing the policy entry, showing the CodeBase, SignedBy and Principals values.

    Saving the User Policy File

    Let’s assume you want to save the policy file you’ve been creating with the default name (.java.policy) in the default location (your home directory).

    To save the user policy file, select the Save As command from the File menu. This brings up the Save As dialog box.

    Navigate the directory structure to get to your home directory. Type

    (note the initial period) as the file name, then select the OK button. The policy file is now saved, and its name and path are shown in the text box labeled «Policy File:».

    Exiting Policy Tool

    When you want to exit Policy Tool, do so by selecting the Exit command from the File menu.

    Источник

    Оцените статью