java.lang.SecurityException: Prohibited package name: java.demo 定位问题

来源:互联网 发布:php mysqli扩展 编辑:程序博客网 时间:2024/06/07 19:35
根据异常信息,定位到java.lang.ClassLoader.preDefineClass进行排查,发现以下代码片断: 
Java代码  收藏代码
  1. /* Determine protection domain, and check that: 
  2.         - not define java.* class, 
  3.         - signer of this class matches signers for the rest of the classes in package. 
  4. */  
  5.     private ProtectionDomain preDefineClass(String name,  
  6.     ProtectionDomain protectionDomain)  
  7.     {  
  8.     if (!checkName(name))  
  9.         throw new NoClassDefFoundError("IllegalName: " + name);  
  10.     if ((name != null) && [color=red]name.startsWith("java.")[/color]) {  
  11.         throw new SecurityException("Prohibited package name: " +  
  12.             name.substring(0, name.lastIndexOf('.')));  
  13.     }  
  14.     if (protectionDomain == null) {  
  15.         protectionDomain = getDefaultDomain();  
  16.     }  
  17.   
  18.     if (name != null)  
  19.         checkCerts(name, protectionDomain.getCodeSource());  
  20.   
  21.     return protectionDomain;  
  22.     }  
  23.   
  24. ......  
  25.   
  26. // true if the name is null or has the potential to be a valid binary name  
  27.     private boolean checkName(String name) {  
  28.     if ((name == null) || (name.length() == 0))  
  29.         return true;  
  30.     if ((name.indexOf('/') != -1)  
  31.         || (!VM.allowArraySyntax() && (name.charAt(0) == '[')))  
  32.         return false;  
  33.     return true;  
  34.     }  


可以看出preDefineClass方法首先对类名进行了检查,发现以java作为一级包名,则抛出安全异常:禁止使用的包名! 

这条安全异常是由Java类加载的“双亲委派模型”(详见这里)所导致的。在双亲委派模型中,由父加载类加载的类,下层加载器是不能加载的。本例中最高层加载器BootstrapClassLoader加载了classpath路径下所定义的java.*包内的类,而java.research包就不能由BootstrapClassLoader的下层加载器AppClassLoader加载了。这也是java安全机制中对于恶意代码所采取的防护措施。