java.security.PrivilegedExceptionAction Java Examples

The following examples show how to use java.security.PrivilegedExceptionAction. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CodeStore.java    From jdk8u_nashorn with GNU General Public License v2.0 6 votes vote down vote up
private static File checkDirectory(final String path, final ScriptEnvironment env, final boolean readOnly) throws IOException {
    try {
        return AccessController.doPrivileged(new PrivilegedExceptionAction<File>() {
            @Override
            public File run() throws IOException {
                final File dir = new File(path, getVersionDir(env)).getAbsoluteFile();
                if (readOnly) {
                    if (!dir.exists() || !dir.isDirectory()) {
                        throw new IOException("Not a directory: " + dir.getPath());
                    } else if (!dir.canRead()) {
                        throw new IOException("Directory not readable: " + dir.getPath());
                    }
                } else if (!dir.exists() && !dir.mkdirs()) {
                    throw new IOException("Could not create directory: " + dir.getPath());
                } else if (!dir.isDirectory()) {
                    throw new IOException("Not a directory: " + dir.getPath());
                } else if (!dir.canRead() || !dir.canWrite()) {
                    throw new IOException("Directory not readable or writable: " + dir.getPath());
                }
                return dir;
            }
        });
    } catch (final PrivilegedActionException e) {
        throw (IOException) e.getException();
    }
}
 
Example #2
Source File: Context.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public Context impersonate(final String someone) throws Exception {
    try {
        GSSCredential creds = Subject.doAs(s, new PrivilegedExceptionAction<GSSCredential>() {
            @Override
            public GSSCredential run() throws Exception {
                GSSManager m = GSSManager.getInstance();
                GSSName other = m.createName(someone, GSSName.NT_USER_NAME);
                if (Context.this.cred == null) {
                    Context.this.cred = m.createCredential(GSSCredential.INITIATE_ONLY);
                }
                return ((ExtendedGSSCredential)Context.this.cred).impersonate(other);
            }
        });
        Context out = new Context();
        out.s = s;
        out.cred = creds;
        out.name = name + " as " + out.cred.getName().toString();
        return out;
    } catch (PrivilegedActionException pae) {
        throw pae.getException();
    }
}
 
Example #3
Source File: ArrayNotificationBuffer.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
private void addNotificationListener(final ObjectName name,
                                     final NotificationListener listener,
                                     final NotificationFilter filter,
                                     final Object handback)
        throws Exception {
    try {
        AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
            public Void run() throws InstanceNotFoundException {
                mBeanServer.addNotificationListener(name,
                                                    listener,
                                                    filter,
                                                    handback);
                return null;
            }
        });
    } catch (Exception e) {
        throw extractException(e);
    }
}
 
Example #4
Source File: BaseFileObj.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public String readSymbolicLinkPath() throws IOException {
    final Path path = getNativePath();
    try {
        return AccessController.doPrivileged(
                new PrivilegedExceptionAction<String>() {

                    @Override
                    public String run() throws Exception {
                        Path target = Files.readSymbolicLink(path);
                        return target.toString();
                    }
                });
    } catch (PrivilegedActionException ex) {
        throw new IOException(ex);
    }
}
 
Example #5
Source File: RMIConnectionImpl.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
private ClassLoader getClassLoaderFor(final ObjectName name)
    throws InstanceNotFoundException {
    try {
        return (ClassLoader)
            AccessController.doPrivileged(
                new PrivilegedExceptionAction<Object>() {
                    public Object run() throws InstanceNotFoundException {
                        return mbeanServer.getClassLoaderFor(name);
                    }
                },
                withPermissions(new MBeanPermission("*", "getClassLoaderFor"))
        );
    } catch (PrivilegedActionException pe) {
        throw (InstanceNotFoundException) extractException(pe);
    }
}
 
Example #6
Source File: UNIXProcess.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
UNIXProcess(final byte[] prog,
            final byte[] argBlock, final int argc,
            final byte[] envBlock, final int envc,
            final byte[] dir,
            final int[] fds,
            final boolean redirectErrorStream)
        throws IOException {

    pid = forkAndExec(launchMechanism.ordinal() + 1,
                      helperpath,
                      prog,
                      argBlock, argc,
                      envBlock, envc,
                      dir,
                      fds,
                      redirectErrorStream);

    try {
        doPrivileged((PrivilegedExceptionAction<Void>) () -> {
            initStreams(fds);
            return null;
        });
    } catch (PrivilegedActionException ex) {
        throw (IOException) ex.getException();
    }
}
 
Example #7
Source File: TestWebDelegationToken.java    From big-c with Apache License 2.0 6 votes vote down vote up
public static <T> T doAsKerberosUser(String principal, String keytab,
    final Callable<T> callable) throws Exception {
  LoginContext loginContext = null;
  try {
    Set<Principal> principals = new HashSet<Principal>();
    principals.add(new KerberosPrincipal(principal));
    Subject subject = new Subject(false, principals, new HashSet<Object>(),
        new HashSet<Object>());
    loginContext = new LoginContext("", subject, null,
        new KerberosConfiguration(principal, keytab));
    loginContext.login();
    subject = loginContext.getSubject();
    return Subject.doAs(subject, new PrivilegedExceptionAction<T>() {
      @Override
      public T run() throws Exception {
        return callable.call();
      }
    });
  } catch (PrivilegedActionException ex) {
    throw ex.getException();
  } finally {
    if (loginContext != null) {
      loginContext.logout();
    }
  }
}
 
Example #8
Source File: RMIIIOPServerImpl.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
@Override
RMIConnection doNewClient(final Object credentials) throws IOException {
    if (callerACC == null) {
        throw new SecurityException("AccessControlContext cannot be null");
    }
    try {
        return AccessController.doPrivileged(
            new PrivilegedExceptionAction<RMIConnection>() {
                public RMIConnection run() throws IOException {
                    return superDoNewClient(credentials);
                }
        }, callerACC);
    } catch (PrivilegedActionException pae) {
        throw (IOException) pae.getCause();
    }
}
 
Example #9
Source File: MethodUtil.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
private static Method getTrampoline() {
    try {
        return AccessController.doPrivileged(
            new PrivilegedExceptionAction<Method>() {
                public Method run() throws Exception {
                    Class<?> t = getTrampolineClass();
                    Class<?>[] types = {
                        Method.class, Object.class, Object[].class
                    };
                    Method b = t.getDeclaredMethod("invoke", types);
                    b.setAccessible(true);
                    return b;
                }
            });
    } catch (Exception e) {
        throw new InternalError("bouncer cannot be found", e);
    }
}
 
Example #10
Source File: SocketAdaptor.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public OutputStream getOutputStream() throws IOException {
    if (!sc.isOpen())
        throw new SocketException("Socket is closed");
    if (!sc.isConnected())
        throw new SocketException("Socket is not connected");
    if (!sc.isOutputOpen())
        throw new SocketException("Socket output is shutdown");
    OutputStream os = null;
    try {
        os = AccessController.doPrivileged(
            new PrivilegedExceptionAction<OutputStream>() {
                public OutputStream run() throws IOException {
                    return Channels.newOutputStream(sc);
                }
            });
    } catch (java.security.PrivilegedActionException e) {
        throw (IOException)e.getException();
    }
    return os;
}
 
Example #11
Source File: IIOPProxyImpl.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Remote toStub(final Remote obj) throws NoSuchObjectException {
    if (System.getSecurityManager() == null) {
        return PortableRemoteObject.toStub(obj);
    } else {
        try {
            return AccessController.doPrivileged(new PrivilegedExceptionAction<Remote>() {

                @Override
                public Remote run() throws Exception {
                    return PortableRemoteObject.toStub(obj);
                }
            }, STUB_ACC);
        } catch (PrivilegedActionException e) {
            if (e.getException() instanceof NoSuchObjectException) {
                throw (NoSuchObjectException)e.getException();
            }
            throw new RuntimeException("Unexpected exception type", e.getException());
        }
    }
}
 
Example #12
Source File: SecurityActions.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
static Class<?> loadClass(final String name) throws PrivilegedActionException 
{
   return AccessController.doPrivileged(new PrivilegedExceptionAction<Class<?>>()
   {
      public Class<?> run() throws PrivilegedActionException
      {
         try
         {
            return getClass().getClassLoader().loadClass(name);
         }
         catch (Exception ignore)
         {
            try
            {
               return getContextClassLoader().loadClass(name);
            }
            catch (Exception e)
            {
               throw new PrivilegedActionException(e);
            }
         }
      }
   });
}
 
Example #13
Source File: ManagementFactory.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Registers a DynamicMBean.
 */
private static void addDynamicMBean(final MBeanServer mbs,
                                    final DynamicMBean dmbean,
                                    final ObjectName on) {
    try {
        AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
            @Override
            public Void run() throws InstanceAlreadyExistsException,
                                     MBeanRegistrationException,
                                     NotCompliantMBeanException {
                mbs.registerMBean(dmbean, on);
                return null;
            }
        });
    } catch (PrivilegedActionException e) {
        throw new RuntimeException(e.getException());
    }
}
 
Example #14
Source File: LOBStreamControl.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
static
// GemStone changes END
    private void deleteFile (StorageFile file) throws IOException {
        try {
            final StorageFile sf = file;
            AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
                public Object run() throws IOException {
                    sf.delete();
                    return null;
                }
            });
        } catch (PrivilegedActionException pae) {
            Exception e = pae.getException();
            if (e instanceof IOException)
                throw (IOException) e;
            if (e instanceof RuntimeException)
                throw (RuntimeException) e;
            throw Util.newIOException(e);
        }
    }
 
Example #15
Source File: ValueHandlerImpl.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Construct a built in implementation with priveleges.
 * Returning null indicates a non-built is specified.
 */
private IIOPOutputStream createOutputStreamBuiltIn(
    final String name
) throws Throwable {
    try {
        return AccessController.doPrivileged(
            new PrivilegedExceptionAction<IIOPOutputStream>() {
                public IIOPOutputStream run() throws IOException {
                    return createOutputStreamBuiltInNoPriv(name);
                }
            }
        );
    } catch (java.security.PrivilegedActionException exc) {
        throw exc.getCause();
    }
}
 
Example #16
Source File: ForkJoinPoolTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * A submitted privileged exception action runs to completion
 */
public void testSubmitPrivilegedExceptionAction() throws Exception {
    final Callable callable =
        Executors.callable(new PrivilegedExceptionAction() {
            public Object run() { return TEST_STRING; }});
    Runnable r = new CheckedRunnable() {
    public void realRun() throws Exception {
        ExecutorService e = new ForkJoinPool(1);
        try (PoolCleaner cleaner = cleaner(e)) {
            Future future = e.submit(callable);
            assertSame(TEST_STRING, future.get());
        }
    }};

    runWithPermissions(r, new RuntimePermission("modifyThread"));
}
 
Example #17
Source File: HttpURLConnection.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
@Override
public synchronized InputStream getInputStream() throws IOException {
    connecting = true;
    SocketPermission p = URLtoSocketPermission(this.url);

    if (p != null) {
        try {
            return AccessController.doPrivilegedWithCombiner(
                new PrivilegedExceptionAction<InputStream>() {
                    public InputStream run() throws IOException {
                        return getInputStream0();
                    }
                }, null, p
            );
        } catch (PrivilegedActionException e) {
            throw (IOException) e.getException();
        }
    } else {
        return getInputStream0();
    }
}
 
Example #18
Source File: DataTransferer.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
private ArrayList<String> castToFiles(final List files,
                                      final ProtectionDomain userProtectionDomain) throws IOException
{
    final ArrayList<String> fileList = new ArrayList<String>();
    try {
        AccessController.doPrivileged(new PrivilegedExceptionAction() {
            public Object run() throws IOException {
                for (Object fileObject : files)
                {
                    File file = castToFile(fileObject);
                    if (file != null &&
                        (null == System.getSecurityManager() ||
                        !(isFileInWebstartedCache(file) ||
                        isForbiddenToRead(file, userProtectionDomain))))
                    {
                        fileList.add(file.getCanonicalPath());
                    }
                }
                return null;
            }
        });
    } catch (PrivilegedActionException pae) {
        throw new IOException(pae.getMessage());
    }
    return fileList;
}
 
Example #19
Source File: RMIConnectionImpl.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
private ClassLoader getClassLoaderFor(final ObjectName name)
    throws InstanceNotFoundException {
    try {
        return (ClassLoader)
            AccessController.doPrivileged(
                new PrivilegedExceptionAction<Object>() {
                    public Object run() throws InstanceNotFoundException {
                        return mbeanServer.getClassLoaderFor(name);
                    }
                },
                withPermissions(new MBeanPermission("*", "getClassLoaderFor"))
        );
    } catch (PrivilegedActionException pe) {
        throw (InstanceNotFoundException) extractException(pe);
    }
}
 
Example #20
Source File: KrbCredSubKey.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {

        // We don't care about clock difference
        new FileOutputStream("krb5.conf").write(
                "[libdefaults]\nclockskew=999999999".getBytes());
        System.setProperty("java.security.krb5.conf", "krb5.conf");
        Config.refresh();

        Subject subj = new Subject();
        KerberosPrincipal kp = new KerberosPrincipal(princ);
        KerberosKey kk = new KerberosKey(
                kp, key, EncryptedData.ETYPE_AES128_CTS_HMAC_SHA1_96, 0);
        subj.getPrincipals().add(kp);
        subj.getPrivateCredentials().add(kk);

        Subject.doAs(subj, new PrivilegedExceptionAction() {
            public Object run() throws Exception {
                GSSManager man = GSSManager.getInstance();
                GSSContext ctxt = man.createContext(man.createCredential(
                        null, GSSCredential.INDEFINITE_LIFETIME,
                        GSSUtil.GSS_KRB5_MECH_OID, GSSCredential.ACCEPT_ONLY));
                return ctxt.acceptSecContext(token, 0, token.length);
            }
        });
    }
 
Example #21
Source File: ArrayNotificationBuffer.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private void addNotificationListener(final ObjectName name,
                                     final NotificationListener listener,
                                     final NotificationFilter filter,
                                     final Object handback)
        throws Exception {
    try {
        AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
            public Void run() throws InstanceNotFoundException {
                mBeanServer.addNotificationListener(name,
                                                    listener,
                                                    filter,
                                                    handback);
                return null;
            }
        });
    } catch (Exception e) {
        throw extractException(e);
    }
}
 
Example #22
Source File: HttpURLConnection.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
private String getHostAndPort(URL url) {
    String host = url.getHost();
    final String hostarg = host;
    try {
        // lookup hostname and use IP address if available
        host = AccessController.doPrivileged(
            new PrivilegedExceptionAction<String>() {
                public String run() throws IOException {
                        InetAddress addr = InetAddress.getByName(hostarg);
                        return addr.getHostAddress();
                }
            }
        );
    } catch (PrivilegedActionException e) {}
    int port = url.getPort();
    if (port == -1) {
        String scheme = url.getProtocol();
        if ("http".equals(scheme)) {
            return host + ":80";
        } else { // scheme must be https
            return host + ":443";
        }
    }
    return host + ":" + Integer.toString(port);
}
 
Example #23
Source File: TestPermissionSymlinks.java    From hadoop with Apache License 2.0 6 votes vote down vote up
private void doDeleteTargetParentAndTargetNotWritable() throws Exception {
  // Try a delete where the symlink parent dir is writable,
  // but the target's parent and target are not
  user.doAs(new PrivilegedExceptionAction<Object>() {
    @Override
    public Object run() throws IOException {
      FileContext myfc = FileContext.getFileContext(conf);
      myfc.delete(link, false);
      return null;
    }
  });
  // Make sure only the link was deleted
  assertTrue("Target should not have been deleted!",
      wrapper.exists(target));
  assertFalse("Link should have been deleted!",
      wrapper.exists(link));
}
 
Example #24
Source File: Utils.java    From deprecated-security-advanced-modules with Apache License 2.0 6 votes vote down vote up
public static byte[] jsonMapToByteArray(Map<String, Object> jsonAsMap) throws IOException {

        final SecurityManager sm = System.getSecurityManager();

        if (sm != null) {
            sm.checkPermission(new SpecialPermission());
        }

        try {
            return AccessController.doPrivileged(new PrivilegedExceptionAction<byte[]>() {
                @Override
                public byte[] run() throws Exception {
                    return internalMapper.writeValueAsBytes(jsonAsMap);
                }
            });
        } catch (final PrivilegedActionException e) {
            if (e.getCause() instanceof JsonProcessingException) {
                throw (JsonProcessingException) e.getCause();
            } else if (e.getCause() instanceof RuntimeException) {
                throw (RuntimeException) e.getCause();
            } else {
                throw new RuntimeException(e.getCause());
            }
        }
    }
 
Example #25
Source File: JobClient.java    From hadoop with Apache License 2.0 6 votes vote down vote up
/**
 * Gets all the jobs which were added to particular Job Queue
 * 
 * @param queueName name of the Job Queue
 * @return Array of jobs present in the job queue
 * @throws IOException
 */

public JobStatus[] getJobsFromQueue(final String queueName) throws IOException {
  try {
    QueueInfo queue = clientUgi.doAs(new PrivilegedExceptionAction<QueueInfo>() {
      @Override
      public QueueInfo run() throws IOException, InterruptedException {
        return cluster.getQueue(queueName);
      }
    });
    if (queue == null) {
      return null;
    }
    org.apache.hadoop.mapreduce.JobStatus[] stats = 
      queue.getJobStatuses();
    JobStatus[] ret = new JobStatus[stats.length];
    for (int i = 0 ; i < stats.length; i++ ) {
      ret[i] = JobStatus.downgrade(stats[i]);
    }
    return ret;
  } catch (InterruptedException ie) {
    throw new IOException(ie);
  }
}
 
Example #26
Source File: RMIIIOPServerImpl.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
@Override
RMIConnection doNewClient(final Object credentials) throws IOException {
    if (callerACC == null) {
        throw new SecurityException("AccessControlContext cannot be null");
    }
    try {
        return AccessController.doPrivileged(
            new PrivilegedExceptionAction<RMIConnection>() {
                public RMIConnection run() throws IOException {
                    return superDoNewClient(credentials);
                }
        }, callerACC);
    } catch (PrivilegedActionException pae) {
        throw (IOException) pae.getCause();
    }
}
 
Example #27
Source File: Utils.java    From deprecated-security-advanced-modules with Apache License 2.0 6 votes vote down vote up
public static void unbindAndCloseSilently(final Connection connection) {
    if (connection == null) {
        return;
    }

    final SecurityManager sm = System.getSecurityManager();

    if (sm != null) {
        sm.checkPermission(new SpecialPermission());
    }

    try {
        AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
            @Override
            public Object run() throws Exception {
                connection.close();
                return null;
            }
        });
    } catch (PrivilegedActionException e) {
        // ignore
    }
}
 
Example #28
Source File: BaseFileObj.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public FileObject readSymbolicLink() throws IOException {
    final Path path = getNativePath();
    try {
        return AccessController.doPrivileged(
                new PrivilegedExceptionAction<FileObject>() {

                    @Override
                    public FileObject run() throws Exception {
                        Path target = Files.readSymbolicLink(path);
                        Path absoluteTarget = target.isAbsolute()
                            ? target
                            : path.getParent().resolve(target);
                        File file = absoluteTarget.toFile();
                        File normFile = FileUtil.normalizeFile(file);
                        return FileBasedFileSystem.getFileObject(normFile);
                    }
                });
    } catch (PrivilegedActionException ex) {
        throw new IOException(ex);
    }
}
 
Example #29
Source File: ArrayNotificationBuffer.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
private static boolean isInstanceOf(final MBeanServer mbs,
                                    final ObjectName name,
                                    final String className) {
    PrivilegedExceptionAction<Boolean> act =
        new PrivilegedExceptionAction<Boolean>() {
            public Boolean run() throws InstanceNotFoundException {
                return mbs.isInstanceOf(name, className);
            }
        };
    try {
        return AccessController.doPrivileged(act);
    } catch (Exception e) {
        logger.fine("isInstanceOf", "failed: " + e);
        logger.debug("isInstanceOf", e);
        return false;
    }
}
 
Example #30
Source File: Socket.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns an output stream for this socket.
 *
 * <p> If this socket has an associated channel then the resulting output
 * stream delegates all of its operations to the channel.  If the channel
 * is in non-blocking mode then the output stream's {@code write}
 * operations will throw an {@link
 * java.nio.channels.IllegalBlockingModeException}.
 *
 * <p> Closing the returned {@link java.io.OutputStream OutputStream}
 * will close the associated socket.
 *
 * @return     an output stream for writing bytes to this socket.
 * @exception  IOException  if an I/O error occurs when creating the
 *               output stream or if the socket is not connected.
 * @revised 1.4
 * @spec JSR-51
 */
public OutputStream getOutputStream() throws IOException {
    if (isClosed())
        throw new SocketException("Socket is closed");
    if (!isConnected())
        throw new SocketException("Socket is not connected");
    if (isOutputShutdown())
        throw new SocketException("Socket output is shutdown");
    final Socket s = this;
    OutputStream os = null;
    try {
        os = AccessController.doPrivileged(
            new PrivilegedExceptionAction<OutputStream>() {
                public OutputStream run() throws IOException {
                    return impl.getOutputStream();
                }
            });
    } catch (java.security.PrivilegedActionException e) {
        throw (IOException) e.getException();
    }
    return os;
}