Java security: how to ensure class is only access from specific package?
<p>Now I know I can mark a method as 'no modifier' so that its only accessible by Class &amp; Package.</p>

<p>That is not what I need in this case though. What I need is this:</p>

<p>Methods on Class "Secure.java" can only be accessed from other Classes in the same JAR file.</p>

<p>AND (this is extra)</p>

<p>When call is made into a secure method, the call stack does not go back to a none secure class &amp; then back in again. For example:</p>

<p>This is good:</p>

<ul>
<li>com.nonsecure.ClassA.doStuff() calls </li>
<li>com.nonsecure.ClassB.doStuff() calls </li>
<li>com.secure.Secure.doStuff() calls </li>
<li>com.secure.SecureB.doStuff()</li>
</ul>

<p>This is bad:</p>

<ul>
<li>com.nonsecure.ClassA.doStuff() calls</li>
<li>com.nonsecure.ClassB.doStuff() calls</li>
<li>com.secure.Secure.doStuff() calls</li>
<li>com.<strong>nonsecure</strong>.ClassC.doStuff() calls [BAD: we went outside the classes in the secure JAR!]</li>
<li>com.secure.SecureB.doStuff() </li>
</ul>

<hr>

<p>Now I think I can do this via a little manual work:</p>

<pre><code> private void checkSecurity()
  {
    StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
    for (StackTraceElement stackTraceElement : stackTraceElements)
    {
      // TODO: Add a little magic to check that we've not stepped outside the secure packages.
      if (!stackTraceElement.getClassName().startsWith("com.secure"))
      {
         throw new SecurityException("Woop!");
      }
    }
  }
</code></pre>

<p>QUESTION: This feels like there should be something that Java provides to help me out here?</p>

<p>I've read about </p>

<pre><code>AccessController.doPrivileged(new PrivilegedExceptionAction&lt;String&gt;()
</code></pre>

<p>But seems to only be about accessing resources/network connections etc.
Not about accessing the call stack to ensure some sort of package protection.</p>

<p>Notes: </p>

<ul>
<li>I am using Spring 3 </li>
<li>The JAR file containing the secure code is signed
with a certificate. </li>
<li>Access to the secure class will only be from
within the JAR, direct access from outside the JAR must not be
allowed.</li>
</ul>
