Example usage for java.lang SecurityException SecurityException

List of usage examples for java.lang SecurityException SecurityException

Introduction

In this page you can find the example usage for java.lang SecurityException SecurityException.

Prototype

public SecurityException(Throwable cause) 

Source Link

Document

Creates a SecurityException with the specified cause and a detail message of (cause==null ?

Usage

From source file:com.google.android.apps.dashclock.DashClockService.java

private void enforceCallingPermission(String permission) throws SecurityException {
    // We need to check that any of the packages of the caller has
    // the request permission
    final PackageManager pm = getPackageManager();
    try {//from  ww w. j a  va2  s . c  om
        String[] packages = pm.getPackagesForUid(Binder.getCallingUid());
        if (packages != null) {
            for (String pkg : packages) {
                PackageInfo pi = pm.getPackageInfo(pkg, PackageManager.GET_PERMISSIONS);
                if (pi.requestedPermissions != null) {
                    for (String requestedPermission : pi.requestedPermissions) {
                        if (requestedPermission.equals(permission)) {
                            // The caller has the request permission
                            return;
                        }
                    }
                }
            }
        }
    } catch (PackageManager.NameNotFoundException ex) {
        // Ignore. Package wasn't found
    }
    throw new SecurityException("Caller doesn't have the request permission \"" + permission + "\"");
}

From source file:org.onecmdb.core.utils.wsdl.OneCMDBWebServiceImpl.java

public Graph queryGraph(String token, GraphQuery q) {

    long start = System.currentTimeMillis();
    log.info("WSDL: QueryGraph(" + token + ", " + q.toString() + ")");
    Graph result = new Graph();
    try {/*from  w  ww.j av  a  2 s .c  om*/
        // Update all beans.
        ISession session = onecmdb.getSession(token);
        if (session == null) {
            throw new SecurityException("No Session found! Try to do auth() first!");
        }
        long t1 = System.currentTimeMillis();
        QueryHandler handler = new QueryHandler(session);
        result = handler.execute3(q);

        long t2 = System.currentTimeMillis();
        log.info("\tWSDL: GraphQuery: result=" + result.toString() + (t2 - t1) + "ms");

    } catch (Throwable t) {
        long stop = System.currentTimeMillis();
        log.error("WSDL{" + (stop - start) + "}: ERROR QueryGraph(" + token + ", " + q.toString() + ")", t);
        t.printStackTrace();
        throw new IllegalArgumentException(t.getMessage(), t);
    }
    long stop = System.currentTimeMillis();
    log.info("WSDL{" + (stop - start) + "}: QueryGraph(" + token + ", " + q.toString() + ") : "
            + result.toString());
    return (result);
}

From source file:org.openanzo.activemq.internal.SecurityBroker.java

@Override
public void addProducer(ConnectionContext context, ProducerInfo info) throws Exception {
    final ServerSecurityContext subject = (ServerSecurityContext) context.getSecurityContext();
    if (subject == null) {
        MDC.put(LogUtils.REMOTE_ADDRESS, context.getConnection().getRemoteAddress());
        String errorMsg = Messages.formatString(ExceptionConstants.COMBUS.ERROR_CONNECTION_NOT_AUTHENTICATED,
                context.getConnectionId().toString());
        log.error(LogUtils.SECURITY_MARKER, errorMsg);
        MDC.clear();/*from   w  w w  .j  a v  a  2 s  .  c o  m*/
        throw new SecurityException(errorMsg);
    }
    if (info.getDestination() != null) {
        if (serverQueueNames.contains(info.getDestination().getPhysicalName())) {
            if (!subject.getAnzoPrincipal().isSysadmin()) {
                MDC.put(LogUtils.REMOTE_ADDRESS, context.getConnection().getRemoteAddress());
                MDC.put(LogUtils.USER, subject.getAnzoPrincipal().getName());
                String errorMsg = Messages.formatString(
                        ExceptionConstants.COMBUS.ERROR_CONNECTION_NOT_AUTHENTICATED, subject.getUserName(),
                        "write", info.getDestination().toString());

                log.info(LogUtils.SECURITY_MARKER, errorMsg);
                MDC.clear();
                throw new SecurityException(errorMsg);
            }
        } else if (info.getDestination().isTemporary()) {
            if (!subject.getAnzoPrincipal().isSysadmin()) {
                MDC.put(LogUtils.REMOTE_ADDRESS, context.getConnection().getRemoteAddress());
                MDC.put(LogUtils.USER, subject.getAnzoPrincipal().getName());
                String errorMsg = Messages.formatString(
                        ExceptionConstants.COMBUS.ERROR_CONNECTION_NOT_AUTHENTICATED, subject.getUserName(),
                        "write", info.getDestination().toString());
                log.info(LogUtils.SECURITY_MARKER, errorMsg);
                MDC.clear();
                throw new SecurityException(errorMsg);
            }
        } else if (info.getDestination().getPhysicalName().startsWith(NAMESPACES.NAMEDGRAPH_TOPIC_PREFIX)) {
            if (!subject.getAnzoPrincipal().isSysadmin()) {
                MDC.put(LogUtils.REMOTE_ADDRESS, context.getConnection().getRemoteAddress());
                MDC.put(LogUtils.USER, subject.getAnzoPrincipal().getName());
                String errorMsg = Messages.formatString(
                        ExceptionConstants.COMBUS.ERROR_CONNECTION_NOT_AUTHENTICATED, subject.getUserName(),
                        "write", info.getDestination().toString());
                log.info(LogUtils.SECURITY_MARKER, errorMsg);
                MDC.clear();
                throw new SecurityException(errorMsg);
            }
        } else if (info.getDestination().getPhysicalName().startsWith(NAMESPACES.STREAM_TOPIC_PREFIX)) {
            if (primaryDatasource == null) {
                String logMsg = Messages.formatString(ExceptionConstants.COMBUS.ERROR_SERVER_NOT_READY);
                log.warn(LogUtils.COMBUS_MARKER, logMsg);
                throw new SecurityException(logMsg);
            }
            IOperationContext opContext = null;
            try {
                opContext = new BaseOperationContext(ADD_PRODUCER, context.getConnectionId().toString(),
                        principal);
                opContext.setMDC();
                if (!subject.getAnzoPrincipal().isSysadmin()) {
                    String namedGraphUUIDUri = UriGenerator.stripEncapsulatedString(
                            NAMESPACES.STREAM_TOPIC_PREFIX, info.getDestination().getPhysicalName());
                    URI namedGraphUri = null;
                    try {
                        namedGraphUri = primaryDatasource.getModelService().getUriForUUID(opContext,
                                Constants.valueFactory.createURI(namedGraphUUIDUri));
                    } catch (AnzoException e) {
                        String logMsg = Messages.formatString(
                                ExceptionConstants.DATASOURCE.NAMEDGRAPH.GRAPH_NOT_VALID, namedGraphUUIDUri);
                        log.debug(LogUtils.DATASOURCE_MARKER, logMsg, e);
                        throw new SecurityException(logMsg, e);
                    }
                    if (namedGraphUri == null) {
                        String logMsg = Messages.formatString(
                                ExceptionConstants.DATASOURCE.NAMEDGRAPH.GRAPH_NOT_VALID, namedGraphUUIDUri);
                        log.debug(LogUtils.DATASOURCE_MARKER, logMsg);
                        throw new SecurityException(logMsg);
                    }
                    Set<URI> roles = primaryDatasource.getAuthorizationService().getRolesForGraph(opContext,
                            namedGraphUri, Privilege.ADD);
                    if (!org.openanzo.rdf.utils.Collections.memberOf(roles,
                            subject.getAnzoPrincipal().getRoles())) {
                        MDC.put(LogUtils.REMOTE_ADDRESS, context.getConnection().getRemoteAddress());
                        MDC.put(LogUtils.USER, subject.getAnzoPrincipal().getName());
                        String errorMsg = Messages.formatString(
                                ExceptionConstants.COMBUS.ERROR_CONNECTION_NOT_AUTHENTICATED,
                                subject.getUserName(), "write", info.getDestination().toString());
                        log.info(LogUtils.SECURITY_MARKER, errorMsg);
                        MDC.clear();
                        throw new SecurityException(errorMsg);
                    }
                }
            } finally {
                if (opContext != null) {
                    opContext.clearMDC();
                }
            }
        } else if (info.getDestination().getPhysicalName().startsWith("services/")) {
            Set<Destination> dests = next.getDestinations(info.getDestination());
            if (dests == null || dests.size() == 0) {
                MDC.put(LogUtils.REMOTE_ADDRESS, context.getConnection().getRemoteAddress());
                MDC.put(LogUtils.USER, subject.getAnzoPrincipal().getName());
                String errorMsg = Messages.formatString(ExceptionConstants.COMBUS.ERROR_TOPIC_NOT_EXIST_YET,
                        subject.getUserName(), info.getDestination().toString());
                log.info(LogUtils.SECURITY_MARKER, errorMsg);
                MDC.clear();
                throw new SecurityException(errorMsg);
            }
        }
        subject.getAuthorizedWriteDests().put(info.getDestination(), info.getDestination());
    }
    super.addProducer(context, info);
}

From source file:com.android.tv.settings.users.AppRestrictionsFragment.java

private void assertSafeToStartCustomActivity(Intent intent, String packageName) {
    // Activity can be started if it belongs to the same app
    if (intent.getPackage() != null && intent.getPackage().equals(packageName)) {
        return;//w w w.ja v  a 2  s.c o m
    }
    // Activity can be started if intent resolves to multiple activities
    List<ResolveInfo> resolveInfos = AppRestrictionsFragment.this.mPackageManager.queryIntentActivities(intent,
            0 /* no flags */);
    if (resolveInfos.size() != 1) {
        return;
    }
    // Prevent potential privilege escalation
    ActivityInfo activityInfo = resolveInfos.get(0).activityInfo;
    if (!packageName.equals(activityInfo.packageName)) {
        throw new SecurityException(
                "Application " + packageName + " is not allowed to start activity " + intent);
    }
}

From source file:edu.umich.flowfence.service.Sandbox.java

private void unbind() {
    if (localLOGD) {
        Log.d(TAG, "unbind: " + this);
    }/* ww w  .  j av a2s .c om*/
    onBeforeDisconnect.fire(this, null);
    ISandboxService sandbox;
    synchronized (mSync) {
        sandbox = mSandboxService;
        mApplication.unbindService(mConnection);
    }

    if (sandbox != null) {
        handleDisconnected();
    } else {
        return;
    }

    synchronized (mSync) {
        // Ask it to terminate itself.
        try {
            IBinder binder = sandbox.asBinder();
            sandbox.kill();

            if (!binder.isBinderAlive()) {
                return;
            }

            int timeout = DEATH_PING_MAX;
            while (--timeout >= 0) {
                if (!binder.pingBinder() || !binder.isBinderAlive()) {
                    return;
                }
                SystemClock.sleep(DEATH_PING_INTERVAL);
            }
            throw new SecurityException("Sandbox process has not died");
        } catch (RemoteException e) {
            // Object's already dead, or we're getting a spurious TransactionTooLarge.
        }
    }
}

From source file:org.fao.geonet.api.users.UsersApi.java

@ApiOperation(value = "Retrieve user groups", notes = "Retrieve the user groups.", nickname = "retrieveUserGroups")
@RequestMapping(value = "/{userIdentifier}/groups", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)
@ResponseStatus(value = HttpStatus.OK)/*from  w  w  w  .  ja  v  a 2  s.  c  o m*/
@PreAuthorize("isAuthenticated()")
@ResponseBody
public List<UserGroup> retrieveUserGroups(
        @ApiParam(value = "User identifier.") @PathVariable Integer userIdentifier,
        @ApiIgnore ServletRequest request, @ApiIgnore HttpSession httpSession) throws Exception {
    UserSession session = ApiUtils.getUserSession(httpSession);
    Profile myProfile = session.getProfile();
    String myUserId = session.getUserId();

    final UserRepository userRepository = ApplicationContextHolder.get().getBean(UserRepository.class);
    final UserGroupRepository userGroupRepository = ApplicationContextHolder.get()
            .getBean(UserGroupRepository.class);

    if (myProfile == Profile.Administrator || myProfile == Profile.UserAdmin
            || myUserId.equals(Integer.toString(userIdentifier))) {
        // -- get the profile of the user id supplied
        User user = userRepository.findOne(userIdentifier);
        if (user == null) {
            throw new IllegalArgumentException("user " + userIdentifier + " doesn't exist");
        }

        String userProfile = user.getProfile().name();

        List<UserGroup> userGroups;

        if (myProfile == Profile.Administrator && userProfile.equals(Profile.Administrator.name())) {
            // Return all groups for administrator.
            // TODO: Check if a better option returning instead of UserGroup a customised GroupDTO
            // containing all group properties and user profile
            userGroups = new ArrayList<UserGroup>();
            final GroupRepository groupRepository = ApplicationContextHolder.get()
                    .getBean(GroupRepository.class);

            List<Group> groups = groupRepository.findAll();

            for (Group g : groups) {
                UserGroup ug = new UserGroup();
                UserGroupId ugId = new UserGroupId();
                ugId.setProfile(Profile.Administrator);
                ugId.setGroupId(g.getId());
                ugId.setUserId(userIdentifier);

                ug.setGroup(g);
                ug.setUser(user);
                ug.setProfile(Profile.Administrator);
                ug.setId(ugId);

                userGroups.add(ug);
            }
        } else {
            if (!(myUserId.equals(Integer.toString(userIdentifier))) && myProfile == Profile.UserAdmin) {

                //--- retrieve session user groups and check to see whether this user is
                //--- allowed to get this info
                List<Integer> adminList = userGroupRepository
                        .findGroupIds(where(UserGroupSpecs.hasUserId(Integer.parseInt(myUserId)))
                                .or(UserGroupSpecs.hasUserId(userIdentifier)));
                if (adminList.isEmpty()) {
                    throw new SecurityException(
                            "You don't have rights to do this because the user you want is not part of your group");
                }
            }

            //--- retrieve user groups of the user id supplied
            userGroups = userGroupRepository.findAll(UserGroupSpecs.hasUserId(userIdentifier));
        }

        return userGroups;
    } else {
        throw new SecurityException("You don't have rights to do get the groups for this user");
    }
}

From source file:org.madsonic.service.PodcastService.java

private synchronized File getFile(PodcastChannel channel, PodcastEpisode episode) {

    File podcastDir = new File(settingsService.getPodcastFolder());
    File channelDir = new File(podcastDir, StringUtil.fileSystemSafe(channel.getTitle()));

    if (!channelDir.exists()) {
        boolean ok = channelDir.mkdirs();
        if (!ok) {
            throw new RuntimeException("Failed to create directory " + channelDir);
        }//  w w w  . j av  a  2  s .com

        MediaFile mediaFile = mediaFileService.getMediaFile(channelDir);
        mediaFile.setComment(channel.getDescription());
        mediaFileService.updateMediaFile(mediaFile);
    }

    String filename = StringUtil.getUrlFile(episode.getUrl());
    if (filename == null) {
        filename = episode.getTitle();
    }
    filename = StringUtil.fileSystemSafe(filename);
    String extension = FilenameUtils.getExtension(filename);
    filename = FilenameUtils.removeExtension(filename);
    if (StringUtils.isBlank(extension)) {
        extension = "mp3";
    }

    File file = new File(channelDir, filename + "." + extension);
    for (int i = 0; file.exists(); i++) {
        file = new File(channelDir, filename + i + "." + extension);
    }

    if (!securityService.isWriteAllowed(file)) {
        throw new SecurityException("Access denied to file " + file);
    }
    return file;
}

From source file:org.onecmdb.core.utils.wsdl.OneCMDBWebServiceImpl.java

public IJobStartResult cancelJob(String token, CiBean job) {
    long start = System.currentTimeMillis();
    log.info("WSDL: cancelJob(" + token + ", " + job.getAlias() + ")");
    // Update all beans.
    ISession session = onecmdb.getSession(token);
    if (session == null) {
        throw new SecurityException("No Session found! Try to do auth() first!");
    }/*from  w w w  .  j a  v a  2s. com*/
    ICi ci = getICI(session, job);

    IJobService jobSvc = (IJobService) session.getService(IJobService.class);

    IJobStartResult result = jobSvc.cancelJob(session, ci);
    long stop = System.currentTimeMillis();
    log.info("WSDL: {" + (stop - start) + "} cancelJob(" + token + ", " + job.getAlias() + ")=" + result);

    return (result);
}

From source file:com.edgenius.wiki.security.strategy.PatternStrategy.java

/**
 * Return space level policy by given spaceUname. If it is available in PolicyCache, just return cached value, otherwise,
 * it will initialise the cache. Note, these policies contain this space and its relative pages policies as well. It does not
 * contains instance policies. But the impact of instance permission setting on space/page is handled in result. For example,
 * Instance not allow "userA" read, then space read policy is not allow "userA" read even space level permission allow it.  
 * //from   w w  w.  j  a  v  a 2 s.  c om
 * 
 * @param spaceUname
 * @return
 */
private List<Policy> getSpacePolicies(String spaceUname) {
    if (StringUtils.isBlank(spaceUname))
        throw new SecurityException("Failed get space policies when given spaceUname is blank.");

    List<Policy> policies = policyCache.getPolicies(spaceUname);
    if (policies == null) {
        policies = new ArrayList<Policy>();
        //initialise space level policy for a special space:
        //its final only contain given space and its pages policies(if have)
        List<Resource> resources = new ArrayList<Resource>();

        //instance resource: will removed after policy handle is done
        Resource instanceRes = resourceDAO.getByName(WikiConstants.CONST_INSTANCE_RESOURCE_NAME);
        resources.add(instanceRes);

        //space resource
        Resource res = resourceDAO.getByName(spaceUname);
        //could not find this space corresponding resource, 
        //Page resource could be null most time. But for space resource, it maybe cause space already delete, 
        if (res != null) {
            resources.add(res);
        }

        //page resource
        List<Policy> pagePolcies = new ArrayList<Policy>();
        List<Resource> children = spaceDAO.getSpacePageResources(spaceUname);
        if (children != null && children.size() > 0)
            resources.addAll(children);

        //now get all resources for this space, handle them according to strategy.
        for (Resource resource : resources) {
            if (resource == null) {
                log.warn("Some resource is null");
                continue;
            }
            PatternFactory strategy = patternFactoryFactory.getFactory(resource.getType());
            if (RESOURCE_TYPES.PAGE.equals(resource.getType()))
                //page permission is forbidden type, rather than instance or space, which default is allow type
                pagePolcies.addAll(strategy.getPolicies(resource));
            else
                policies.addAll(strategy.getPolicies(resource));
        }

        confilictHandle(policies);
        pagePoliciesHandle(policies, pagePolcies);

        //OK, remove instance resource then
        for (Iterator<Policy> iter = policies.iterator(); iter.hasNext();) {
            if (iter.next().getType() == RESOURCE_TYPES.INSTANCE)
                iter.remove();
        }

        log.info("Space " + spaceUname + " policies is initialized.");
        policyCache.setPolicies(spaceUname, policies);
    }

    return policies;
}

From source file:org.onecmdb.core.utils.wsdl.OneCMDBWebServiceImpl.java

public void cancelTrigger(String token, CiBean trigger) {
    long start = System.currentTimeMillis();
    log.info("WSDL: cancelTrigger(" + token + ", " + trigger.getAlias() + ")");
    // Update all beans.
    ISession session = onecmdb.getSession(token);
    if (session == null) {
        throw new SecurityException("No Session found! Try to do auth() first!");
    }//from  w  w w  . j  ava 2s . co m
    ICi ci = getICI(session, trigger);

    IJobService jobSvc = (IJobService) session.getService(IJobService.class);

    jobSvc.cancelTrigger(session, ci);
    long stop = System.currentTimeMillis();
    log.info("WSDL: {" + (stop - start) + "} cancelTrigger(" + token + ", " + trigger.getAlias() + ")");
}