@Override public DatagramChannel bind(SocketAddress local) throws IOException { synchronized (readLock) { synchronized (writeLock) { synchronized (stateLock) { ensureOpen(); if (localAddress != null) throw new AlreadyBoundException(); InetSocketAddress isa; if (local == null) { // only Inet4Address allowed with IPv4 socket if (family == StandardProtocolFamily.INET) { isa = new InetSocketAddress(InetAddress.getByName("0.0.0.0"), 0); } else { isa = new InetSocketAddress(0); } } else { isa = Net.checkAddress(local); // only Inet4Address allowed with IPv4 socket if (family == StandardProtocolFamily.INET) { InetAddress addr = isa.getAddress(); if (!(addr instanceof Inet4Address)) throw new UnsupportedAddressTypeException(); } } SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkListen(isa.getPort()); } Net.bind(family, fd, isa.getAddress(), isa.getPort()); localAddress = Net.localAddress(fd); } } } return this; }
private static void permissionCheck() { SecurityManager sec = System.getSecurityManager(); if (sec != null) { sec.checkPermission(new RuntimePermission("useKeychainStore")); } }
/** * 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); }
@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; }
public static void main(String[] args) { String host = args[0]; int port = Integer.parseInt(args[1]); long id = Long.parseLong(args[2]); String character = args[3]; long actorId = Long.parseLong(args[4]); // Install an RMISecurityManager, if there is not a // SecurityManager already installed if (System.getSecurityManager() == null) { System.setSecurityManager(new RMISecurityManager()); } String name = "rmi://" + host + ":" + port + "/MovieDatabase"; try { MovieDatabase db = (MovieDatabase) Naming.lookup(name); db.noteCharacter(id, character, actorId); Movie movie = db.getMovie(id); out.println(movie.getTitle()); for (Map.Entry entry : movie.getCharacters().entrySet()) { out.println(" " + entry.getKey() + "\t" + entry.getValue()); } } catch (RemoteException | NotBoundException | MalformedURLException ex) { ex.printStackTrace(System.err); } }
public DatagramChannel connect(SocketAddress sa) throws IOException { int localPort = 0; synchronized (readLock) { synchronized (writeLock) { synchronized (stateLock) { ensureOpenAndUnconnected(); InetSocketAddress isa = Net.checkAddress(sa); SecurityManager sm = System.getSecurityManager(); if (sm != null) sm.checkConnect(isa.getAddress().getHostAddress(), isa.getPort()); int n = Net.connect(family, fd, isa.getAddress(), isa.getPort()); if (n <= 0) throw new Error(); // Can't happen // Connection succeeded; disallow further invocation state = ST_CONNECTED; remoteAddress = sa; sender = isa; cachedSenderInetAddress = isa.getAddress(); cachedSenderPort = isa.getPort(); // set or refresh local address localAddress = Net.localAddress(fd); } } } return this; }
final void checkWriteExtended() { SecurityManager sm = System.getSecurityManager(); if (sm != null) { file.checkWrite(); sm.checkPermission(new RuntimePermission("accessUserInformation")); } }
/** 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)); }
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; } }
/** Permission checks to access file */ private void checkAccess(UnixPath file, boolean checkRead, boolean checkWrite) { SecurityManager sm = System.getSecurityManager(); if (sm != null) { if (checkRead) file.checkRead(); if (checkWrite) file.checkWrite(); sm.checkPermission(new RuntimePermission("accessUserInformation")); } }
/** * Retrieve the value of the named environment property. * * @param key The name of the requested property. * @return The value of the requested property, or <code>null</code> if the property is undefined. */ public String getProperty(String key) { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPropertyAccess(key); } return (framework.getProperty(key)); }
/** * 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 static ClassLoader getClassLoader(final Class clazz) { if (System.getSecurityManager() == null) return clazz.getClassLoader(); return (ClassLoader) AccessController.doPrivileged( new PrivilegedAction() { public Object run() { return clazz.getClassLoader(); } }); }
/** * Returns the absolute path name of a native library. * * @param name the library name * @return the absolute path of the native library or null if not found */ public String findLibrary(final String name) { if (System.getSecurityManager() == null) return findLocalLibrary(name); return (String) AccessController.doPrivileged( new PrivilegedAction() { public Object run() { return findLocalLibrary(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; }
private ClassLoader getParentPrivileged(final BundleClassLoader bcl) { if (System.getSecurityManager() == null) return bcl.getParent(); return (ClassLoader) AccessController.doPrivileged( new PrivilegedAction() { public Object run() { return bcl.getParent(); } }); }
private BundleClassLoader createBCLPrevileged( final BundleProtectionDomain pd, final String[] cp) { // Create the classloader as previleged code if security manager is present. if (System.getSecurityManager() == null) return createBCL(pd, cp); return (BundleClassLoader) AccessController.doPrivileged( new PrivilegedAction() { public Object run() { return createBCL(pd, cp); } }); }
public SocketAddress receive(ByteBuffer dst) throws IOException { if (dst.isReadOnly()) throw new IllegalArgumentException("Read-only buffer"); if (dst == null) throw new NullPointerException(); synchronized (readLock) { ensureOpen(); // Socket was not bound before attempting receive if (localAddress() == null) bind(null); int n = 0; ByteBuffer bb = null; try { begin(); if (!isOpen()) return null; SecurityManager security = System.getSecurityManager(); readerThread = NativeThread.current(); if (isConnected() || (security == null)) { do { n = receive(fd, dst); } while ((n == IOStatus.INTERRUPTED) && isOpen()); if (n == IOStatus.UNAVAILABLE) return null; } else { bb = Util.getTemporaryDirectBuffer(dst.remaining()); for (; ; ) { do { n = receive(fd, bb); } while ((n == IOStatus.INTERRUPTED) && isOpen()); if (n == IOStatus.UNAVAILABLE) return null; InetSocketAddress isa = (InetSocketAddress) sender; try { security.checkAccept(isa.getAddress().getHostAddress(), isa.getPort()); } catch (SecurityException se) { // Ignore packet bb.clear(); n = 0; continue; } bb.flip(); dst.put(bb); break; } } return sender; } finally { if (bb != null) Util.releaseTemporaryDirectBuffer(bb); readerThread = 0; end((n > 0) || (n == IOStatus.UNAVAILABLE)); assert IOStatus.check(n); } } }
public int send(ByteBuffer src, SocketAddress target) throws IOException { if (src == null) throw new NullPointerException(); synchronized (writeLock) { ensureOpen(); InetSocketAddress isa = Net.checkAddress(target); InetAddress ia = isa.getAddress(); if (ia == null) throw new IOException("Target address not resolved"); synchronized (stateLock) { if (!isConnected()) { if (target == null) throw new NullPointerException(); SecurityManager sm = System.getSecurityManager(); if (sm != null) { if (ia.isMulticastAddress()) { sm.checkMulticast(ia); } else { sm.checkConnect(ia.getHostAddress(), isa.getPort()); } } } else { // Connected case; Check address then write if (!target.equals(remoteAddress)) { throw new IllegalArgumentException("Connected address not equal to target address"); } return write(src); } } int n = 0; try { begin(); if (!isOpen()) return 0; writerThread = NativeThread.current(); do { n = send(fd, src, isa); } while ((n == IOStatus.INTERRUPTED) && isOpen()); synchronized (stateLock) { if (isOpen() && (localAddress == null)) { localAddress = Net.localAddress(fd); } } return IOStatus.normalize(n); } finally { writerThread = 0; end((n > 0) || (n == IOStatus.UNAVAILABLE)); assert IOStatus.check(n); } } }
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)); } }
// 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; }}); }
@Override public DatagramChannel connect(SocketAddress sa) throws IOException { int localPort = 0; synchronized (readLock) { synchronized (writeLock) { synchronized (stateLock) { ensureOpenAndUnconnected(); InetSocketAddress isa = Net.checkAddress(sa); SecurityManager sm = System.getSecurityManager(); if (sm != null) sm.checkConnect(isa.getAddress().getHostAddress(), isa.getPort()); int n = Net.connect(family, fd, isa.getAddress(), isa.getPort()); if (n <= 0) throw new Error(); // Can't happen // Connection succeeded; disallow further invocation state = ST_CONNECTED; remoteAddress = isa; sender = isa; cachedSenderInetAddress = isa.getAddress(); cachedSenderPort = isa.getPort(); // set or refresh local address localAddress = Net.localAddress(fd); // flush any packets already received. boolean blocking = false; synchronized (blockingLock()) { try { blocking = isBlocking(); // remainder of each packet thrown away ByteBuffer tmpBuf = ByteBuffer.allocate(1); if (blocking) { configureBlocking(false); } do { tmpBuf.clear(); } while (receive(tmpBuf) != null); } finally { if (blocking) { configureBlocking(true); } } } } } } return this; }
// 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); } } }
public DatagramChannel disconnect() throws IOException { synchronized (readLock) { synchronized (writeLock) { synchronized (stateLock) { if (!isConnected() || !isOpen()) return this; InetSocketAddress isa = (InetSocketAddress) remoteAddress; SecurityManager sm = System.getSecurityManager(); if (sm != null) sm.checkConnect(isa.getAddress().getHostAddress(), isa.getPort()); disconnect0(fd); remoteAddress = null; state = ST_UNCONNECTED; // refresh local address localAddress = Net.localAddress(fd); } } } return this; }
@Override public ConfigBeanProxy compute(final Class<?> proxyType) throws ComputationErrorException { ClassLoader cl; if (System.getSecurityManager() != null) { cl = AccessController.doPrivileged( new PrivilegedAction<ClassLoader>() { @Override public ClassLoader run() { return proxyType.getClassLoader(); } }); } else { cl = proxyType.getClassLoader(); } ConfigBeanProxy retVal = (ConfigBeanProxy) Proxy.newProxyInstance(cl, new Class[] {proxyType}, dom); return retVal; }
/** * 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; }
private static void check(String directive) { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkSecurityAccess(directive); } }
DefaultThreadFactory() { SecurityManager s = System.getSecurityManager(); group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup(); namePrefix = "pool-" + poolNumber.getAndIncrement() + "-thread-"; }
private static void checkAllPermission() { SecurityManager sm = System.getSecurityManager(); if (sm != null) sm.checkPermission(new AllPermission()); }