/** * 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; }
/** * 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; }
@Override public boolean hasPermission(Object permission) { Generation current = (Generation) module.getCurrentRevision().getRevisionInfo(); ProtectionDomain domain = current.getDomain(); if (domain != null) { if (permission instanceof Permission) { SecurityManager sm = System.getSecurityManager(); if (sm instanceof EquinoxSecurityManager) { /* * If the FrameworkSecurityManager is active, we need to do checks the "right" way. * We can exploit our knowledge that the security context of FrameworkSecurityManager * is an AccessControlContext to invoke it properly with the ProtectionDomain. */ AccessControlContext acc = new AccessControlContext(new ProtectionDomain[] {domain}); try { sm.checkPermission((Permission) permission, acc); return true; } catch (Exception e) { return false; } } return domain.implies((Permission) permission); } return false; } return true; }
/** Check for permission to get a service. */ private <A> void checkAdaptPermission(Class<A> adapterType) { SecurityManager sm = System.getSecurityManager(); if (sm == null) { return; } sm.checkPermission(new AdaptPermission(adapterType.getName(), this, AdaptPermission.ADAPT)); }
/** @param args */ public static void main(String[] args) { if (args.length < 1) { System.out.println("Uso echo <host>"); System.exit(1); } if (System.getSecurityManager() == null) { System.setSecurityManager(new SecurityManager()); } BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); PrintWriter stdOut = new PrintWriter(System.out); String input, output; try { EchoInt eo = (EchoInt) Naming.lookup("//" + args[0] + "/miEcho"); stdOut.print("> "); stdOut.flush(); while ((input = stdIn.readLine()) != null) { output = eo.echo(input); stdOut.println(output); stdOut.print("> "); stdOut.flush(); } } catch (Exception e) { System.err.println("RMI Echo Client error: " + e.getLocalizedMessage()); } }
/** * Check that the current context is trusted to modify the logging * configuration. This requires LoggingPermission("control"). * <p> * If the check fails we throw a SecurityException, otherwise * we return normally. * * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void checkAccess() throws SecurityException { SecurityManager sm = System.getSecurityManager(); if (sm == null) { return; } sm.checkPermission(ourPermission); }
/** * Used to indicate whether of not we are running in an environment where GUI interaction is * available. * * <p>Note that this method is security checked and is not available to (for example) untrusted * applets. More specifically, if there is a security manager, its <code>checkPropertiesAccess * </code> method is called. This could result in a SecurityException. * * @param isGuiAvailable True if GUI interaction is available. * @exception SecurityException if a security manager exists and its <code>checkPropertiesAccess * </code> method doesn't allow setting of system properties. * @see SecurityManager#checkPropertiesAccess */ public static void setGuiAvailable(boolean isGuiAvailable) throws SecurityException { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPropertiesAccess(); } guiAvailable = isGuiAvailable; }
/** * Sets the default locale for this instance of the Java Virtual Machine. This does not affect the * host locale. * * <p>If there is a security manager, its <code>checkPermission</code> method is called with a * <code>PropertyPermission("user.language", "write")</code> permission before the default locale * is changed. * * <p>The Java Virtual Machine sets the default locale during startup based on the host * environment. It is used by many locale-sensitive methods if no locale is explicitly specified. * * <p>Since changing the default locale may affect many different areas of functionality, this * method should only be used if the caller is prepared to reinitialize locale-sensitive code * running within the same Java Virtual Machine, such as the user interface. * * @throws SecurityException if a security manager exists and its <code>checkPermission</code> * method doesn't allow the operation. * @throws NullPointerException if <code>newLocale</code> is null * @param newLocale the new default locale * @see SecurityManager#checkPermission * @see java.util.PropertyPermission */ public static synchronized void setDefault(Locale newLocale) { if (newLocale == null) throw new NullPointerException("Can't set default locale to NULL"); SecurityManager sm = System.getSecurityManager(); if (sm != null) sm.checkPermission(new PropertyPermission("user.language", "write")); defaultLocale = newLocale; }
/** * Used to indicate whether of not we are running in an application builder environment. * * <p>Note that this method is security checked and is not available to (for example) untrusted * applets. More specifically, if there is a security manager, its <code>checkPropertiesAccess * </code> method is called. This could result in a SecurityException. * * @param isDesignTime True if we're in an application builder tool. * @exception SecurityException if a security manager exists and its <code>checkPropertiesAccess * </code> method doesn't allow setting of system properties. * @see SecurityManager#checkPropertiesAccess */ public static void setDesignTime(boolean isDesignTime) throws SecurityException { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPropertiesAccess(); } designTime = isDesignTime; }
private static void permissionCheck() { SecurityManager sec = System.getSecurityManager(); if (sec != null) { sec.checkPermission(new RuntimePermission("useKeychainStore")); } }
private JarFile getCachedJarFile(URL url) { JarFile result = (JarFile) fileCache.get(url); /* if the JAR file is cached, the permission will always be there */ if (result != null) { Permission perm = getPermission(result); if (perm != null) { SecurityManager sm = System.getSecurityManager(); if (sm != null) { try { sm.checkPermission(perm); } catch (SecurityException se) { // fallback to checkRead/checkConnect for pre 1.2 // security managers if ((perm instanceof java.io.FilePermission) && perm.getActions().indexOf("read") != -1) { sm.checkRead(perm.getName()); } else if ((perm instanceof java.net.SocketPermission) && perm.getActions().indexOf("connect") != -1) { sm.checkConnect(url.getHost(), url.getPort()); } else { throw se; } } } } } return result; }
private static EquinoxSecurityManager getSupportedSystemSecurityManager() { try { EquinoxSecurityManager equinoxManager = (EquinoxSecurityManager) System.getSecurityManager(); return equinoxManager != null && equinoxManager.inCheckPermission() ? equinoxManager : null; } catch (ClassCastException e) { return null; } }
/** * Gets a security property value. * * <p>First, if there is a security manager, its <code>checkPermission</code> method is called * with a <code>java.security.SecurityPermission("getProperty."+key)</code> permission to see if * it's ok to retrieve the specified security property value.. * * @param key the key of the property being retrieved. * @return the value of the security property corresponding to key. * @throws SecurityException if a security manager exists and its <code>{@link * java.lang.SecurityManager#checkPermission}</code> method denies access to retrieve the * specified security property value * @throws NullPointerException is key is null * @see #setProperty * @see java.security.SecurityPermission */ public static String getProperty(String key) { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(new SecurityPermission("getProperty." + key)); } String name = props.getProperty(key); if (name != null) name = name.trim(); // could be a class name with trailing ws return name; }
private Descrittore contatta_server(String nome) { // variabili per l'RMI RMIServerInt serv = null; // server Descrittore descr_rit = null; // descrittore ritornato if (nome == null) { System.out.println("## contatta_server di Download ha ricevuto parametro null ! "); return null; } System.out.println("@ provo a contattare il server RMI "); // ################ RMI ################ if (System.getSecurityManager() == null) { System.setSecurityManager(new SecurityManager()); } Object o = null; try { // o = Naming.lookup("rmi://192.168.0.10:1099/srmi"); Registry registry = LocateRegistry.getRegistry(server.getHostAddress()); o = registry.lookup("srmi"); } catch (RemoteException e) { System.out.println("## Problemi nell'RMI di Download - contatta_server di " + nome); e.printStackTrace(); } catch (NotBoundException e) { System.out.println("## Problemi nell'RMI di Download - contatta_server di " + nome); e.printStackTrace(); } if (o == null) { System.out.println( "## l'RMI di Download - contatta_server di " + nome + " ha ritornato l'oggetto o null"); return null; } serv = (RMIServerInt) o; try { descr_rit = serv.lookup(nome, InetAddress.getLocalHost()); } catch (RemoteException e) { e.printStackTrace(); System.out.println("## Problemi con Lookup di " + nome); return null; } catch (UnknownHostException e) { e.printStackTrace(); System.out.println("## Problemi con Lookup di " + nome); return null; } return descr_rit; }
/** * Sets the <code>SocketImplFactory</code>. This may be done only once per virtual machine. * Subsequent attempts will generate a <code>SocketException</code>. Note that a <code> * SecurityManager</code> check is made prior to setting the factory. If insufficient privileges * exist to set the factory, then an <code>IOException</code> will be thrown. * * @exception SecurityException If the <code>SecurityManager</code> does not allow this operation. * @exception SocketException If the SocketImplFactory is already defined * @exception IOException If any other error occurs */ public static synchronized void setSocketImplFactory(SocketImplFactory fac) throws IOException { // See if already set if (factory != null) throw new SocketException("SocketImplFactory already defined"); // Check permissions SecurityManager sm = System.getSecurityManager(); if (sm != null) sm.checkSetFactory(); if (fac == null) throw new SocketException("SocketImplFactory cannot be null"); factory = fac; }
public static boolean checkSecurity() { SecurityManager security = System.getSecurityManager(); if (security != null) { try { security.checkPropertyAccess("user.dir"); security.checkPropertyAccess("file.separator"); } catch (SecurityException e) { System.out.println("SecurityManager restricts session recording."); return false; } } return true; }
// 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; }}); }
/** * Constructor. The properties specifies how the connector should be configured. The properties to * include are; * * <p>'network_password' -> (String) the network password 'output_net_interface' -> * (NetworkInterface) the output network interface to use for IPv6 scope. */ TCPNetworkConnector(TCPConnectorValues properties) { // Security check, SecurityManager security = System.getSecurityManager(); if (security != null) security.checkPermission(MckoiNetworkPermission.CREATE_TCP_CONNECTOR); connection_pool = new HashMap<>(); this.password = properties.getNetworkPassword(); this.network_interface = properties.getOutputNetworkInterface(); // This thread kills connections that have timed out. background_thread = new ConnectionDestroyThread(log, connection_pool); background_thread.setDaemon(true); background_thread.start(); }
// security check to see whether the caller can perform attach private void checkProcessAttach(int pid) { SecurityManager sm = System.getSecurityManager(); if (sm != null) { String os = System.getProperty("os.name"); try { // Whether the caller can perform link against SA native library? checkNativeLink(sm, os); if (os.equals("SunOS") || os.equals("Linux")) { // Whether the caller can read /proc/<pid> file? sm.checkRead("/proc/" + pid); } } catch (SecurityException se) { throw new SecurityException("permission denied to attach to " + pid); } } }
/** * This constructor is where the real work takes place. Connect to the specified address and port. * Use default local values if not specified, otherwise use the local host and port passed in. * Create as stream or datagram based on "stream" argument. * * <p> * * @param raddr The remote address to connect to * @param rport The remote port to connect to * @param laddr The local address to connect to * @param lport The local port to connect to * @param stream true for a stream socket, false for a datagram socket * @exception IOException If an error occurs * @exception SecurityException If a security manager exists and its checkConnect method doesn't * allow the operation */ private Socket(InetAddress raddr, int rport, InetAddress laddr, int lport, boolean stream) throws IOException { this(); this.inputShutdown = false; this.outputShutdown = false; if (impl == null) throw new IOException("Cannot initialize Socket implementation"); SecurityManager sm = System.getSecurityManager(); if (sm != null) sm.checkConnect(raddr.getHostName(), rport); impl.create(stream); // FIXME: JCL p. 1586 says if localPort is unspecified, bind to any port, // i.e. '0' and if localAddr is unspecified, use getLocalAddress() as // that default. JDK 1.2 doc infers not to do a bind. if (laddr != null) impl.bind(laddr, lport); if (raddr != null) impl.connect(raddr, rport); }
/** * Returns the local address to which this socket is bound. If this socket is not connected, then * <code>null</code> is returned. * * @return The local address * @since 1.1 */ public InetAddress getLocalAddress() { if (impl == null) return null; InetAddress addr = null; try { addr = (InetAddress) impl.getOption(SocketOptions.SO_BINDADDR); } catch (SocketException e) { // (hopefully) shouldn't happen // throw new java.lang.InternalError // ("Error in PlainSocketImpl.getOption"); return null; } // FIXME: According to libgcj, checkConnect() is supposed to be called // before performing this operation. Problems: 1) We don't have the // addr until after we do it, so we do a post check. 2). The docs I // see don't require this in the Socket case, only DatagramSocket, but // we'll assume they mean both. SecurityManager sm = System.getSecurityManager(); if (sm != null) sm.checkConnect(addr.getHostName(), getLocalPort()); return addr; }
/** Utility routine for setting the context class loader. Returns previous class loader. */ public static ClassLoader setContextClassLoader(ClassLoader newClassLoader) { // Can only reference final local variables from dopriveleged block final ClassLoader classLoaderToSet = newClassLoader; final Thread currentThread = Thread.currentThread(); ClassLoader originalClassLoader = currentThread.getContextClassLoader(); if (classLoaderToSet != originalClassLoader) { if (System.getSecurityManager() == null) { currentThread.setContextClassLoader(classLoaderToSet); } else { java.security.AccessController.doPrivileged( new java.security.PrivilegedAction() { public java.lang.Object run() { currentThread.setContextClassLoader(classLoaderToSet); return null; } }); } } return originalClassLoader; }
/** * loads a class from a file or a parent classloader. * * @param name of the class to be loaded * @param lookupScriptFiles if false no lookup at files is done at all * @param preferClassOverScript if true the file lookup is only done if there is no class * @param resolve see {@link java.lang.ClassLoader#loadClass(java.lang.String, boolean)} * @return the class found or the class created from a file lookup * @throws ClassNotFoundException if the class could not be found * @throws CompilationFailedException if the source file could not be compiled */ public Class loadClass( final String name, boolean lookupScriptFiles, boolean preferClassOverScript, boolean resolve) throws ClassNotFoundException, CompilationFailedException { // look into cache Class cls = getClassCacheEntry(name); // enable recompilation? boolean recompile = isRecompilable(cls); if (!recompile) return cls; // try parent loader ClassNotFoundException last = null; try { Class parentClassLoaderClass = super.loadClass(name, resolve); // always return if the parent loader was successful if (cls != parentClassLoaderClass) return parentClassLoaderClass; } catch (ClassNotFoundException cnfe) { last = cnfe; } catch (NoClassDefFoundError ncdfe) { if (ncdfe.getMessage().indexOf("wrong name") > 0) { last = new ClassNotFoundException(name); } else { throw ncdfe; } } // check security manager SecurityManager sm = System.getSecurityManager(); if (sm != null) { String className = name.replace('/', '.'); int i = className.lastIndexOf('.'); // no checks on the sun.reflect classes for reflection speed-up // in particular ConstructorAccessorImpl, MethodAccessorImpl, FieldAccessorImpl and // SerializationConstructorAccessorImpl // which are generated at runtime by the JDK if (i != -1 && !className.startsWith("sun.reflect.")) { sm.checkPackageAccess(className.substring(0, i)); } } // prefer class if no recompilation if (cls != null && preferClassOverScript) return cls; // at this point the loading from a parent loader failed // and we want to recompile if needed. if (lookupScriptFiles) { // try groovy file try { // check if recompilation already happened. final Class classCacheEntry = getClassCacheEntry(name); if (classCacheEntry != cls) return classCacheEntry; URL source = resourceLoader.loadGroovySource(name); // if recompilation fails, we want cls==null Class oldClass = cls; cls = null; cls = recompile(source, name, oldClass); } catch (IOException ioe) { last = new ClassNotFoundException("IOException while opening groovy source: " + name, ioe); } finally { if (cls == null) { removeClassCacheEntry(name); } else { setClassCacheEntry(cls); } } } if (cls == null) { // no class found, there should have been an exception before now if (last == null) throw new AssertionError(true); throw last; } return cls; }
public static void main(String args[]) { sameGroup = true; RMID rmid = null; System.err.println("\nRegression test for bug/rfe 4179055\n"); try { TestLibrary.suggestSecurityManager("java.lang.SecurityManager"); registry = java.rmi.registry.LocateRegistry.createRegistry(TestLibrary.REGISTRY_PORT); // must run with java.lang.SecurityManager or the test // result will be nullified if running with a build where // 4180392 has not been fixed. String smClassName = System.getSecurityManager().getClass().getName(); if (!smClassName.equals("java.lang.SecurityManager")) { TestLibrary.bomb("Test must run with java.lang.SecurityManager"); } // start an rmid. RMID.removeLog(); rmid = RMID.createRMID(); rmid.start(); // rmid.addOptions(new String[] {"-C-Djava.rmi.server.logCalls=true"}); // Ensure that activation groups run with the correct // security manager. // Properties p = new Properties(); p.put("java.security.policy", TestParams.defaultGroupPolicy); p.put("java.security.manager", "java.lang.SecurityManager"); // This action causes the following classes to be created // in this VM (RMI must permit the creation of these classes): // // sun.rmi.server.Activation$ActivationSystemImpl_Stub // sun.rmi.server.Activation$ActivationMonitorImpl_Stub // System.err.println("Create activation group, in a new VM"); ActivationGroupDesc groupDesc = new ActivationGroupDesc(p, null); ActivationSystem system = ActivationGroup.getSystem(); ActivationGroupID groupID = system.registerGroup(groupDesc); System.err.println("register activatable"); // Fix for: 4271615: make sure activation group runs in a new VM ActivationDesc desc = new ActivationDesc(groupID, "StubClassesPermitted", null, null); canCreateStubs = (CanCreateStubs) Activatable.register(desc); // ensure registry stub can be passed in a remote call System.err.println("getting the registry"); registry = canCreateStubs.getRegistry(); // make sure a client cant load just any sun.* class, just // as a sanity check, try to create a class we are not // allowed to access but which was passed in a remote call try { System.err.println("accessing forbidden class"); Object secureRandom = canCreateStubs.getForbiddenClass(); TestLibrary.bomb( "test allowed to access forbidden class," + " sun.security.provider.SecureRandom"); } catch (java.security.AccessControlException e) { // Make sure we received a *local* AccessControlException ByteArrayOutputStream bout = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(bout); e.printStackTrace(ps); ps.flush(); String trace = new String(bout.toByteArray()); if ((trace.indexOf("exceptionReceivedFromServer") >= 0) || trace.equals("")) { throw e; } System.err.println("received expected local access control exception"); } // make sure that an ActivationGroupID can be passed in a // remote call; this is slightly more inclusive than // just passing a reference to the activation system System.err.println("returning group desc"); canCreateStubs.returnGroupID(); // Clean up object System.err.println("Deactivate object via method call"); canCreateStubs.shutdown(); System.err.println("\nsuccess: StubClassesPermitted test passed "); } catch (Exception e) { TestLibrary.bomb("\nfailure: unexpected exception ", e); } finally { try { Thread.sleep(4000); } catch (InterruptedException e) { } canCreateStubs = null; ActivationLibrary.rmidCleanup(rmid); System.err.println("rmid shut down"); } }
void checkPermission() { SecurityManager sm = System.getSecurityManager(); if (sm != null) sm.checkPermission(controlPermission); }
private static void check(String directive) { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkSecurityAccess(directive); } }
private static void checkAllPermission() { SecurityManager sm = System.getSecurityManager(); if (sm != null) sm.checkPermission(new AllPermission()); }