/**
  * Obtain an ObjectOutputStream that allows serialization of a graph of objects. The objects can
  * be plain Serializable objects or can be converted into Serializable objects using the handler
  *
  * @throws IOException when the serialziation fails
  * @return an ObjectOutputStream that can be used to serialize objects
  */
 public ObjectOutputStream createObjectOutputStream(
     final OutputStream os,
     final boolean replaceObject,
     final NonSerializableObjectHandler handler)
     throws IOException {
   // Need privileged block here because EJBObjectOutputStream
   // does enableReplaceObject
   ObjectOutputStream oos = null;
   if (System.getSecurityManager() == null) {
     oos = new EJBObjectOutputStream(os, replaceObject, handler);
   } else {
     try {
       oos =
           (ObjectOutputStream)
               AccessController.doPrivileged(
                   new PrivilegedExceptionAction() {
                     public java.lang.Object run() throws Exception {
                       return new EJBObjectOutputStream(os, replaceObject, handler);
                     }
                   });
     } catch (PrivilegedActionException ex) {
       throw (IOException) ex.getException();
     }
   }
   return oos;
 }
  /**
   * Obtain an ObjectInputStream that allows de-serialization of a graph of objects.
   *
   * @throws IOException when the de-serialziation fails
   * @return an ObjectInputStream that can be used to deserialize objects
   */
  public ObjectInputStream createObjectInputStream(
      final InputStream is, final boolean resolveObject, final ClassLoader loader)
      throws Exception {
    ObjectInputStream ois = null;
    if (loader != null) {
      // Need privileged block here because EJBObjectInputStream
      // does enableResolveObject
      if (System.getSecurityManager() == null) {
        ois = new EJBObjectInputStream(is, loader, resolveObject);
      } else {
        try {
          ois =
              (ObjectInputStream)
                  AccessController.doPrivileged(
                      new PrivilegedExceptionAction() {
                        public java.lang.Object run() throws Exception {
                          return new EJBObjectInputStream(is, loader, resolveObject);
                        }
                      });
        } catch (PrivilegedActionException ex) {
          throw (IOException) ex.getException();
        }
      }
    } else {
      ois = new ObjectInputStream(is);
    }

    return ois;
  }
  /* this code is workaround for subtle bug/feature in JDK1.3.1 and 1.4,
  related to loading applets behind proxy */
  protected PermissionCollection getPermissions(CodeSource codesource) {
    PermissionCollection sysPerms = null;
    Policy policy =
        (Policy)
            AccessController.doPrivileged(
                new PrivilegedAction() {
                  public Object run() {
                    return Policy.getPolicy();
                  }
                });
    if (policy != null) sysPerms = policy.getPermissions(new CodeSource(null, null));
    else sysPerms = new Permissions();

    final PermissionCollection perms = sysPerms;
    if (base != null && base.getHost() != null)
      perms.add(new SocketPermission(base.getHost() + ":1-", "accept,connect,resolve"));
    URL url = codesource.getLocation();

    if (url.getProtocol().equals("file")) {

      String path = url.getFile().replace('/', File.separatorChar);

      if (!path.endsWith(File.separator)) {
        int endIndex = path.lastIndexOf(File.separatorChar);
        if (endIndex != -1) {
          path = path.substring(0, endIndex + 1) + "-";
          perms.add(new FilePermission(path, "read"));
        }
      }
      perms.add(new SocketPermission("localhost", "connect,accept"));
      AccessController.doPrivileged(
          new PrivilegedAction() {
            public Object run() {
              try {
                String host = InetAddress.getLocalHost().getHostName();
                perms.add(new SocketPermission(host, "connect,accept"));
              } catch (UnknownHostException uhe) {
              }
              return null;
            }
          });

      if (base.getProtocol().equals("file")) {
        String bpath = base.getFile().replace('/', File.separatorChar);
        if (bpath.endsWith(File.separator)) {
          bpath += "-";
        }
        perms.add(new FilePermission(bpath, "read"));
      }
    }
    // for (Enumeration e=perms.elements();e.hasMoreElements();)
    // System.err.println("p="+e.nextElement());
    return perms;
  }
 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;
         }
       });
 }
Exemplo n.º 5
0
 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();
                 }
             }
         }
     }
 }
Exemplo n.º 6
0
    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;
                }
            });
    }
Exemplo n.º 7
0
 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;
         }
       });
 }
Exemplo n.º 8
0
 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;
         }
       });
 }
Exemplo n.º 9
0
 /**
  * @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);
 }
Exemplo n.º 10
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();
 }
Exemplo n.º 11
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();
  }
Exemplo n.º 12
0
  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;
  }
Exemplo n.º 13
0
    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()});
      }
    }
Exemplo n.º 14
0
 static {
   String p = "sun.security.pkcs11.allowSingleThreadedModules";
   String s = AccessController.doPrivileged(new GetPropertyAction(p));
   if ("false".equalsIgnoreCase(s)) {
     staticAllowSingleThreadedModules = false;
   } else {
     staticAllowSingleThreadedModules = true;
   }
 }
Exemplo n.º 15
0
 public void log(final String s) {
   AccessController.doPrivileged(
       new PrivilegedAction() {
         public Object run() {
           System.out.println((new Date()).toString() + ": " + s);
           return null;
         }
       });
 }
Exemplo n.º 16
0
 private void alert(final String s) {
   AccessController.doPrivileged(
       new PrivilegedAction() {
         public Object run() {
           window.eval("top.alert(\"" + s + "\");");
           return null;
         }
       });
 }
Exemplo n.º 17
0
 /**
  * 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);
 }
Exemplo n.º 18
0
 private boolean confirm(final String s) {
   return ((Boolean)
           AccessController.doPrivileged(
               new PrivilegedAction() {
                 public Object run() {
                   return ((Boolean) window.eval("top.confirm(\"" + s + "\");"));
                 }
               }))
       .booleanValue();
 }
Exemplo n.º 19
0
 /**
  * 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();
   }
 }
Exemplo n.º 21
0
 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;
         }
       });
 }
Exemplo n.º 22
0
 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();
   }
 }
Exemplo n.º 25
0
 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;
         }
       });
 }
Exemplo n.º 26
0
  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);
    }
  }
Exemplo n.º 27
0
    // 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;
	    }});
    }
Exemplo n.º 28
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 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;
 }
Exemplo n.º 30
0
 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;
 }