Java Code Examples for java.security.AccessControlException

The following examples show how to use java.security.AccessControlException. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
@Override
public void paste(long[] docIds, long folderId, String action) throws ServerException {
	Session session = ServiceUtil.validateSession(getThreadLocalRequest());

	FolderDAO fdao = (FolderDAO) Context.get().getBean(FolderDAO.class);

	Folder folder = fdao.findFolder(folderId);

	if (!fdao.isWriteEnabled(folder.getId(), session.getUserId()))
		throw new AccessControlException("Cannot write in folder " + folder.getName());

	if (action.equals(Clipboard.CUT))
		cut(session, docIds, folder.getId());
	else if (action.equals(Clipboard.COPY))
		copy(session, docIds, folder.getId());
}
 
Example 2
private void newProxyInstance() {
    // expect newProxyInstance to succeed if it's in the same runtime package
    int i = proxyClass.getName().lastIndexOf('.');
    String pkg = (i != -1) ? proxyClass.getName().substring(0, i) : "";
    boolean hasAccess = pkg.isEmpty() || hasAccess();
    try {
        Proxy.newProxyInstance(loader, interfaces, handler);
        if (!hasAccess) {
            throw new RuntimeException("ERROR: Proxy.newProxyInstance should fail " + proxyClass);
        }
    } catch (AccessControlException e) {
        if (hasAccess) {
            throw e;
        }
        if (e.getPermission().getClass() != ReflectPermission.class ||
                !e.getPermission().getName().equals(NEW_PROXY_IN_PKG + pkg)) {
            throw e;
        }
    }
}
 
Example 3
private void newProxyInstance() {
    // expect newProxyInstance to succeed if it's in the same runtime package
    int i = proxyClass.getName().lastIndexOf('.');
    String pkg = (i != -1) ? proxyClass.getName().substring(0, i) : "";
    boolean hasAccess = pkg.isEmpty() || hasAccess();
    try {
        Proxy.newProxyInstance(loader, interfaces, handler);
        if (!hasAccess) {
            throw new RuntimeException("ERROR: Proxy.newProxyInstance should fail " + proxyClass);
        }
    } catch (AccessControlException e) {
        if (hasAccess) {
            throw e;
        }
        if (e.getPermission().getClass() != ReflectPermission.class ||
                !e.getPermission().getName().equals(NEW_PROXY_IN_PKG + pkg)) {
            throw e;
        }
    }
}
 
Example 4
Source Project: jdk8u_jdk   Source File: bug6484091.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) {
    File dir = FileSystemView.getFileSystemView().getDefaultDirectory();

    printDirContent(dir);

    System.setSecurityManager(new SecurityManager());

    // The next test cases use 'dir' obtained without SecurityManager

    try {
        printDirContent(dir);

        throw new RuntimeException("Dir content was derived bypass SecurityManager");
    } catch (AccessControlException e) {
        // It's a successful situation
    }
}
 
Example 5
Source Project: hadoop   Source File: ClientRMService.java    License: Apache License 2.0 6 votes vote down vote up
private String checkReservationACLs(String queueName, String auditConstant)
    throws YarnException {
  UserGroupInformation callerUGI;
  try {
    callerUGI = UserGroupInformation.getCurrentUser();
  } catch (IOException ie) {
    RMAuditLogger.logFailure("UNKNOWN", auditConstant, queueName,
        "ClientRMService", "Error getting UGI");
    throw RPCUtil.getRemoteException(ie);
  }
  // Check if user has access on the managed queue
  if (!queueACLsManager.checkAccess(callerUGI, QueueACL.SUBMIT_APPLICATIONS,
      queueName)) {
    RMAuditLogger.logFailure(
        callerUGI.getShortUserName(),
        auditConstant,
        "User doesn't have permissions to "
            + QueueACL.SUBMIT_APPLICATIONS.toString(), "ClientRMService",
        AuditConstants.UNAUTHORIZED_USER);
    throw RPCUtil.getRemoteException(new AccessControlException("User "
        + callerUGI.getShortUserName() + " cannot perform operation "
        + QueueACL.SUBMIT_APPLICATIONS.name() + " on queue" + queueName));
  }
  return callerUGI.getShortUserName();
}
 
Example 6
Source Project: hadoop   Source File: TestMoveApplication.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testMoveRejectedByPermissions() throws Exception {
  failMove = true;
  
  // Submit application
  final Application application = new Application("user1", resourceManager);
  application.submit();

  final ClientRMService clientRMService = resourceManager.getClientRMService();
  try {
    UserGroupInformation.createRemoteUser("otheruser").doAs(
        new PrivilegedExceptionAction<MoveApplicationAcrossQueuesResponse>() {
          @Override
          public MoveApplicationAcrossQueuesResponse run() throws Exception {
            return clientRMService.moveApplicationAcrossQueues(
                MoveApplicationAcrossQueuesRequest.newInstance(
                    application.getApplicationId(), "newqueue"));
          }
          
        });
    fail("Should have hit exception");
  } catch (Exception ex) {
    assertEquals(AccessControlException.class, ex.getCause().getCause().getClass());
  }
}
 
Example 7
public static void main (String args[]) throws Exception {
    Authenticator defaultAuth = Authenticator.getDefault();
    if (defaultAuth != null) {
        throw new RuntimeException("Unexpected authenticator: null expected");
    }
    MyAuthenticator auth = new MyAuthenticator();
    Authenticator.setDefault(auth);
    defaultAuth = Authenticator.getDefault();
    if (defaultAuth != auth) {
        throw new RuntimeException("Unexpected authenticator: auth expected");
    }
    System.setSecurityManager(new SecurityManager());
    try {
        defaultAuth = Authenticator.getDefault();
        throw new RuntimeException("Expected security exception not raised");
    } catch (AccessControlException s) {
        System.out.println("Got expected exception: " + s);
        if (!s.getPermission().equals(new NetPermission("requestPasswordAuthentication"))) {
            throw new RuntimeException("Unexpected permission check: " + s.getPermission());
        }
    }
    System.out.println("Test passed with default authenticator "
                       + defaultAuth);
}
 
Example 8
/**
 * Runs a privileged user action for a given principal.
 */
private void execute(SystemPrincipal principal,
                     PrivilegedAction action,
                     boolean isGrantExpected) {
    //println();
    //println("    testing action " + action);

    final RunAsPrivilegedUserAction runAsPrivilegedUserAction
            = new RunAsPrivilegedUserAction(principal, action);
    try {
        AccessController.doPrivileged(runAsPrivilegedUserAction);
        //println("    Congrats! access granted " + action);
        if (!isGrantExpected) {
            fail("expected AccessControlException");
        }
    } catch (AccessControlException ace) {
        //println("    Yikes! " + ace.getMessage());
        if (isGrantExpected) {
            //fail("caught AccessControlException");
            throw ace;
        }
    }
}
 
Example 9
Source Project: ganttproject   Source File: GanttProject.java    License: GNU General Public License v3.0 6 votes vote down vote up
public void setAskForSave(boolean afs) {
  if (isOnlyViewer) {
    return;
  }
  fireProjectModified(afs);
  String title = getTitle();
  askForSave = afs;
  try {
    if (System.getProperty("mrj.version") != null) {
      rootPane.putClientProperty("windowModified", Boolean.valueOf(afs));
      // see http://developer.apple.com/qa/qa2001/qa1146.html
    } else {
      if (askForSave) {
        if (!title.endsWith(" *")) {
          setTitle(title + " *");
        }
      }
    }
  } catch (AccessControlException e) {
    // This can happen when running in a sandbox (Java WebStart)
    System.err.println(e + ": " + e.getMessage());
  }
}
 
Example 10
Source Project: ignite   Source File: SecurityAwareTransformerFactory.java    License: Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override public IgniteClosure<E, R> create() {
    final IgniteClosure<E, R> cl = original.create();

    return new IgniteClosure<E, R>() {
        /** {@inheritDoc} */
        @Override public R apply(E e) {
            IgniteSecurity security = ignite.context().security();

            try (OperationSecurityContext c = security.withContext(subjectId)) {
                IgniteSandbox sandbox = security.sandbox();

                return sandbox.enabled() ? sandbox.execute(() -> cl.apply(e)) : cl.apply(e);
            }
            catch (AccessControlException ace) {
                logAccessDeniedMessage(ace);

                throw ace;
            }
        }
    };
}
 
Example 11
Source Project: peer-os   Source File: RestServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@RolesAllowed( { "Peer-Management|Delete", "Peer-Management|Update" } )
@Override
public Response cancelForRegistrationRequest( final String peerId, Boolean force )
{
    try
    {
        peerManager.doCancelRequest( peerId, force );
    }
    catch ( Exception e )
    {
        if ( e.getClass() == AccessControlException.class )
        {
            LOGGER.error( e.getMessage() );
            return Response.status( Response.Status.INTERNAL_SERVER_ERROR ).
                    entity( JsonUtil.GSON.toJson( "You don't have permission to perform this operation" ) ).build();
        }

        return Response.status( Response.Status.BAD_REQUEST ).entity( e.getMessage() ).build();
    }

    return Response.ok().build();
}
 
Example 12
/**
 * Test that setting process-wide filter is checked by security manager.
 */
@Test
public void testGlobalFilter() throws Exception {
    ObjectInputFilter global = ObjectInputFilter.Config.getSerialFilter();

    try  {
        ObjectInputFilter.Config.setSerialFilter(filter);
        assertFalse(setSecurityManager,
                "When SecurityManager exists, without "
                + "java.io.SerializablePermission(serialFilter) "
                + "IllegalStateException should be thrown");
    } catch (AccessControlException ex) {
        assertTrue(setSecurityManager);
        assertTrue(ex.getMessage().contains("java.io.SerializablePermission"));
        assertTrue(ex.getMessage().contains("serialFilter"));
    } catch (IllegalStateException ise) {
        // ISE should occur only if global filter already set
        Assert.assertNotNull(global, "Global filter should be non-null");
    }
}
 
Example 13
private void newProxyInstance() {
    // expect newProxyInstance to succeed if it's in the same runtime package
    int i = proxyClass.getName().lastIndexOf('.');
    String pkg = (i != -1) ? proxyClass.getName().substring(0, i) : "";
    boolean hasAccess = pkg.isEmpty() || hasAccess();
    try {
        Proxy.newProxyInstance(loader, interfaces, handler);
        if (!hasAccess) {
            throw new RuntimeException("ERROR: Proxy.newProxyInstance should fail " + proxyClass);
        }
    } catch (AccessControlException e) {
        if (hasAccess) {
            throw e;
        }
        if (e.getPermission().getClass() != ReflectPermission.class ||
                !e.getPermission().getName().equals(NEW_PROXY_IN_PKG + pkg)) {
            throw e;
        }
    }
}
 
Example 14
Source Project: jesterj   Source File: TikaProcessorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testExceptionToIgnoreFromTika() throws ParserConfigurationException, IOException, SAXException, TikaException {
  DocumentBuilderFactory factory =
      DocumentBuilderFactory.newInstance();
  DocumentBuilder builder = factory.newDocumentBuilder();
  ByteArrayInputStream input = new ByteArrayInputStream(XML_CONFIG.getBytes("UTF-8"));
  org.w3c.dom.Document doc = builder.parse(input);

  TikaProcessor proc = new TikaProcessor.Builder().named("foo").appendingSuffix("_tk").truncatingTextTo(20)
      .configuredWith(doc)
      .build();
  expect(mockDocument.getRawData()).andThrow(new AccessControlException("Oh no you don't!"));

  replay();
  proc.processDocument(mockDocument);
}
 
Example 15
/**
 * Test that setting process-wide filter is checked by security manager.
 */
@Test
public void testGlobalFilter() throws Exception {
    if (ObjectInputFilter.Config.getSerialFilter() == null) {
        return;
    }
    try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(bais)) {
        ObjectInputFilter.Config.setSerialFilter(filter);
        assertFalse(setSecurityManager,
                "When SecurityManager exists, without "
                + "java.security.SerializablePermission(serialFilter) Exception should be thrown");
        Object o = ois.readObject();
    } catch (AccessControlException ex) {
        assertTrue(setSecurityManager);
        assertTrue(ex.getMessage().contains("java.io.SerializablePermission"));
        assertTrue(ex.getMessage().contains("serialFilter"));
    }
}
 
Example 16
Source Project: groovy   Source File: SecurityTestSupport.java    License: Apache License 2.0 6 votes vote down vote up
protected void executeScript(Class scriptClass, Permission missingPermission) {
    try {
        Script script = InvokerHelper.createScript(scriptClass, new Binding());
        script.run();
        //InvokerHelper.runScript(scriptClass, null);
    } catch (AccessControlException ace) {
        if (missingPermission != null && missingPermission.implies(ace.getPermission())) {
            return;
        } else {
            fail(ace.toString());
        }
    }
    if (missingPermission != null) {
        fail("Should catch an AccessControlException");
    }
}
 
Example 17
/**
 * Test the LoggingPermission("control") is required.
 * @param loggerName The logger to use.
 */
public static void testPermission(String loggerName) {
    if (System.getSecurityManager() != null) {
        throw new Error("Security manager is already set");
    }
    Policy.setPolicy(new SimplePolicy(TestCase.PERMISSION));
    System.setSecurityManager(new SecurityManager());
    final ResourceBundle bundle = ResourceBundle.getBundle(LIST_BUNDLE_NAME);
    Logger foobar = Logger.getLogger(loggerName);
    try {
        foobar.setResourceBundle(bundle);
        throw new RuntimeException("Permission not checked!");
    } catch (AccessControlException x) {
        if (x.getPermission() instanceof LoggingPermission) {
            if ("control".equals(x.getPermission().getName())) {
                System.out.println("Got expected exception: " + x);
                return;
            }
        }
        throw new RuntimeException("Unexpected exception: "+x, x);
    }

}
 
Example 18
Source Project: lucene-solr   Source File: VelocityResponseWriterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@Ignore("SOLR-14025: Velocity's SecureUberspector addresses this")
public void testSandboxIntersection() throws Exception {
  assumeTrue("This test only works with security manager", System.getSecurityManager() != null);
  VelocityResponseWriter vrw = new VelocityResponseWriter();
  NamedList<String> nl = new NamedList<>();
  nl.add("template.base.dir", getFile("velocity").getAbsolutePath());
  vrw.init(nl);
  SolrQueryRequest req = req(VelocityResponseWriter.TEMPLATE,"sandbox_intersection");
  SolrQueryResponse rsp = new SolrQueryResponse();
  StringWriter buf = new StringWriter();
  try {
    vrw.write(buf, req, rsp);
    fail("template broke outside the box, retrieved: " + buf);
  } catch (MethodInvocationException e) {
    assertNotNull(e.getCause());
    assertEquals(AccessControlException.class, e.getCause().getClass());
    // expected failure, can't get outside the box
  }
}
 
Example 19
Source Project: tomee   Source File: AbstractSecurityService.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean isCallerAuthorized(final Method method, final InterfaceType type) {
    final ThreadContext threadContext = ThreadContext.getThreadContext();
    final BeanContext beanContext = threadContext.getBeanContext();
    try {
        final String ejbName = beanContext.getEjbName();
        String name = type == null ? null : type.getSpecName();
        if ("LocalBean".equals(name) || "LocalBeanHome".equals(name)) {
            name = null;
        }
        final Identity currentIdentity = clientIdentity.get();
        final SecurityContext securityContext;
        if (currentIdentity == null) {
            securityContext = threadContext.get(SecurityContext.class);
        } else {
            securityContext = new SecurityContext(currentIdentity.getSubject());
        }
        securityContext.acc.checkPermission(new EJBMethodPermission(ejbName, name, method));
    } catch (final AccessControlException e) {
        return false;
    }
    return true;
}
 
Example 20
Source Project: hadoop-gpu   Source File: ServiceAuthorizationManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Check if the given {@link Subject} has all of necessary {@link Permission} 
 * set.
 * 
 * @param user <code>Subject</code> to be authorized
 * @param permissions <code>Permission</code> set
 * @throws AuthorizationException if the authorization failed
 */
private static void checkPermission(final Subject user, 
                                    final Permission... permissions) 
throws AuthorizationException {
  try{
    Subject.doAs(user, 
                 new PrivilegedExceptionAction<Void>() {
                   @Override
                   public Void run() throws Exception {
                     try {
                       for(Permission permission : permissions) {
                         AccessController.checkPermission(permission);
                       }
                     } catch (AccessControlException ace) {
                       LOG.info("Authorization failed for " + 
                                UserGroupInformation.getCurrentUGI(), ace);
                       throw new AuthorizationException(ace);
                     }
                    return null;
                   }
                 }
                );
  } catch (PrivilegedActionException e) {
    throw new AuthorizationException(e.getException());
  }
}
 
Example 21
Source Project: lams   Source File: InternalWorkbook.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * creates the WriteAccess record containing the logged in user's name
 */
private static WriteAccessRecord createWriteAccess() {
    WriteAccessRecord retval = new WriteAccessRecord();

    String defaultUserName = "POI";
    try {
        String username = System.getProperty("user.name");
        // Google App engine returns null for user.name, see Bug 53974
        if(username == null) {
            username = defaultUserName;
        }

        retval.setUsername(username);
    } catch (AccessControlException e) {
        LOG.log(POILogger.WARN, "can't determine user.name", e);
        // AccessControlException can occur in a restricted context
        // (client applet/jws application or restricted security server)
        retval.setUsername(defaultUserName);
    }
    return retval;
}
 
Example 22
/**
 * Test the LoggingPermission("control") is required.
 * @param loggerName The logger to use.
 */
public static void testPermission(String loggerName) {
    if (System.getSecurityManager() != null) {
        throw new Error("Security manager is already set");
    }
    Policy.setPolicy(new SimplePolicy(TestCase.PERMISSION));
    System.setSecurityManager(new SecurityManager());
    final ResourceBundle bundle = ResourceBundle.getBundle(LIST_BUNDLE_NAME);
    Logger foobar = Logger.getLogger(loggerName);
    try {
        foobar.setResourceBundle(bundle);
        throw new RuntimeException("Permission not checked!");
    } catch (AccessControlException x) {
        if (x.getPermission() instanceof LoggingPermission) {
            if ("control".equals(x.getPermission().getName())) {
                System.out.println("Got expected exception: " + x);
                return;
            }
        }
        throw new RuntimeException("Unexpected exception: "+x, x);
    }

}
 
Example 23
Source Project: openjdk-jdk9   Source File: Tests.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testFactoryMethodUsingIteratorNoPermission() {
    ServiceLoader<S2> sl = doPrivileged(loadAction(S2.class), noPermissions());
    try {
        sl.iterator().next();
        assertTrue(false);
    } catch (ServiceConfigurationError e) {
        assertTrue(e.getCause() instanceof AccessControlException);
    }
}
 
Example 24
Source Project: hottub   Source File: SAAJUtil.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static boolean getSystemBoolean(String arg) {
    try {
        return Boolean.getBoolean(arg);
    } catch (AccessControlException ex) {
        return false;
    }
}
 
Example 25
public static void main (String argv[]) throws Exception {
     try {
         AccessController.checkPermission(
                     new BasicPermission("no such permission"){});
     } catch (NullPointerException npe) {
        throw new Exception("Unexpected NullPointerException for security" +
                     " debug option, -Djava.security.debug=failure");
     } catch (AccessControlException ace) {
     }
}
 
Example 26
/**
 * Test if checkAccessThread method checks permission for a Thread
 */
@Test(expectedExceptions = AccessControlException.class)
public void testCheckAccessThread() {
    System.setProperty("denied.system.properties", "mockDeniedProperty");
    carbonSecurityManager = new CarbonSecurityManager();
    Thread thread = mock(Thread.class);
    carbonSecurityManager.checkAccess(thread);
}
 
Example 27
Source Project: hadoop   Source File: HistoryClientService.java    License: Apache License 2.0 5 votes vote down vote up
private void checkAccess(Job job, JobACL jobOperation)
    throws IOException {

  UserGroupInformation callerUGI;
  callerUGI = UserGroupInformation.getCurrentUser();

  if (!job.checkAccess(callerUGI, jobOperation)) {
    throw new IOException(new AccessControlException("User "
        + callerUGI.getShortUserName() + " cannot perform operation "
        + jobOperation.name() + " on " + job.getID()));
  }
}
 
Example 28
Source Project: jdk1.8-source-analysis   Source File: Dialog.java    License: Apache License 2.0 5 votes vote down vote up
private void readObject(ObjectInputStream s)
    throws ClassNotFoundException, IOException, HeadlessException
{
    GraphicsEnvironment.checkHeadless();

    java.io.ObjectInputStream.GetField fields =
        s.readFields();

    ModalityType localModalityType = (ModalityType)fields.get("modalityType", null);

    try {
        checkModalityPermission(localModalityType);
    } catch (AccessControlException ace) {
        localModalityType = DEFAULT_MODALITY_TYPE;
    }

    // in 1.5 or earlier modalityType was absent, so use "modal" instead
    if (localModalityType == null) {
        this.modal = fields.get("modal", false);
        setModal(modal);
    } else {
        this.modalityType = localModalityType;
    }

    this.resizable = fields.get("resizable", true);
    this.undecorated = fields.get("undecorated", false);
    this.title = (String)fields.get("title", "");

    blockedWindows = new IdentityArrayList<>();

    SunToolkit.checkAndSetPolicy(this);

    initialized = true;

}
 
Example 29
Source Project: jdk8u-dev-jdk   Source File: KeyTab.java    License: GNU General Public License v2.0 5 votes vote down vote up
sun.security.krb5.internal.ktab.KeyTab takeSnapshot() {
    try {
        return sun.security.krb5.internal.ktab.KeyTab.getInstance(file);
    } catch (AccessControlException ace) {
        if (file != null) {
            // It's OK to show the name if caller specified it
            throw ace;
        } else {
            AccessControlException ace2 = new AccessControlException(
                    "Access to default keytab denied (modified exception)");
            ace2.setStackTrace(ace.getStackTrace());
            throw ace2;
        }
    }
}
 
Example 30
private static void checkPermission(PermissionCollection perms,
                                    Permission p)
    throws AccessControlException
{
    if (!perms.implies(p)) {
        throw new AccessControlException(
           "access denied " + p.toString());
    }
}