How to use custom PolicySpi











up vote
3
down vote

favorite
1












I'm trying to implement a custom java.security.Permission type, which should be checked at runtime (so no policy file, but in code). This checking is done by a java.security.Policy. I understood I should implement my own java.security.PolicySpi for this.



I cannot find any explanation on how to initialise and use a PolicySpi, or is there a better way to do this?










share|improve this question




























    up vote
    3
    down vote

    favorite
    1












    I'm trying to implement a custom java.security.Permission type, which should be checked at runtime (so no policy file, but in code). This checking is done by a java.security.Policy. I understood I should implement my own java.security.PolicySpi for this.



    I cannot find any explanation on how to initialise and use a PolicySpi, or is there a better way to do this?










    share|improve this question


























      up vote
      3
      down vote

      favorite
      1









      up vote
      3
      down vote

      favorite
      1






      1





      I'm trying to implement a custom java.security.Permission type, which should be checked at runtime (so no policy file, but in code). This checking is done by a java.security.Policy. I understood I should implement my own java.security.PolicySpi for this.



      I cannot find any explanation on how to initialise and use a PolicySpi, or is there a better way to do this?










      share|improve this question















      I'm trying to implement a custom java.security.Permission type, which should be checked at runtime (so no policy file, but in code). This checking is done by a java.security.Policy. I understood I should implement my own java.security.PolicySpi for this.



      I cannot find any explanation on how to initialise and use a PolicySpi, or is there a better way to do this?







      java security permissions policy






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 20 '14 at 12:51

























      asked Feb 25 '14 at 14:10









      OblongZebra

      393315




      393315
























          3 Answers
          3






          active

          oldest

          votes

















          up vote
          3
          down vote



          accepted










          Checking permissions



          In your question you stated that you then want to check the permission with java.security.Policy, but without using a spi.policy file.



          From the PolicySpi API, you can see that a PolicySpi object features 4 methods:




          1. engineGetPermissions(CodeSource codesource)

          2. engineGetPermissions(ProtectionDomain domain)

          3. engineImplies(ProtectionDomain domain, Permission permission)

          4. engineRefresh()


          However, you might not need PolicySpi as there are easier solutions to check permissions.



          See:




          • Security Manager vs Access Controller

          • AccessController usage


          Since you haven't specified what kind of permission you will grant, I will assume it is a permission concerning a java.security.CodeSource object.



          To check all current permissions for a file:



          public static void main(String args) {

          CodeSource source;

          try {
          source = new CodeSource(new URL("file:/c:/*"), (java.security.cert.Certificate) null);

          Policy policy = Policy.getPolicy();
          System.out.println(policy.getPermissions(source));

          } catch (IOException e) {
          e.printStackTrace();
          }
          }


          A nice example for the SecurityManager checkPermission() is this tutorial.



          For checking specific FilePermissions, you can use:



          FilePermission perm = new FilePermission("path/file", "read");
          AccessController.checkPermission(perm);


          Granting permissions



          Granting permissions at runtime can be done with java.lang.RuntimePermission.



          For other examples of how to grant permissions to a file, I suggest you read the following:




          • Access Control Mechanisms and Algorithms

          • Configuring spi.policy files

          • Security Managers and Permissions




          That should bring you a long way! Good luck!






          share|improve this answer























          • The idea is to create a runtime checking of a custom Permission (MyPermission). Since the checking may vary during runtime, I need a implementation without policy file. I already used AccessController.checkPermission(). The only thing is I need this method to go to a interface which provides runtime information
            – OblongZebra
            Mar 31 '14 at 14:50










          • According to THIS, There is only one instance of AccessController in each Java runtime.. This means that the default context is already the context of the current runtime.
            – Jean-Paul
            Mar 31 '14 at 15:07






          • 1




            Thats true, I'am using AccessController.checkPermission which uses the Policy in its turn. The Policy should do specific checking, for instance if the time is between 8:00 and 10:00 the permission is allowed otherwise it is not allowed. But that is possible especially with the 'configuring spi.policy files' I now know how to start using it. Thx.
            – OblongZebra
            Mar 31 '14 at 15:16










          • @OblongZebra: Too bad of your reputation bounty :( You didn't use it!
            – Jean-Paul
            Mar 31 '14 at 15:20










          • Sorry I reacted to late. I requested stackoverflow to allow you the bounty anyway, hope they grant it.
            – OblongZebra
            Apr 4 '14 at 7:33


















          up vote
          0
          down vote













          The previous answer lists alternatives to using PolicySpi (and more generally custom Policy implementations ). This answer will instead give a simplistic example on how a PolicySpi implementation can actually be used as a replacement of the system-default Policy.





          1. Author a JCA Provider.



            package com.example;

            import java.security.AccessController;
            import java.security.PrivilegedAction;
            import java.security.Provider;

            public final class TestProvider extends Provider {

            private static final long serialVersionUID = 5544432861418770903L;

            public TestProvider() {
            super("TestProvider", 1, "TestProvider 1.0");
            AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
            putService(new TestPolicySpiService(this));
            return null;
            });
            }

            }



          2. Author the sole Service descriptor encapsulated by the provider.



            package com.example;

            import java.security.Policy.Parameters;
            import java.security.PolicySpi;
            import java.security.Provider;
            import java.security.Provider.Service;
            import java.util.Collections;

            final class TestPolicySpiService extends Service {

            TestPolicySpiService(Provider p) {
            super(p, "Policy", "TestPolicy", PolicySpi.class.getName(), Collections.emptyList(), Collections.emptyMap());
            }

            @Override
            public PolicySpi newInstance(Object constructorParameter) {
            Parameters policyParams = null;
            if (constructorParameter instanceof Parameters) {
            policyParams = (Parameters) constructorParameter;
            }
            return new TestPolicySpi(policyParams);
            }

            @Override
            public boolean supportsParameter(Object parameter) {
            return parameter instanceof Parameters;
            }

            }



          3. Author the actual service (the PolicySpi implementation in this case) that the service descriptor produces.



            package com.example;

            import java.security.Permission;
            import java.security.Policy.Parameters;
            import java.security.PolicySpi;
            import java.security.ProtectionDomain;

            final class TestPolicySpi extends PolicySpi {

            TestPolicySpi(Parameters policyParams) {}

            @Override
            protected boolean engineImplies(ProtectionDomain domain, Permission permission) {
            // deny unconditionally
            return false;
            }

            }


          4. Register the provider either statically, by modifying the security.provider.n properties in JAVA_HOME/lib/security/java.security, or programmatically, via java.security.Security.addProvider(Provider) / java.security.Security.insertProviderAt(Provider, int).



          5. Replace the default Policy.



            package com.example;

            import java.security.NoSuchAlgorithmException;
            import java.security.Policy;

            public class Main {

            public static void main(String... args) throws NoSuchAlgorithmException {
            // the following assumes that the provider has been statically registered
            Policy.setPolicy(Policy.getInstance("TestPolicy", null));
            System.setSecurityManager(new SecurityManager());

            // test
            System.out.println(System.getProperty("user.home")); // should raise AccessControlException
            }

            }



          Is there a better way to do this?



          There certainly is a less involved way, as long as the consequent tight coupling between application and policy does not irk you too badly: Just subclass Policy directly and pass an instance of your implementation to Policy.setPolicy(Policy).




          Further reading:


          • Java Cryptography Architecture (JCA) Reference Guide

          • How to Implement a Provider in the Java Cryptography Architecture

          • Standard Algorithm Name Documentation for JDK 8

          • Troubleshooting Security






          share|improve this answer




























            up vote
            0
            down vote













            As of Java 6, the default implementation for PolicySpi is sun.security.provider.PolicySpiFile. You can get inspired from the source code of PolicySpiFile:



            package sun.security.provider;

            import java.security.CodeSource;
            import java.security.Permission;
            import java.security.PermissionCollection;
            import java.security.Policy;
            import java.security.PolicySpi;
            import java.security.ProtectionDomain;
            import java.security.URIParameter;

            import java.net.MalformedURLException;

            /**
            * This class wraps the PolicyFile subclass implementation of Policy
            * inside a PolicySpi implementation that is available from the SUN provider
            * via the Policy.getInstance calls.
            *
            */
            public final class PolicySpiFile extends PolicySpi {

            private PolicyFile pf;

            public PolicySpiFile(Policy.Parameters params) {

            if (params == null) {
            pf = new PolicyFile();
            } else {
            if (!(params instanceof URIParameter)) {
            throw new IllegalArgumentException
            ("Unrecognized policy parameter: " + params);
            }
            URIParameter uriParam = (URIParameter)params;
            try {
            pf = new PolicyFile(uriParam.getURI().toURL());
            } catch (MalformedURLException mue) {
            throw new IllegalArgumentException("Invalid URIParameter", mue);
            }
            }
            }

            protected PermissionCollection engineGetPermissions(CodeSource codesource) {
            return pf.getPermissions(codesource);
            }

            protected PermissionCollection engineGetPermissions(ProtectionDomain d) {
            return pf.getPermissions(d);
            }

            protected boolean engineImplies(ProtectionDomain d, Permission p) {
            return pf.implies(d, p);
            }

            protected void engineRefresh() {
            pf.refresh();
            }
            }





            share|improve this answer





















              Your Answer






              StackExchange.ifUsing("editor", function () {
              StackExchange.using("externalEditor", function () {
              StackExchange.using("snippets", function () {
              StackExchange.snippets.init();
              });
              });
              }, "code-snippets");

              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "1"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














               

              draft saved


              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f22016669%2fhow-to-use-custom-policyspi%23new-answer', 'question_page');
              }
              );

              Post as a guest
































              3 Answers
              3






              active

              oldest

              votes








              3 Answers
              3






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes








              up vote
              3
              down vote



              accepted










              Checking permissions



              In your question you stated that you then want to check the permission with java.security.Policy, but without using a spi.policy file.



              From the PolicySpi API, you can see that a PolicySpi object features 4 methods:




              1. engineGetPermissions(CodeSource codesource)

              2. engineGetPermissions(ProtectionDomain domain)

              3. engineImplies(ProtectionDomain domain, Permission permission)

              4. engineRefresh()


              However, you might not need PolicySpi as there are easier solutions to check permissions.



              See:




              • Security Manager vs Access Controller

              • AccessController usage


              Since you haven't specified what kind of permission you will grant, I will assume it is a permission concerning a java.security.CodeSource object.



              To check all current permissions for a file:



              public static void main(String args) {

              CodeSource source;

              try {
              source = new CodeSource(new URL("file:/c:/*"), (java.security.cert.Certificate) null);

              Policy policy = Policy.getPolicy();
              System.out.println(policy.getPermissions(source));

              } catch (IOException e) {
              e.printStackTrace();
              }
              }


              A nice example for the SecurityManager checkPermission() is this tutorial.



              For checking specific FilePermissions, you can use:



              FilePermission perm = new FilePermission("path/file", "read");
              AccessController.checkPermission(perm);


              Granting permissions



              Granting permissions at runtime can be done with java.lang.RuntimePermission.



              For other examples of how to grant permissions to a file, I suggest you read the following:




              • Access Control Mechanisms and Algorithms

              • Configuring spi.policy files

              • Security Managers and Permissions




              That should bring you a long way! Good luck!






              share|improve this answer























              • The idea is to create a runtime checking of a custom Permission (MyPermission). Since the checking may vary during runtime, I need a implementation without policy file. I already used AccessController.checkPermission(). The only thing is I need this method to go to a interface which provides runtime information
                – OblongZebra
                Mar 31 '14 at 14:50










              • According to THIS, There is only one instance of AccessController in each Java runtime.. This means that the default context is already the context of the current runtime.
                – Jean-Paul
                Mar 31 '14 at 15:07






              • 1




                Thats true, I'am using AccessController.checkPermission which uses the Policy in its turn. The Policy should do specific checking, for instance if the time is between 8:00 and 10:00 the permission is allowed otherwise it is not allowed. But that is possible especially with the 'configuring spi.policy files' I now know how to start using it. Thx.
                – OblongZebra
                Mar 31 '14 at 15:16










              • @OblongZebra: Too bad of your reputation bounty :( You didn't use it!
                – Jean-Paul
                Mar 31 '14 at 15:20










              • Sorry I reacted to late. I requested stackoverflow to allow you the bounty anyway, hope they grant it.
                – OblongZebra
                Apr 4 '14 at 7:33















              up vote
              3
              down vote



              accepted










              Checking permissions



              In your question you stated that you then want to check the permission with java.security.Policy, but without using a spi.policy file.



              From the PolicySpi API, you can see that a PolicySpi object features 4 methods:




              1. engineGetPermissions(CodeSource codesource)

              2. engineGetPermissions(ProtectionDomain domain)

              3. engineImplies(ProtectionDomain domain, Permission permission)

              4. engineRefresh()


              However, you might not need PolicySpi as there are easier solutions to check permissions.



              See:




              • Security Manager vs Access Controller

              • AccessController usage


              Since you haven't specified what kind of permission you will grant, I will assume it is a permission concerning a java.security.CodeSource object.



              To check all current permissions for a file:



              public static void main(String args) {

              CodeSource source;

              try {
              source = new CodeSource(new URL("file:/c:/*"), (java.security.cert.Certificate) null);

              Policy policy = Policy.getPolicy();
              System.out.println(policy.getPermissions(source));

              } catch (IOException e) {
              e.printStackTrace();
              }
              }


              A nice example for the SecurityManager checkPermission() is this tutorial.



              For checking specific FilePermissions, you can use:



              FilePermission perm = new FilePermission("path/file", "read");
              AccessController.checkPermission(perm);


              Granting permissions



              Granting permissions at runtime can be done with java.lang.RuntimePermission.



              For other examples of how to grant permissions to a file, I suggest you read the following:




              • Access Control Mechanisms and Algorithms

              • Configuring spi.policy files

              • Security Managers and Permissions




              That should bring you a long way! Good luck!






              share|improve this answer























              • The idea is to create a runtime checking of a custom Permission (MyPermission). Since the checking may vary during runtime, I need a implementation without policy file. I already used AccessController.checkPermission(). The only thing is I need this method to go to a interface which provides runtime information
                – OblongZebra
                Mar 31 '14 at 14:50










              • According to THIS, There is only one instance of AccessController in each Java runtime.. This means that the default context is already the context of the current runtime.
                – Jean-Paul
                Mar 31 '14 at 15:07






              • 1




                Thats true, I'am using AccessController.checkPermission which uses the Policy in its turn. The Policy should do specific checking, for instance if the time is between 8:00 and 10:00 the permission is allowed otherwise it is not allowed. But that is possible especially with the 'configuring spi.policy files' I now know how to start using it. Thx.
                – OblongZebra
                Mar 31 '14 at 15:16










              • @OblongZebra: Too bad of your reputation bounty :( You didn't use it!
                – Jean-Paul
                Mar 31 '14 at 15:20










              • Sorry I reacted to late. I requested stackoverflow to allow you the bounty anyway, hope they grant it.
                – OblongZebra
                Apr 4 '14 at 7:33













              up vote
              3
              down vote



              accepted







              up vote
              3
              down vote



              accepted






              Checking permissions



              In your question you stated that you then want to check the permission with java.security.Policy, but without using a spi.policy file.



              From the PolicySpi API, you can see that a PolicySpi object features 4 methods:




              1. engineGetPermissions(CodeSource codesource)

              2. engineGetPermissions(ProtectionDomain domain)

              3. engineImplies(ProtectionDomain domain, Permission permission)

              4. engineRefresh()


              However, you might not need PolicySpi as there are easier solutions to check permissions.



              See:




              • Security Manager vs Access Controller

              • AccessController usage


              Since you haven't specified what kind of permission you will grant, I will assume it is a permission concerning a java.security.CodeSource object.



              To check all current permissions for a file:



              public static void main(String args) {

              CodeSource source;

              try {
              source = new CodeSource(new URL("file:/c:/*"), (java.security.cert.Certificate) null);

              Policy policy = Policy.getPolicy();
              System.out.println(policy.getPermissions(source));

              } catch (IOException e) {
              e.printStackTrace();
              }
              }


              A nice example for the SecurityManager checkPermission() is this tutorial.



              For checking specific FilePermissions, you can use:



              FilePermission perm = new FilePermission("path/file", "read");
              AccessController.checkPermission(perm);


              Granting permissions



              Granting permissions at runtime can be done with java.lang.RuntimePermission.



              For other examples of how to grant permissions to a file, I suggest you read the following:




              • Access Control Mechanisms and Algorithms

              • Configuring spi.policy files

              • Security Managers and Permissions




              That should bring you a long way! Good luck!






              share|improve this answer














              Checking permissions



              In your question you stated that you then want to check the permission with java.security.Policy, but without using a spi.policy file.



              From the PolicySpi API, you can see that a PolicySpi object features 4 methods:




              1. engineGetPermissions(CodeSource codesource)

              2. engineGetPermissions(ProtectionDomain domain)

              3. engineImplies(ProtectionDomain domain, Permission permission)

              4. engineRefresh()


              However, you might not need PolicySpi as there are easier solutions to check permissions.



              See:




              • Security Manager vs Access Controller

              • AccessController usage


              Since you haven't specified what kind of permission you will grant, I will assume it is a permission concerning a java.security.CodeSource object.



              To check all current permissions for a file:



              public static void main(String args) {

              CodeSource source;

              try {
              source = new CodeSource(new URL("file:/c:/*"), (java.security.cert.Certificate) null);

              Policy policy = Policy.getPolicy();
              System.out.println(policy.getPermissions(source));

              } catch (IOException e) {
              e.printStackTrace();
              }
              }


              A nice example for the SecurityManager checkPermission() is this tutorial.



              For checking specific FilePermissions, you can use:



              FilePermission perm = new FilePermission("path/file", "read");
              AccessController.checkPermission(perm);


              Granting permissions



              Granting permissions at runtime can be done with java.lang.RuntimePermission.



              For other examples of how to grant permissions to a file, I suggest you read the following:




              • Access Control Mechanisms and Algorithms

              • Configuring spi.policy files

              • Security Managers and Permissions




              That should bring you a long way! Good luck!







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited May 23 '17 at 12:05









              Community

              11




              11










              answered Mar 24 '14 at 19:10









              Jean-Paul

              7,93263763




              7,93263763












              • The idea is to create a runtime checking of a custom Permission (MyPermission). Since the checking may vary during runtime, I need a implementation without policy file. I already used AccessController.checkPermission(). The only thing is I need this method to go to a interface which provides runtime information
                – OblongZebra
                Mar 31 '14 at 14:50










              • According to THIS, There is only one instance of AccessController in each Java runtime.. This means that the default context is already the context of the current runtime.
                – Jean-Paul
                Mar 31 '14 at 15:07






              • 1




                Thats true, I'am using AccessController.checkPermission which uses the Policy in its turn. The Policy should do specific checking, for instance if the time is between 8:00 and 10:00 the permission is allowed otherwise it is not allowed. But that is possible especially with the 'configuring spi.policy files' I now know how to start using it. Thx.
                – OblongZebra
                Mar 31 '14 at 15:16










              • @OblongZebra: Too bad of your reputation bounty :( You didn't use it!
                – Jean-Paul
                Mar 31 '14 at 15:20










              • Sorry I reacted to late. I requested stackoverflow to allow you the bounty anyway, hope they grant it.
                – OblongZebra
                Apr 4 '14 at 7:33


















              • The idea is to create a runtime checking of a custom Permission (MyPermission). Since the checking may vary during runtime, I need a implementation without policy file. I already used AccessController.checkPermission(). The only thing is I need this method to go to a interface which provides runtime information
                – OblongZebra
                Mar 31 '14 at 14:50










              • According to THIS, There is only one instance of AccessController in each Java runtime.. This means that the default context is already the context of the current runtime.
                – Jean-Paul
                Mar 31 '14 at 15:07






              • 1




                Thats true, I'am using AccessController.checkPermission which uses the Policy in its turn. The Policy should do specific checking, for instance if the time is between 8:00 and 10:00 the permission is allowed otherwise it is not allowed. But that is possible especially with the 'configuring spi.policy files' I now know how to start using it. Thx.
                – OblongZebra
                Mar 31 '14 at 15:16










              • @OblongZebra: Too bad of your reputation bounty :( You didn't use it!
                – Jean-Paul
                Mar 31 '14 at 15:20










              • Sorry I reacted to late. I requested stackoverflow to allow you the bounty anyway, hope they grant it.
                – OblongZebra
                Apr 4 '14 at 7:33
















              The idea is to create a runtime checking of a custom Permission (MyPermission). Since the checking may vary during runtime, I need a implementation without policy file. I already used AccessController.checkPermission(). The only thing is I need this method to go to a interface which provides runtime information
              – OblongZebra
              Mar 31 '14 at 14:50




              The idea is to create a runtime checking of a custom Permission (MyPermission). Since the checking may vary during runtime, I need a implementation without policy file. I already used AccessController.checkPermission(). The only thing is I need this method to go to a interface which provides runtime information
              – OblongZebra
              Mar 31 '14 at 14:50












              According to THIS, There is only one instance of AccessController in each Java runtime.. This means that the default context is already the context of the current runtime.
              – Jean-Paul
              Mar 31 '14 at 15:07




              According to THIS, There is only one instance of AccessController in each Java runtime.. This means that the default context is already the context of the current runtime.
              – Jean-Paul
              Mar 31 '14 at 15:07




              1




              1




              Thats true, I'am using AccessController.checkPermission which uses the Policy in its turn. The Policy should do specific checking, for instance if the time is between 8:00 and 10:00 the permission is allowed otherwise it is not allowed. But that is possible especially with the 'configuring spi.policy files' I now know how to start using it. Thx.
              – OblongZebra
              Mar 31 '14 at 15:16




              Thats true, I'am using AccessController.checkPermission which uses the Policy in its turn. The Policy should do specific checking, for instance if the time is between 8:00 and 10:00 the permission is allowed otherwise it is not allowed. But that is possible especially with the 'configuring spi.policy files' I now know how to start using it. Thx.
              – OblongZebra
              Mar 31 '14 at 15:16












              @OblongZebra: Too bad of your reputation bounty :( You didn't use it!
              – Jean-Paul
              Mar 31 '14 at 15:20




              @OblongZebra: Too bad of your reputation bounty :( You didn't use it!
              – Jean-Paul
              Mar 31 '14 at 15:20












              Sorry I reacted to late. I requested stackoverflow to allow you the bounty anyway, hope they grant it.
              – OblongZebra
              Apr 4 '14 at 7:33




              Sorry I reacted to late. I requested stackoverflow to allow you the bounty anyway, hope they grant it.
              – OblongZebra
              Apr 4 '14 at 7:33












              up vote
              0
              down vote













              The previous answer lists alternatives to using PolicySpi (and more generally custom Policy implementations ). This answer will instead give a simplistic example on how a PolicySpi implementation can actually be used as a replacement of the system-default Policy.





              1. Author a JCA Provider.



                package com.example;

                import java.security.AccessController;
                import java.security.PrivilegedAction;
                import java.security.Provider;

                public final class TestProvider extends Provider {

                private static final long serialVersionUID = 5544432861418770903L;

                public TestProvider() {
                super("TestProvider", 1, "TestProvider 1.0");
                AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
                putService(new TestPolicySpiService(this));
                return null;
                });
                }

                }



              2. Author the sole Service descriptor encapsulated by the provider.



                package com.example;

                import java.security.Policy.Parameters;
                import java.security.PolicySpi;
                import java.security.Provider;
                import java.security.Provider.Service;
                import java.util.Collections;

                final class TestPolicySpiService extends Service {

                TestPolicySpiService(Provider p) {
                super(p, "Policy", "TestPolicy", PolicySpi.class.getName(), Collections.emptyList(), Collections.emptyMap());
                }

                @Override
                public PolicySpi newInstance(Object constructorParameter) {
                Parameters policyParams = null;
                if (constructorParameter instanceof Parameters) {
                policyParams = (Parameters) constructorParameter;
                }
                return new TestPolicySpi(policyParams);
                }

                @Override
                public boolean supportsParameter(Object parameter) {
                return parameter instanceof Parameters;
                }

                }



              3. Author the actual service (the PolicySpi implementation in this case) that the service descriptor produces.



                package com.example;

                import java.security.Permission;
                import java.security.Policy.Parameters;
                import java.security.PolicySpi;
                import java.security.ProtectionDomain;

                final class TestPolicySpi extends PolicySpi {

                TestPolicySpi(Parameters policyParams) {}

                @Override
                protected boolean engineImplies(ProtectionDomain domain, Permission permission) {
                // deny unconditionally
                return false;
                }

                }


              4. Register the provider either statically, by modifying the security.provider.n properties in JAVA_HOME/lib/security/java.security, or programmatically, via java.security.Security.addProvider(Provider) / java.security.Security.insertProviderAt(Provider, int).



              5. Replace the default Policy.



                package com.example;

                import java.security.NoSuchAlgorithmException;
                import java.security.Policy;

                public class Main {

                public static void main(String... args) throws NoSuchAlgorithmException {
                // the following assumes that the provider has been statically registered
                Policy.setPolicy(Policy.getInstance("TestPolicy", null));
                System.setSecurityManager(new SecurityManager());

                // test
                System.out.println(System.getProperty("user.home")); // should raise AccessControlException
                }

                }



              Is there a better way to do this?



              There certainly is a less involved way, as long as the consequent tight coupling between application and policy does not irk you too badly: Just subclass Policy directly and pass an instance of your implementation to Policy.setPolicy(Policy).




              Further reading:


              • Java Cryptography Architecture (JCA) Reference Guide

              • How to Implement a Provider in the Java Cryptography Architecture

              • Standard Algorithm Name Documentation for JDK 8

              • Troubleshooting Security






              share|improve this answer

























                up vote
                0
                down vote













                The previous answer lists alternatives to using PolicySpi (and more generally custom Policy implementations ). This answer will instead give a simplistic example on how a PolicySpi implementation can actually be used as a replacement of the system-default Policy.





                1. Author a JCA Provider.



                  package com.example;

                  import java.security.AccessController;
                  import java.security.PrivilegedAction;
                  import java.security.Provider;

                  public final class TestProvider extends Provider {

                  private static final long serialVersionUID = 5544432861418770903L;

                  public TestProvider() {
                  super("TestProvider", 1, "TestProvider 1.0");
                  AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
                  putService(new TestPolicySpiService(this));
                  return null;
                  });
                  }

                  }



                2. Author the sole Service descriptor encapsulated by the provider.



                  package com.example;

                  import java.security.Policy.Parameters;
                  import java.security.PolicySpi;
                  import java.security.Provider;
                  import java.security.Provider.Service;
                  import java.util.Collections;

                  final class TestPolicySpiService extends Service {

                  TestPolicySpiService(Provider p) {
                  super(p, "Policy", "TestPolicy", PolicySpi.class.getName(), Collections.emptyList(), Collections.emptyMap());
                  }

                  @Override
                  public PolicySpi newInstance(Object constructorParameter) {
                  Parameters policyParams = null;
                  if (constructorParameter instanceof Parameters) {
                  policyParams = (Parameters) constructorParameter;
                  }
                  return new TestPolicySpi(policyParams);
                  }

                  @Override
                  public boolean supportsParameter(Object parameter) {
                  return parameter instanceof Parameters;
                  }

                  }



                3. Author the actual service (the PolicySpi implementation in this case) that the service descriptor produces.



                  package com.example;

                  import java.security.Permission;
                  import java.security.Policy.Parameters;
                  import java.security.PolicySpi;
                  import java.security.ProtectionDomain;

                  final class TestPolicySpi extends PolicySpi {

                  TestPolicySpi(Parameters policyParams) {}

                  @Override
                  protected boolean engineImplies(ProtectionDomain domain, Permission permission) {
                  // deny unconditionally
                  return false;
                  }

                  }


                4. Register the provider either statically, by modifying the security.provider.n properties in JAVA_HOME/lib/security/java.security, or programmatically, via java.security.Security.addProvider(Provider) / java.security.Security.insertProviderAt(Provider, int).



                5. Replace the default Policy.



                  package com.example;

                  import java.security.NoSuchAlgorithmException;
                  import java.security.Policy;

                  public class Main {

                  public static void main(String... args) throws NoSuchAlgorithmException {
                  // the following assumes that the provider has been statically registered
                  Policy.setPolicy(Policy.getInstance("TestPolicy", null));
                  System.setSecurityManager(new SecurityManager());

                  // test
                  System.out.println(System.getProperty("user.home")); // should raise AccessControlException
                  }

                  }



                Is there a better way to do this?



                There certainly is a less involved way, as long as the consequent tight coupling between application and policy does not irk you too badly: Just subclass Policy directly and pass an instance of your implementation to Policy.setPolicy(Policy).




                Further reading:


                • Java Cryptography Architecture (JCA) Reference Guide

                • How to Implement a Provider in the Java Cryptography Architecture

                • Standard Algorithm Name Documentation for JDK 8

                • Troubleshooting Security






                share|improve this answer























                  up vote
                  0
                  down vote










                  up vote
                  0
                  down vote









                  The previous answer lists alternatives to using PolicySpi (and more generally custom Policy implementations ). This answer will instead give a simplistic example on how a PolicySpi implementation can actually be used as a replacement of the system-default Policy.





                  1. Author a JCA Provider.



                    package com.example;

                    import java.security.AccessController;
                    import java.security.PrivilegedAction;
                    import java.security.Provider;

                    public final class TestProvider extends Provider {

                    private static final long serialVersionUID = 5544432861418770903L;

                    public TestProvider() {
                    super("TestProvider", 1, "TestProvider 1.0");
                    AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
                    putService(new TestPolicySpiService(this));
                    return null;
                    });
                    }

                    }



                  2. Author the sole Service descriptor encapsulated by the provider.



                    package com.example;

                    import java.security.Policy.Parameters;
                    import java.security.PolicySpi;
                    import java.security.Provider;
                    import java.security.Provider.Service;
                    import java.util.Collections;

                    final class TestPolicySpiService extends Service {

                    TestPolicySpiService(Provider p) {
                    super(p, "Policy", "TestPolicy", PolicySpi.class.getName(), Collections.emptyList(), Collections.emptyMap());
                    }

                    @Override
                    public PolicySpi newInstance(Object constructorParameter) {
                    Parameters policyParams = null;
                    if (constructorParameter instanceof Parameters) {
                    policyParams = (Parameters) constructorParameter;
                    }
                    return new TestPolicySpi(policyParams);
                    }

                    @Override
                    public boolean supportsParameter(Object parameter) {
                    return parameter instanceof Parameters;
                    }

                    }



                  3. Author the actual service (the PolicySpi implementation in this case) that the service descriptor produces.



                    package com.example;

                    import java.security.Permission;
                    import java.security.Policy.Parameters;
                    import java.security.PolicySpi;
                    import java.security.ProtectionDomain;

                    final class TestPolicySpi extends PolicySpi {

                    TestPolicySpi(Parameters policyParams) {}

                    @Override
                    protected boolean engineImplies(ProtectionDomain domain, Permission permission) {
                    // deny unconditionally
                    return false;
                    }

                    }


                  4. Register the provider either statically, by modifying the security.provider.n properties in JAVA_HOME/lib/security/java.security, or programmatically, via java.security.Security.addProvider(Provider) / java.security.Security.insertProviderAt(Provider, int).



                  5. Replace the default Policy.



                    package com.example;

                    import java.security.NoSuchAlgorithmException;
                    import java.security.Policy;

                    public class Main {

                    public static void main(String... args) throws NoSuchAlgorithmException {
                    // the following assumes that the provider has been statically registered
                    Policy.setPolicy(Policy.getInstance("TestPolicy", null));
                    System.setSecurityManager(new SecurityManager());

                    // test
                    System.out.println(System.getProperty("user.home")); // should raise AccessControlException
                    }

                    }



                  Is there a better way to do this?



                  There certainly is a less involved way, as long as the consequent tight coupling between application and policy does not irk you too badly: Just subclass Policy directly and pass an instance of your implementation to Policy.setPolicy(Policy).




                  Further reading:


                  • Java Cryptography Architecture (JCA) Reference Guide

                  • How to Implement a Provider in the Java Cryptography Architecture

                  • Standard Algorithm Name Documentation for JDK 8

                  • Troubleshooting Security






                  share|improve this answer












                  The previous answer lists alternatives to using PolicySpi (and more generally custom Policy implementations ). This answer will instead give a simplistic example on how a PolicySpi implementation can actually be used as a replacement of the system-default Policy.





                  1. Author a JCA Provider.



                    package com.example;

                    import java.security.AccessController;
                    import java.security.PrivilegedAction;
                    import java.security.Provider;

                    public final class TestProvider extends Provider {

                    private static final long serialVersionUID = 5544432861418770903L;

                    public TestProvider() {
                    super("TestProvider", 1, "TestProvider 1.0");
                    AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
                    putService(new TestPolicySpiService(this));
                    return null;
                    });
                    }

                    }



                  2. Author the sole Service descriptor encapsulated by the provider.



                    package com.example;

                    import java.security.Policy.Parameters;
                    import java.security.PolicySpi;
                    import java.security.Provider;
                    import java.security.Provider.Service;
                    import java.util.Collections;

                    final class TestPolicySpiService extends Service {

                    TestPolicySpiService(Provider p) {
                    super(p, "Policy", "TestPolicy", PolicySpi.class.getName(), Collections.emptyList(), Collections.emptyMap());
                    }

                    @Override
                    public PolicySpi newInstance(Object constructorParameter) {
                    Parameters policyParams = null;
                    if (constructorParameter instanceof Parameters) {
                    policyParams = (Parameters) constructorParameter;
                    }
                    return new TestPolicySpi(policyParams);
                    }

                    @Override
                    public boolean supportsParameter(Object parameter) {
                    return parameter instanceof Parameters;
                    }

                    }



                  3. Author the actual service (the PolicySpi implementation in this case) that the service descriptor produces.



                    package com.example;

                    import java.security.Permission;
                    import java.security.Policy.Parameters;
                    import java.security.PolicySpi;
                    import java.security.ProtectionDomain;

                    final class TestPolicySpi extends PolicySpi {

                    TestPolicySpi(Parameters policyParams) {}

                    @Override
                    protected boolean engineImplies(ProtectionDomain domain, Permission permission) {
                    // deny unconditionally
                    return false;
                    }

                    }


                  4. Register the provider either statically, by modifying the security.provider.n properties in JAVA_HOME/lib/security/java.security, or programmatically, via java.security.Security.addProvider(Provider) / java.security.Security.insertProviderAt(Provider, int).



                  5. Replace the default Policy.



                    package com.example;

                    import java.security.NoSuchAlgorithmException;
                    import java.security.Policy;

                    public class Main {

                    public static void main(String... args) throws NoSuchAlgorithmException {
                    // the following assumes that the provider has been statically registered
                    Policy.setPolicy(Policy.getInstance("TestPolicy", null));
                    System.setSecurityManager(new SecurityManager());

                    // test
                    System.out.println(System.getProperty("user.home")); // should raise AccessControlException
                    }

                    }



                  Is there a better way to do this?



                  There certainly is a less involved way, as long as the consequent tight coupling between application and policy does not irk you too badly: Just subclass Policy directly and pass an instance of your implementation to Policy.setPolicy(Policy).




                  Further reading:


                  • Java Cryptography Architecture (JCA) Reference Guide

                  • How to Implement a Provider in the Java Cryptography Architecture

                  • Standard Algorithm Name Documentation for JDK 8

                  • Troubleshooting Security







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Aug 19 '17 at 16:10









                  Uux

                  9931715




                  9931715






















                      up vote
                      0
                      down vote













                      As of Java 6, the default implementation for PolicySpi is sun.security.provider.PolicySpiFile. You can get inspired from the source code of PolicySpiFile:



                      package sun.security.provider;

                      import java.security.CodeSource;
                      import java.security.Permission;
                      import java.security.PermissionCollection;
                      import java.security.Policy;
                      import java.security.PolicySpi;
                      import java.security.ProtectionDomain;
                      import java.security.URIParameter;

                      import java.net.MalformedURLException;

                      /**
                      * This class wraps the PolicyFile subclass implementation of Policy
                      * inside a PolicySpi implementation that is available from the SUN provider
                      * via the Policy.getInstance calls.
                      *
                      */
                      public final class PolicySpiFile extends PolicySpi {

                      private PolicyFile pf;

                      public PolicySpiFile(Policy.Parameters params) {

                      if (params == null) {
                      pf = new PolicyFile();
                      } else {
                      if (!(params instanceof URIParameter)) {
                      throw new IllegalArgumentException
                      ("Unrecognized policy parameter: " + params);
                      }
                      URIParameter uriParam = (URIParameter)params;
                      try {
                      pf = new PolicyFile(uriParam.getURI().toURL());
                      } catch (MalformedURLException mue) {
                      throw new IllegalArgumentException("Invalid URIParameter", mue);
                      }
                      }
                      }

                      protected PermissionCollection engineGetPermissions(CodeSource codesource) {
                      return pf.getPermissions(codesource);
                      }

                      protected PermissionCollection engineGetPermissions(ProtectionDomain d) {
                      return pf.getPermissions(d);
                      }

                      protected boolean engineImplies(ProtectionDomain d, Permission p) {
                      return pf.implies(d, p);
                      }

                      protected void engineRefresh() {
                      pf.refresh();
                      }
                      }





                      share|improve this answer

























                        up vote
                        0
                        down vote













                        As of Java 6, the default implementation for PolicySpi is sun.security.provider.PolicySpiFile. You can get inspired from the source code of PolicySpiFile:



                        package sun.security.provider;

                        import java.security.CodeSource;
                        import java.security.Permission;
                        import java.security.PermissionCollection;
                        import java.security.Policy;
                        import java.security.PolicySpi;
                        import java.security.ProtectionDomain;
                        import java.security.URIParameter;

                        import java.net.MalformedURLException;

                        /**
                        * This class wraps the PolicyFile subclass implementation of Policy
                        * inside a PolicySpi implementation that is available from the SUN provider
                        * via the Policy.getInstance calls.
                        *
                        */
                        public final class PolicySpiFile extends PolicySpi {

                        private PolicyFile pf;

                        public PolicySpiFile(Policy.Parameters params) {

                        if (params == null) {
                        pf = new PolicyFile();
                        } else {
                        if (!(params instanceof URIParameter)) {
                        throw new IllegalArgumentException
                        ("Unrecognized policy parameter: " + params);
                        }
                        URIParameter uriParam = (URIParameter)params;
                        try {
                        pf = new PolicyFile(uriParam.getURI().toURL());
                        } catch (MalformedURLException mue) {
                        throw new IllegalArgumentException("Invalid URIParameter", mue);
                        }
                        }
                        }

                        protected PermissionCollection engineGetPermissions(CodeSource codesource) {
                        return pf.getPermissions(codesource);
                        }

                        protected PermissionCollection engineGetPermissions(ProtectionDomain d) {
                        return pf.getPermissions(d);
                        }

                        protected boolean engineImplies(ProtectionDomain d, Permission p) {
                        return pf.implies(d, p);
                        }

                        protected void engineRefresh() {
                        pf.refresh();
                        }
                        }





                        share|improve this answer























                          up vote
                          0
                          down vote










                          up vote
                          0
                          down vote









                          As of Java 6, the default implementation for PolicySpi is sun.security.provider.PolicySpiFile. You can get inspired from the source code of PolicySpiFile:



                          package sun.security.provider;

                          import java.security.CodeSource;
                          import java.security.Permission;
                          import java.security.PermissionCollection;
                          import java.security.Policy;
                          import java.security.PolicySpi;
                          import java.security.ProtectionDomain;
                          import java.security.URIParameter;

                          import java.net.MalformedURLException;

                          /**
                          * This class wraps the PolicyFile subclass implementation of Policy
                          * inside a PolicySpi implementation that is available from the SUN provider
                          * via the Policy.getInstance calls.
                          *
                          */
                          public final class PolicySpiFile extends PolicySpi {

                          private PolicyFile pf;

                          public PolicySpiFile(Policy.Parameters params) {

                          if (params == null) {
                          pf = new PolicyFile();
                          } else {
                          if (!(params instanceof URIParameter)) {
                          throw new IllegalArgumentException
                          ("Unrecognized policy parameter: " + params);
                          }
                          URIParameter uriParam = (URIParameter)params;
                          try {
                          pf = new PolicyFile(uriParam.getURI().toURL());
                          } catch (MalformedURLException mue) {
                          throw new IllegalArgumentException("Invalid URIParameter", mue);
                          }
                          }
                          }

                          protected PermissionCollection engineGetPermissions(CodeSource codesource) {
                          return pf.getPermissions(codesource);
                          }

                          protected PermissionCollection engineGetPermissions(ProtectionDomain d) {
                          return pf.getPermissions(d);
                          }

                          protected boolean engineImplies(ProtectionDomain d, Permission p) {
                          return pf.implies(d, p);
                          }

                          protected void engineRefresh() {
                          pf.refresh();
                          }
                          }





                          share|improve this answer












                          As of Java 6, the default implementation for PolicySpi is sun.security.provider.PolicySpiFile. You can get inspired from the source code of PolicySpiFile:



                          package sun.security.provider;

                          import java.security.CodeSource;
                          import java.security.Permission;
                          import java.security.PermissionCollection;
                          import java.security.Policy;
                          import java.security.PolicySpi;
                          import java.security.ProtectionDomain;
                          import java.security.URIParameter;

                          import java.net.MalformedURLException;

                          /**
                          * This class wraps the PolicyFile subclass implementation of Policy
                          * inside a PolicySpi implementation that is available from the SUN provider
                          * via the Policy.getInstance calls.
                          *
                          */
                          public final class PolicySpiFile extends PolicySpi {

                          private PolicyFile pf;

                          public PolicySpiFile(Policy.Parameters params) {

                          if (params == null) {
                          pf = new PolicyFile();
                          } else {
                          if (!(params instanceof URIParameter)) {
                          throw new IllegalArgumentException
                          ("Unrecognized policy parameter: " + params);
                          }
                          URIParameter uriParam = (URIParameter)params;
                          try {
                          pf = new PolicyFile(uriParam.getURI().toURL());
                          } catch (MalformedURLException mue) {
                          throw new IllegalArgumentException("Invalid URIParameter", mue);
                          }
                          }
                          }

                          protected PermissionCollection engineGetPermissions(CodeSource codesource) {
                          return pf.getPermissions(codesource);
                          }

                          protected PermissionCollection engineGetPermissions(ProtectionDomain d) {
                          return pf.getPermissions(d);
                          }

                          protected boolean engineImplies(ProtectionDomain d, Permission p) {
                          return pf.implies(d, p);
                          }

                          protected void engineRefresh() {
                          pf.refresh();
                          }
                          }






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered 2 days ago









                          M.S. Dousti

                          1,44842236




                          1,44842236






























                               

                              draft saved


                              draft discarded



















































                               


                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f22016669%2fhow-to-use-custom-policyspi%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest




















































































                              Popular posts from this blog

                              Full-time equivalent

                              さくらももこ

                              13 indicted, 8 arrested in Calif. drug cartel investigation