1

We are building an engine that will allow us to add new jar files whenever, load those jar files and look for some specific functionality, and run the code that exposes that functionality. Current plan is to use the ServiceLoader to do so (just an extra detail; I'm not married to that idea). For the moment let's assume that we completely control which jar files are going to be loaded (big assumption--I'd guess I'm going to eventually post something about that too).

Given all that, I would like to restrict access in those extensions to certain classes. For a fake example, we want to ensure that instead of using java.io.PrintStream, they use our.better.PrintStreamSolution.

I really don't have a good idea of what I could do here. Since for the time being, we own the code that will go out as extensions, we could just do very thorough code reviews but I'd rather do either a static analysis at install time or actually throw errors at runtime. Any idea how one would would accomplish this?

4

2 に答える 2

2

API をホワイトリストに登録する必要があります。リフレクティブ API はいたるところにあるため、現実的にブラックリストに登録することはできません。これを行うには、ASM などのライブラリを使用して jar を調べる必要があります。カスタム URL 接続ハンドラを使用することもできますがURLClassLoader、カスタム クラス ローダーをお勧めします。などのグローバル状態に関係することは避けることを強くお勧めしServiceLoaderます。

于 2012-06-19T00:45:50.037 に答える
1

JAR を読み取る特別な ClassLoader を作成し、メソッド「loadClass」をオーバーライドして、クラスローダーが「java.io」パッケージからクラスをロードしようとすると SecurityException をスローするようにします。このようなもの:

protected Class loadClass(String name, boolean resolve)
                                            throws ClassNotFoundException { 
       if (name.startsWith("java.io")) 
             throw new SecurityException("java.io access not allowed on extensions");

        return super.loadClass(name,resolve); 
} 

ClassLoader のオーバーライドされた findClass メソッドにクラスローディング ロジックを実装することを忘れないでください。

拡張機能が別のクラスローダ (システム クラスローダなど) を取得して「禁止された」クラスをロードできる場合、このチェックを無効にすることができます。

コメントに示されているように、SecurityManager を使用する代替手段は、パッケージが拡張機能内からアクセスされていることをセキュリティ マネージャーが識別できる場合にのみ可能です。

于 2012-06-19T00:50:30.607 に答える