protected PermissionCollection getPermissions(CodeSource codeSource) {
    PermissionCollection perms;
    try {
      try {
        perms = super.getPermissions(codeSource);
      } catch (SecurityException e) {
        // We lied about our CodeSource and that makes URLClassLoader unhappy.
        perms = new Permissions();
      }

      ProtectionDomain myDomain =
          AccessController.doPrivileged(
              new PrivilegedAction<ProtectionDomain>() {
                public ProtectionDomain run() {
                  return getClass().getProtectionDomain();
                }
              });
      PermissionCollection myPerms = myDomain.getPermissions();
      if (myPerms != null) {
        for (Enumeration<Permission> elements = myPerms.elements(); elements.hasMoreElements(); ) {
          perms.add(elements.nextElement());
        }
      }
    } catch (Throwable e) {
      // We lied about our CodeSource and that makes URLClassLoader unhappy.
      perms = new Permissions();
    }
    perms.setReadOnly();
    return perms;
  }
    static {
	AccessController.doPrivileged(new PrivilegedAction() {
                public Object run() {
                    String cname = null;
                    try {
                        cname = System.getProperty("java.util.logging.manager");
                        if (cname != null) {
                            Class clz = ClassLoader.getSystemClassLoader().loadClass(cname);
                            manager = (LogManager) clz.newInstance();
                        }
                    } catch (Exception ex) {
                        System.err.println("Could not load Logmanager \"" + cname + "\"");
                        ex.printStackTrace();
                    }
                    if (manager == null) {
                        manager = new LogManager();
                    }

                    // Create and retain Logger for the root of the namespace.
                    manager.rootLogger = manager.new RootLogger();
                    manager.addLogger(manager.rootLogger);

                    // We don't call readConfiguration() here, as we may be running
                    // very early in the JVM startup sequence.  Instead readConfiguration
                    // will be called lazily in getLogManager().
                    return null;
                }
            });
    }
Exemple #3
0
 /**
  * Gets most recent focus owner component associated with the given window. It does that without
  * calling Window.getMostRecentFocusOwner since it provides its own logic contradicting with
  * setDefautlFocus. Instead, it calls KeyboardFocusManager directly.
  */
 private Component getMostRecentFocusOwnerForWindow(Window w) {
   Method meth =
       AccessController.doPrivileged(
           new PrivilegedAction<Method>() {
             @Override
             public Method run() {
               Method meth = null;
               try {
                 meth =
                     KeyboardFocusManager.class.getDeclaredMethod(
                         "getMostRecentFocusOwner", new Class<?>[] {Window.class});
                 meth.setAccessible(true);
               } catch (Exception e) {
                 // Must never happen
                 e.printStackTrace();
               }
               return meth;
             }
           });
   if (meth != null) {
     // Meth refers static method
     try {
       return (Component) meth.invoke(null, new Object[] {w});
     } catch (Exception e) {
       // Must never happen
       e.printStackTrace();
     }
   }
   // Will get here if exception was thrown or meth is null
   return w.getMostRecentFocusOwner();
 }
 private ModuleClassLoader getModuleClassLoader(boolean logResolveError) {
   ResolutionReport report = resolve();
   if (logResolveError && !Module.RESOLVED_SET.contains(module.getState())) {
     String reportMessage = report.getResolutionReportMessage(module.getCurrentRevision());
     equinoxContainer
         .getEventPublisher()
         .publishFrameworkEvent(
             FrameworkEvent.ERROR,
             this,
             new BundleException(reportMessage, BundleException.RESOLVE_ERROR));
   }
   return AccessController.doPrivileged(
       new PrivilegedAction<ModuleClassLoader>() {
         @Override
         public ModuleClassLoader run() {
           ModuleWiring wiring = getModule().getCurrentRevision().getWiring();
           if (wiring != null) {
             ModuleLoader moduleLoader = wiring.getModuleLoader();
             if (moduleLoader instanceof BundleLoader) {
               return ((BundleLoader) moduleLoader).getModuleClassLoader();
             }
           }
           return null;
         }
       });
 }
  private void updatePropertiesFromCustomizer(
      final FormProperty[] properties, final PropertyChangeEvent evt) {
    // we run this as privileged to avoid security problems - because
    // the property change is fired from untrusted bean customizer code
    AccessController.doPrivileged(
        new PrivilegedAction<Object>() {
          @Override
          public Object run() {
            Object oldValue = evt != null ? evt.getOldValue() : null;
            Object newValue = evt != null ? evt.getNewValue() : null;

            for (int i = 0; i < properties.length; i++) {
              FormProperty prop = properties[i];
              try {
                prop.reinstateProperty();
                //                        if (prop.isChanged()) // [what if changed to default
                // value?]
                prop.propertyValueChanged(oldValue, newValue);
              } catch (Exception ex) { // unlikely to happen
                ex.printStackTrace();
              }
            }
            return null;
          }
        });
  }
Exemple #6
0
  /*
   * Creates a thread to run the applet. This method is called
   * each time an applet is loaded and reloaded.
   */
  synchronized void createAppletThread() {
    // Create a thread group for the applet, and start a new
    // thread to load the applet.
    String nm = "applet-" + getCode();
    loader = getClassLoader(getCodeBase(), getClassLoaderCacheKey());
    loader.grab(); // Keep this puppy around!

    // 4668479: Option to turn off codebase lookup in AppletClassLoader
    // during resource requests. [stanley.ho]
    String param = getParameter("codebase_lookup");

    if (param != null && param.equals("false")) loader.setCodebaseLookup(false);
    else loader.setCodebaseLookup(true);

    ThreadGroup appletGroup = loader.getThreadGroup();
    handler = new Thread(appletGroup, this, "thread " + nm, 0, false);
    // set the context class loader for this thread
    AccessController.doPrivileged(
        new PrivilegedAction<Object>() {
          @Override
          public Object run() {
            handler.setContextClassLoader(loader);
            return null;
          }
        });
    handler.start();
  }
 public void typeKey(
     double sec,
     final int charCode,
     final int keyCode,
     final boolean alt,
     final boolean ctrl,
     final boolean shift,
     final int delay,
     final boolean async) {
   if (!isSecure(sec)) return;
   // called by doh.robot._keyPress
   // see it for details
   AccessController.doPrivileged(
       new PrivilegedAction() {
         public Object run() {
           try {
             log("> typeKey Robot " + charCode + ", " + keyCode + ", " + async);
             KeyPressThread thread =
                 new KeyPressThread(
                     charCode, keyCode, alt, ctrl, shift, delay, async ? null : previousThread);
             previousThread = async ? previousThread : thread;
             thread.start();
             log("< typeKey Robot");
           } catch (Exception e) {
             log("Error calling typeKey");
             e.printStackTrace();
           }
           return null;
         }
       });
 }
 public void moveMouse(double sec, final int x1, final int y1, final int d, final int duration) {
   // called by doh.robot.mouseMove
   // see it for details
   // a nice name like "mouseMove" is reserved in Java
   if (!isSecure(sec)) return;
   AccessController.doPrivileged(
       new PrivilegedAction() {
         public Object run() {
           int x = x1 + docScreenX;
           int y = y1 + docScreenY;
           if (x > docScreenXMax || y > docScreenYMax) {
             // TODO: try to scroll view
             log("Request to mouseMove denied");
             return null;
           }
           int delay = d;
           log("> mouseMove Robot " + x + ", " + y);
           MouseMoveThread thread = new MouseMoveThread(x, y, delay, duration, previousThread);
           previousThread = thread;
           thread.start();
           log("< mouseMove Robot");
           return null;
         }
       });
 }
 private void readPrimordialConfiguration() {
     if (!readPrimordialConfiguration) {
         synchronized (this) {
             if (!readPrimordialConfiguration) {
                 // If System.in/out/err are null, it's a good
                 // indication that we're still in the
                 // bootstrapping phase
                 if (System.out == null) {
                     return;
                 }
                 readPrimordialConfiguration = true;
                 try {
                     AccessController.doPrivileged(new PrivilegedExceptionAction() {
                             public Object run() throws Exception {
                                 readConfiguration();
                                 return null;
                             }
                         });
                 } catch (Exception ex) {
                     // System.err.println("Can't read logging configuration:");
                     // ex.printStackTrace();
                 }
             }
         }
     }
 }
 /**
  * @deprecated Prefer using methods taking a Reader rather than an InputStream to avoid wrong
  *     encoding issues.
  */
 public Class parseClass(final InputStream in, final String fileName)
     throws CompilationFailedException {
   // For generic input streams, provide a catch-all codebase of GroovyScript
   // Security for these classes can be administered via policy grants with
   // a codebase of file:groovy.script
   GroovyCodeSource gcs =
       AccessController.doPrivileged(
           new PrivilegedAction<GroovyCodeSource>() {
             public GroovyCodeSource run() {
               try {
                 String scriptText =
                     config.getSourceEncoding() != null
                         ? IOGroovyMethods.getText(in, config.getSourceEncoding())
                         : IOGroovyMethods.getText(in);
                 return new GroovyCodeSource(scriptText, fileName, "/groovy/script");
               } catch (IOException e) {
                 throw new RuntimeException(
                     "Impossible to read the content of the input stream for file named: "
                         + fileName,
                     e);
               }
             }
           });
   return parseClass(gcs);
 }
    public void componentShown(ComponentEvent evt) {
      // sets the security manager to fix a bug in liveconnect in Safari on Mac
      if (key != -1) {
        return;
      }
      window = (JSObject) JSObject.getWindow(applet());

      AccessController.doPrivileged(
          new PrivilegedAction() {
            public Object run() {
              log("> init Robot");
              try {
                SecurityManager oldsecurity = System.getSecurityManager();
                boolean isOpera = false;
                try {
                  isOpera = (System.getProperty("browser").equals("Opera.plugin"));
                } catch (Exception e) {
                }
                try {
                  securitymanager = oldsecurity;
                  securitymanager.checkTopLevelWindow(null);
                  // xdomain
                  if (charMap == null) {
                    if (!confirm(
                        "DOH has detected that the current Web page is attempting to access DOH, but belongs to a different domain than the one you agreed to let DOH automate. If you did not intend to start a new DOH test by visiting this Web page, press Cancel now and leave the Web page. Otherwise, press OK to trust this domain to automate DOH tests.")) {
                      stop();
                      return null;
                    }
                  }
                  log("Found old security manager");
                } catch (Exception e) {
                  e.printStackTrace();
                  log("Making new security manager");
                  securitymanager = new RobotSecurityManager(isOpera, oldsecurity);
                  securitymanager.checkTopLevelWindow(null);
                  System.setSecurityManager(securitymanager);
                }
                // instantiate the Robot
                robot = new Robot();
              } catch (Exception e) {
                log("Error calling _init_: " + e.getMessage());
                key = -2;
                e.printStackTrace();
              }
              log("< init Robot");
              return null;
            }
          });
      if (key == -2) {
        // applet not trusted
        // start the test without it
        window.eval("doh.robot._appletDead=true;doh.run();");
      } else {
        // now that the applet has really started, let doh know it's ok to use it
        log("_initRobot");
        dohrobot = (JSObject) window.eval("doh.robot");
        dohrobot.call("_initRobot", new Object[] {applet()});
      }
    }
Exemple #12
0
 static {
   String p = "sun.security.pkcs11.allowSingleThreadedModules";
   String s = AccessController.doPrivileged(new GetPropertyAction(p));
   if ("false".equalsIgnoreCase(s)) {
     staticAllowSingleThreadedModules = false;
   } else {
     staticAllowSingleThreadedModules = true;
   }
 }
 public void log(final String s) {
   AccessController.doPrivileged(
       new PrivilegedAction() {
         public Object run() {
           System.out.println((new Date()).toString() + ": " + s);
           return null;
         }
       });
 }
 private void alert(final String s) {
   AccessController.doPrivileged(
       new PrivilegedAction() {
         public Object run() {
           window.eval("top.alert(\"" + s + "\");");
           return null;
         }
       });
 }
 private boolean confirm(final String s) {
   return ((Boolean)
           AccessController.doPrivileged(
               new PrivilegedAction() {
                 public Object run() {
                   return ((Boolean) window.eval("top.confirm(\"" + s + "\");"));
                 }
               }))
       .booleanValue();
 }
 /**
  * creates a ClassCollector for a new compilation.
  *
  * @param unit the compilationUnit
  * @param su the SourceUnit
  * @return the ClassCollector
  */
 protected ClassCollector createCollector(CompilationUnit unit, SourceUnit su) {
   InnerLoader loader =
       AccessController.doPrivileged(
           new PrivilegedAction<InnerLoader>() {
             public InnerLoader run() {
               return new InnerLoader(GroovyClassLoader.this);
             }
           });
   return new ClassCollector(loader, unit, su);
 }
 /**
  * Parses the given text into a Java class capable of being run
  *
  * @param text the text of the script/class to parse
  * @param fileName the file name to use as the name of the class
  * @return the main class defined in the given script
  */
 public Class parseClass(final String text, final String fileName)
     throws CompilationFailedException {
   GroovyCodeSource gcs =
       AccessController.doPrivileged(
           new PrivilegedAction<GroovyCodeSource>() {
             public GroovyCodeSource run() {
               return new GroovyCodeSource(text, fileName, "/groovy/script");
             }
           });
   gcs.setCachable(false);
   return parseClass(gcs);
 }
 public static InputStream openStream(final URL url) throws IOException {
   try {
     return (InputStream)
         AccessController.doPrivileged(
             new PrivilegedExceptionAction() {
               public Object run() throws IOException {
                 return url.openStream();
               }
             });
   } catch (PrivilegedActionException e) {
     throw (IOException) e.getException();
   }
 }
 static {
   // doPrivileged here because there are multiple
   // things in initialize that might require privs.
   // (the FileInputStream call and the File.exists call,
   // the securityPropFile call, etc)
   AccessController.doPrivileged(
       new PrivilegedAction() {
         public Object run() {
           initialize();
           return null;
         }
       });
 }
 public void wheelMouse(double sec, final int amount, final int delay, final int duration) {
   // called by doh.robot.mouseWheel
   // see it for details
   if (!isSecure(sec)) return;
   AccessController.doPrivileged(
       new PrivilegedAction() {
         public Object run() {
           MouseWheelThread thread = new MouseWheelThread(amount, delay, duration, previousThread);
           previousThread = thread;
           thread.start();
           return null;
         }
       });
 }
 public static ClassLoader getContextClassLoader() {
   return (ClassLoader)
       AccessController.doPrivileged(
           new PrivilegedAction() {
             public Object run() {
               ClassLoader cl = null;
               try {
                 cl = Thread.currentThread().getContextClassLoader();
               } catch (SecurityException ex) {
               }
               return cl;
             }
           });
 }
 public static InputStream getResourceAsStream(final Class c, final String name)
     throws IOException {
   try {
     return (InputStream)
         AccessController.doPrivileged(
             new PrivilegedExceptionAction() {
               public Object run() throws IOException {
                 return c.getResourceAsStream(name);
               }
             });
   } catch (PrivilegedActionException e) {
     throw (IOException) e.getException();
   }
 }
Exemple #23
0
 static {
   AccessController.doPrivileged(
       new PrivilegedAction<Void>() {
         public Void run() {
           System.loadLibrary("osx");
           return null;
         }
       });
   try {
     PKCS8ShroudedKeyBag_OID = new ObjectIdentifier(keyBag);
     pbeWithSHAAnd3KeyTripleDESCBC_OID = new ObjectIdentifier(pbeWithSHAAnd3KeyTripleDESCBC);
   } catch (IOException ioe) {
     // should not happen
   }
 }
  public SunRsaSign() {
    super("SunRsaSign", 1.7d, "Sun RSA signature provider");

    // if there is no security manager installed, put directly into
    // the provider. Otherwise, create a temporary map and use a
    // doPrivileged() call at the end to transfer the contents
    if (System.getSecurityManager() == null) {
      SunRsaSignEntries.putEntries(this);
    } else {
      // use LinkedHashMap to preserve the order of the PRNGs
      Map<Object, Object> map = new HashMap<Object, Object>();
      SunRsaSignEntries.putEntries(map);
      AccessController.doPrivileged(new PutAllAction(this, map));
    }
  }
  static {
    try {
      AccessController.doPrivileged(
          new PrivilegedExceptionAction<Object>() {
            public Object run() throws Exception {
              setupJurisdictionPolicies();
              return null;
            }
          });

      isRestricted = defaultPolicy.implies(CryptoAllPermission.INSTANCE) ? false : true;
    } catch (Exception e) {
      throw new SecurityException("Can not initialize cryptographic mechanism", e);
    }
  }
 public URL getResource(final String name) {
   try {
     return (URL)
         AccessController.doPrivileged(
             new PrivilegedExceptionAction<Object>() {
               public Object run() throws Exception {
                 return httpContext.getResource(name);
               }
             },
             acc);
   } catch (PrivilegedActionException e) {
     log(e.getException().getMessage(), e.getException());
   }
   return null;
 }
    // Private method to set a parent on a logger.
    // If necessary, we raise privilege before doing the setParent call.
    private static void doSetParent(final Logger logger, final Logger parent) {
	SecurityManager sm = System.getSecurityManager();
	if (sm == null) {
	    // There is no security manager, so things are easy.
	    logger.setParent(parent);
	    return;
	} 
	// There is a security manager.  Raise privilege before
	// calling setParent.
	AccessController.doPrivileged(new PrivilegedAction() {
	    public Object run() {
		logger.setParent(parent);
		return null;
	    }});
    }
 public URL loadGroovySource(final String filename) throws MalformedURLException {
   return AccessController.doPrivileged(
       new PrivilegedAction<URL>() {
         public URL run() {
           for (String extension : config.getScriptExtensions()) {
             try {
               URL ret = getSourceFile(filename, extension);
               if (ret != null) return ret;
             } catch (Throwable t) { //
             }
           }
           return null;
         }
       });
 }
 public static Field makeAccessible(Class<?> target, String fieldName) {
   try {
     final Field field = target.getDeclaredField(fieldName);
     return (Field)
         AccessController.doPrivileged(
             new PrivilegedExceptionAction<Object>() {
               public Object run() throws IllegalAccessException, InvocationTargetException {
                 if (!field.isAccessible()) field.setAccessible(true);
                 return field;
               }
             });
   } catch (NoSuchFieldException | PrivilegedActionException e) {
     System.out.print("");
   } // keep quiet IError.printStackTrace(e); }
   return null;
 }
 /** Invoke a method on an object using reflection. */
 public static Object invoke(final Object target, final Method method, final Object... args) {
   try {
     return AccessController.doPrivileged(
         new PrivilegedExceptionAction<Object>() {
           public Object run() throws IllegalAccessException, InvocationTargetException {
             if (!method.isAccessible())
               method.setAccessible(
                   true); // Say please - else invoke() will fail if method is protected
             return method.invoke(target, args);
           }
         });
   } catch (PrivilegedActionException e) {
     e.printStackTrace();
   }
   return null;
 }