Example #1
0
  private static void permissionCheck() {
    SecurityManager sec = System.getSecurityManager();

    if (sec != null) {
      sec.checkPermission(new RuntimePermission("useKeychainStore"));
    }
  }
  @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;
  }
 final void checkWriteExtended() {
   SecurityManager sm = System.getSecurityManager();
   if (sm != null) {
     file.checkWrite();
     sm.checkPermission(new RuntimePermission("accessUserInformation"));
   }
 }
Example #4
0
    /**
     * 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);
    }
 /** 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));
 }
 @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 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;
  }
  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;
  }
 /** 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));
  }
Example #11
0
 /**
  * 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;
 }
 protected void checkNativeLink(SecurityManager sm, String os) {
   if (os.equals("SunOS") || os.equals("Linux")) {
     // link "saproc" - SA native library on SunOS and Linux?
     sm.checkLink("saproc");
   } else if (os.startsWith("Windows")) {
     // link "sawindbg" - SA native library on Windows.
     sm.checkLink("sawindbg");
   } else {
     throw new RuntimeException(os + " is not yet supported");
   }
 }
  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 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);
     }
   }
 }
  @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;
  }
Example #16
0
 // 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;
  }
 public void checkPermission(Permission p) {
   // liveconnect SocketPermission resolve takes
   // FOREVER (like 6 seconds) in Safari
   // Java does like 50 of these on the first JS call
   // 6*50=300 seconds!
   // Opera freaks out though if we deny resolve
   if (isActive
       && !isOpera
       && java.net.SocketPermission.class.isInstance(p)
       && p.getActions().matches(".*resolve.*")) {
     throw new SecurityException(
         "DOH: liveconnect resolve locks up Safari. Denying resolve request.");
   } else {
     oldsecurity.checkPermission(p);
   }
 }
    public boolean checkTopLevelWindow(Object window) {
      // If our users temporarily accept our cert for a session,
      // then use the same session to browse to a malicious website also using our applet,
      // that website can automatically execute the applet.
      // To resolve this issue, RobotSecurityManager overrides checkTopLevelWindow
      // to check the JVM to see if there are other instances of the applet running on different
      // domains.
      // If there are, it prompts the user to confirm that they want to run the applet before
      // continuing.

      // null is not supposed to be allowed
      // so we allow it to distinguish our security manager.
      if (window == null) {
        isActive = !isActive;
        log("Active is now " + isActive);
      }
      return window == null ? true : oldsecurity.checkTopLevelWindow(window);
    }
  /**
   * 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;
  }
 void checkPermission() {
   SecurityManager sm = System.getSecurityManager();
   if (sm != null) sm.checkPermission(controlPermission);
 }
Example #22
0
 private static void check(String directive) {
   SecurityManager security = System.getSecurityManager();
   if (security != null) {
     security.checkSecurityAccess(directive);
   }
 }
Example #23
0
 DefaultThreadFactory() {
   SecurityManager s = System.getSecurityManager();
   group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
   namePrefix = "pool-" + poolNumber.getAndIncrement() + "-thread-";
 }
Example #24
0
 private static void checkAllPermission() {
   SecurityManager sm = System.getSecurityManager();
   if (sm != null) sm.checkPermission(new AllPermission());
 }
  /** Joins channel's socket to the given group/interface and optional source address. */
  private MembershipKey innerJoin(InetAddress group, NetworkInterface interf, InetAddress source)
      throws IOException {
    if (!group.isMulticastAddress())
      throw new IllegalArgumentException("Group not a multicast address");

    // check multicast address is compatible with this socket
    if (group instanceof Inet4Address) {
      if (family == StandardProtocolFamily.INET6 && !Net.canIPv6SocketJoinIPv4Group())
        throw new IllegalArgumentException("IPv6 socket cannot join IPv4 multicast group");
    } else if (group instanceof Inet6Address) {
      if (family != StandardProtocolFamily.INET6)
        throw new IllegalArgumentException("Only IPv6 sockets can join IPv6 multicast group");
    } else {
      throw new IllegalArgumentException("Address type not supported");
    }

    // check source address
    if (source != null) {
      if (source.isAnyLocalAddress())
        throw new IllegalArgumentException("Source address is a wildcard address");
      if (source.isMulticastAddress())
        throw new IllegalArgumentException("Source address is multicast address");
      if (source.getClass() != group.getClass())
        throw new IllegalArgumentException("Source address is different type to group");
    }

    SecurityManager sm = System.getSecurityManager();
    if (sm != null) sm.checkMulticast(group);

    synchronized (stateLock) {
      if (!isOpen()) throw new ClosedChannelException();

      // check the registry to see if we are already a member of the group
      if (registry == null) {
        registry = new MembershipRegistry();
      } else {
        // return existing membership key
        MembershipKey key = registry.checkMembership(group, interf, source);
        if (key != null) return key;
      }

      MembershipKeyImpl key;
      if ((family == StandardProtocolFamily.INET6)
          && ((group instanceof Inet6Address) || Net.canJoin6WithIPv4Group())) {
        int index = interf.getIndex();
        if (index == -1) throw new IOException("Network interface cannot be identified");

        // need multicast and source address as byte arrays
        byte[] groupAddress = Net.inet6AsByteArray(group);
        byte[] sourceAddress = (source == null) ? null : Net.inet6AsByteArray(source);

        // join the group
        int n = Net.join6(fd, groupAddress, index, sourceAddress);
        if (n == IOStatus.UNAVAILABLE) throw new UnsupportedOperationException();

        key =
            new MembershipKeyImpl.Type6(
                this, group, interf, source, groupAddress, index, sourceAddress);

      } else {
        // need IPv4 address to identify interface
        Inet4Address target = Net.anyInet4Address(interf);
        if (target == null) throw new IOException("Network interface not configured for IPv4");

        int groupAddress = Net.inet4AsInt(group);
        int targetAddress = Net.inet4AsInt(target);
        int sourceAddress = (source == null) ? 0 : Net.inet4AsInt(source);

        // join the group
        int n = Net.join4(fd, groupAddress, targetAddress, sourceAddress);
        if (n == IOStatus.UNAVAILABLE) throw new UnsupportedOperationException();

        key =
            new MembershipKeyImpl.Type4(
                this, group, interf, source, groupAddress, targetAddress, sourceAddress);
      }

      registry.add(key);
      return key;
    }
  }