Search in sources :

Example 1 with AuthorizationException

use of org.apereo.portal.AuthorizationException in project uPortal by Jasig.

the class AnyUnblockedGrantPermissionPolicy method doesPrincipalHavePermission.

@Override
public boolean doesPrincipalHavePermission(IAuthorizationService service, IAuthorizationPrincipal principal, IPermissionOwner owner, IPermissionActivity activity, IPermissionTarget target) throws AuthorizationException {
    /*
         * The API states that the service, owner, and activity arguments must
         * not be null. If for some reason they are null, log and fail closed.
         * In our case, the principal and target must also be non-null.
         */
    if (service == null || principal == null || owner == null || activity == null || target == null) {
        log.error("Null argument to AnyUnblockedGrantPermissionPolicy doesPrincipalHavePermission() method " + "should not be possible.  This is indicative of a potentially serious bug in the permissions " + "and authorization infrastructure;  service='{}', principal='{}', owner='{}', activity='{}', " + "target='{}'", service, principal, owner, activity, target, new AuthorizationException("Null argument"));
        // fail closed
        return false;
    }
    // Is this user a super-user?  (Should this logic be moved to AuthorizationImpl?)
    final IPermissionActivity allPermissionsActivity = permissionOwnerDao.getPermissionActivity(IPermission.PORTAL_SYSTEM, IPermission.ALL_PERMISSIONS_ACTIVITY);
    if (!activity.equals(allPermissionsActivity)) {
        // NOTE:  Must check to avoid infinite recursion
        final IPermissionOwner allPermissionsOwner = permissionOwnerDao.getPermissionOwner(IPermission.PORTAL_SYSTEM);
        final IPermissionTarget allPermissionsTarget = targetProviderRegistry.getTargetProvider(allPermissionsActivity.getTargetProviderKey()).getTarget(IPermission.ALL_TARGET);
        if (doesPrincipalHavePermission(service, principal, allPermissionsOwner, allPermissionsActivity, allPermissionsTarget)) {
            // Stop checking;  just return true
            return true;
        }
    }
    /*
         * uPortal uses a few "special" targets that signal permission to
         * perform the specified activity over an entire class of targets;
         * see if one of those applies in this case.
         */
    IPermissionTarget collectiveTarget = // The "collective noun" representing a class of thing
    null;
    switch(target.getTargetType()) {
        case PORTLET:
            collectiveTarget = targetProviderRegistry.getTargetProvider(activity.getTargetProviderKey()).getTarget(IPermission.ALL_PORTLETS_TARGET);
            break;
        case CATEGORY:
            collectiveTarget = targetProviderRegistry.getTargetProvider(activity.getTargetProviderKey()).getTarget(IPermission.ALL_CATEGORIES_TARGET);
            break;
        case GROUP:
            collectiveTarget = targetProviderRegistry.getTargetProvider(activity.getTargetProviderKey()).getTarget(IPermission.ALL_GROUPS_TARGET);
            break;
        default:
    }
    /*
         * NOTE:  Cannot generalize to a collective target if we are already on
         * the collective target, else StackOverflowError.
         */
    if (collectiveTarget != null && !collectiveTarget.equals(target)) {
        if (doesPrincipalHavePermission(service, principal, owner, activity, collectiveTarget)) {
            /*
                 * There is a collective for this class of target,
                 * and the user DOES have this special permission
                 */
            return true;
        }
    }
    // Search ourselves and all ancestors for an unblocked GRANT.
    boolean rslt;
    try {
        // Track groups we've already explored to avoid infinite loop
        final Set<IGroupMember> seenGroups = new HashSet<>();
        rslt = hasUnblockedPathToGrantWithCache(service, principal, owner, activity, target, seenGroups);
    } catch (Exception e) {
        log.error("Error searching for unblocked path to grant for principal [" + principal + "]", e);
        // fail closed
        return false;
    }
    if (log.isTraceEnabled()) {
        if (rslt) {
            log.trace("Principal '{}' is granted permission to perform activity " + "'{}' on target '{}' under permission owning system '{}' " + "because this principal has an unblocked path to a GRANT.", principal, activity.getFname(), target.getKey(), owner.getFname());
        } else {
            log.trace("Principal '{}' is denied permission to perform activity '{}' " + "on target '{}' under permission owning system '{}' because this " + "principal does not have an unblocked path to a GRANT.", principal, activity.getFname(), target.getKey(), owner.getFname());
        }
    }
    return rslt;
}
Also used : IPermissionActivity(org.apereo.portal.permission.IPermissionActivity) IGroupMember(org.apereo.portal.groups.IGroupMember) AuthorizationException(org.apereo.portal.AuthorizationException) IPermissionTarget(org.apereo.portal.permission.target.IPermissionTarget) AuthorizationException(org.apereo.portal.AuthorizationException) GroupsException(org.apereo.portal.groups.GroupsException) IPermissionOwner(org.apereo.portal.permission.IPermissionOwner) HashSet(java.util.HashSet)

Example 2 with AuthorizationException

use of org.apereo.portal.AuthorizationException in project uPortal by Jasig.

the class AuthorizationImpl method canPrincipalConfigure.

@Override
@RequestCache
public boolean canPrincipalConfigure(IAuthorizationPrincipal principal, String portletDefinitionId) throws AuthorizationException {
    String owner = IPermission.PORTAL_PUBLISH;
    String target = IPermission.PORTLET_PREFIX + portletDefinitionId;
    // retrieve the indicated channel from the channel registry store and
    // determine its current lifecycle state
    IPortletDefinition portlet = this.portletDefinitionRegistry.getPortletDefinition(portletDefinitionId);
    if (portlet == null) {
        throw new AuthorizationException("Unable to locate portlet " + portletDefinitionId);
    }
    final String activity = IPermission.PORTLET_MODE_CONFIG;
    boolean isAllowed = doesPrincipalHavePermission(principal, owner, activity, target);
    logger.trace("In canPrincipalConfigure() - principal.key=[{}], is allowed?=[{}]", principal.getKey(), isAllowed);
    return isAllowed;
}
Also used : AuthorizationException(org.apereo.portal.AuthorizationException) IPortletDefinition(org.apereo.portal.portlet.om.IPortletDefinition) RequestCache(org.apereo.portal.concurrency.caching.RequestCache)

Example 3 with AuthorizationException

use of org.apereo.portal.AuthorizationException in project uPortal by Jasig.

the class AuthorizationImpl method canPrincipalManage.

/**
 * This checks if the framework has granted principal a right to publish. DO WE WANT SOMETHING
 * THIS COARSE (de)?
 *
 * @param principal IAuthorizationPrincipal
 * @return boolean
 */
@Override
@RequestCache
public boolean canPrincipalManage(IAuthorizationPrincipal principal, PortletLifecycleState state, String categoryId) throws AuthorizationException {
    // return doesPrincipalHavePermission
    // (principal, IPermission.PORTAL_FRAMEWORK, IPermission.CHANNEL_PUBLISHER_ACTIVITY,
    // null);
    String owner = IPermission.PORTAL_PUBLISH;
    // retrieve the indicated channel from the channel registry store and
    // determine its current lifecycle state
    PortletCategory category = PortletCategoryRegistryLocator.getPortletCategoryRegistry().getPortletCategory(categoryId);
    if (category == null) {
        // IPermission.CHANNEL_MANAGER_APPROVED_ACTIVITY, target);
        throw new AuthorizationException("Unable to locate category " + categoryId);
    }
    int order = state.getOrder();
    String activity = IPermission.PORTLET_MANAGER_MAINTENANCE_ACTIVITY;
    if (order <= PortletLifecycleState.MAINTENANCE.getOrder() && doesPrincipalHavePermission(principal, owner, activity, categoryId)) {
        return true;
    }
    activity = IPermission.PORTLET_MANAGER_EXPIRED_ACTIVITY;
    if (order <= PortletLifecycleState.EXPIRED.getOrder() && doesPrincipalHavePermission(principal, owner, activity, categoryId)) {
        return true;
    }
    activity = IPermission.PORTLET_MANAGER_ACTIVITY;
    if (order <= PortletLifecycleState.PUBLISHED.getOrder() && doesPrincipalHavePermission(principal, owner, activity, categoryId)) {
        return true;
    }
    activity = IPermission.PORTLET_MANAGER_APPROVED_ACTIVITY;
    if (order <= PortletLifecycleState.APPROVED.getOrder() && doesPrincipalHavePermission(principal, owner, activity, categoryId)) {
        return true;
    }
    activity = IPermission.PORTLET_MANAGER_CREATED_ACTIVITY;
    if (order <= PortletLifecycleState.CREATED.getOrder() && doesPrincipalHavePermission(principal, owner, activity, categoryId)) {
        return true;
    }
    return false;
}
Also used : AuthorizationException(org.apereo.portal.AuthorizationException) PortletCategory(org.apereo.portal.portlet.om.PortletCategory) RequestCache(org.apereo.portal.concurrency.caching.RequestCache)

Example 4 with AuthorizationException

use of org.apereo.portal.AuthorizationException in project uPortal by Jasig.

the class Authentication method authenticate.

/**
 * Attempts to authenticate a given IPerson based on a set of principals and credentials
 *
 * @param principals
 * @param credentials
 * @param person
 * @exception PortalSecurityException
 */
public void authenticate(HttpServletRequest request, Map<String, String> principals, Map<String, String> credentials, IPerson person) throws PortalSecurityException {
    // Retrieve the security context for the user
    final ISecurityContext securityContext = person.getSecurityContext();
    // Set the principals and credentials for the security context chain
    this.configureSecurityContextChain(principals, credentials, securityContext, BASE_CONTEXT_NAME);
    // NOTE: PortalPreAuthenticatedProcessingFilter looks in the security.properties file to
    // determine what tokens to look for that represent the principals and
    // credentials for each context. It then retrieves the values from the request
    // and stores the values in the principals and credentials HashMaps that are
    // passed to the Authentication service.
    // Attempt to authenticate the user
    final long start = System.currentTimeMillis();
    securityContext.authenticate();
    final long elapsed = System.currentTimeMillis() - start;
    // Check to see if the user was authenticated
    if (securityContext.isAuthenticated()) {
        // metric
        lastAuthentication = authenticationTimes.add(elapsed);
        // Add the authenticated username to the person object
        // the login name may have been provided or reset by the security provider
        // so this needs to be done after authentication.
        final String userName = securityContext.getPrincipal().getUID();
        person.setAttribute(IPerson.USERNAME, userName);
        if (log.isDebugEnabled()) {
            log.debug("FINISHED SecurityContext authentication for user '" + userName + "' in " + elapsed + "ms #milestone");
        }
        threadNamingRequestFilter.updateCurrentUsername(userName);
        /*
             * Clear cached group info for this user.
             *
             * There seem to be 2 systems in place for this information:
             *   - The old system based on EntityCachingService
             *   - The new system based on ehcache
             *
             * For uPortal 5, we should work to remove the old system.
             */
        // Old system
        GroupService.finishedSession(person);
        for (IAuthenticationListener authListener : authenticationListeners) {
            // New system
            authListener.userAuthenticated(person);
        }
        // Clear all existing cached data about the person
        this.usernameTaggedCacheEntryPurger.purgeTaggedCacheEntries(userName);
        // Retrieve the additional descriptor from the security context
        final IAdditionalDescriptor addInfo = person.getSecurityContext().getAdditionalDescriptor();
        // Process the additional descriptor if one was created
        if (addInfo != null) {
            // handled by the PersonManager.
            if (addInfo instanceof IPerson) {
                final IPerson newPerson = (IPerson) addInfo;
                person.setFullName(newPerson.getFullName());
                for (final String attributeName : newPerson.getAttributeMap().keySet()) {
                    person.setAttribute(attributeName, newPerson.getAttribute(attributeName));
                }
            } else // simply copy all of these additional attributes into the IPerson
            if (addInfo instanceof Map) {
                // Cast the additional descriptor as a Map
                final Map<?, ?> additionalAttributes = (Map<?, ?>) addInfo;
                // Copy each additional attribute into the person object
                for (final Iterator<?> keys = additionalAttributes.keySet().iterator(); keys.hasNext(); ) {
                    // Get a key
                    final String key = (String) keys.next();
                    // Set the attribute
                    person.setAttribute(key, additionalAttributes.get(key));
                }
            } else if (addInfo instanceof ChainingSecurityContext.ChainingAdditionalDescriptor) {
            // do nothing
            } else {
                if (log.isWarnEnabled()) {
                    log.warn("Authentication Service received unknown additional descriptor [" + addInfo + "]");
                }
            }
        }
        // Populate the person object using the PersonDirectory if applicable
        if (PropertiesManager.getPropertyAsBoolean("org.apereo.portal.services.Authentication.usePersonDirectory")) {
            // Retrieve all of the attributes associated with the person logging in
            final String username = person.getUserName();
            final long timestamp = System.currentTimeMillis();
            if (log.isDebugEnabled()) {
                log.debug("STARTING user attribute gathering for user '" + userName + "' #milestone");
            }
            final IPersonAttributes personAttributes = this.personAttributeDao.getPerson(username);
            if (log.isDebugEnabled()) {
                log.debug("FINISHED user attribute gathering for user '" + userName + "' in " + Long.toString(System.currentTimeMillis() - timestamp) + "ms #milestone");
            }
            if (personAttributes != null) {
                // attribs may be null.  IPersonAttributeDao returns null when it does not
                // recognize a user at all, as
                // distinguished from returning an empty Map of attributes when it recognizes a
                // user has having no
                // attributes.
                person.setAttributes(personAttributes.getAttributes());
            }
        }
        // Call extensions if present
        if (authenticationExt != null) {
            authenticationExt.postAttributeResolution(request, person);
        }
        // Make sure the the user's fullname is set
        if (person.getFullName() == null) {
            // Use portal display name if one exists
            if (person.getAttribute("portalDisplayName") != null) {
                person.setFullName((String) person.getAttribute("portalDisplayName"));
            } else // If not try the eduPerson displayName
            if (person.getAttribute("displayName") != null) {
                person.setFullName((String) person.getAttribute("displayName"));
            }
            // If still no FullName use an unrecognized string
            if (person.getFullName() == null) {
                person.setFullName("Unrecognized person: " + person.getAttribute(IPerson.USERNAME));
            }
        }
        // Find the uPortal userid for this user or flunk authentication if not found.
        final boolean autocreate = PropertiesManager.getPropertyAsBoolean("org.apereo.portal.services.Authentication.autoCreateUsers");
        try {
            // Attempt to retrieve the UID
            final int newUID = this.userIdentityStore.getPortalUID(person, autocreate);
            person.setID(newUID);
        } catch (final AuthorizationException ae) {
            log.error("Exception retrieving ID", ae);
            throw new PortalSecurityException("Authentication Service: Exception retrieving UID");
        }
    }
    // Publish a login event for the person
    this.portalEventFactory.publishLoginEvent(request, this, person);
}
Also used : IAdditionalDescriptor(org.apereo.portal.security.IAdditionalDescriptor) AuthorizationException(org.apereo.portal.AuthorizationException) ISecurityContext(org.apereo.portal.security.ISecurityContext) PortalSecurityException(org.apereo.portal.security.PortalSecurityException) IPerson(org.apereo.portal.security.IPerson) IPersonAttributes(org.apereo.services.persondir.IPersonAttributes) Iterator(java.util.Iterator) Map(java.util.Map)

Example 5 with AuthorizationException

use of org.apereo.portal.AuthorizationException in project uPortal by Jasig.

the class PortletRendererImpl method enforceConfigPermission.

/**
 * Enforces config mode access control. If requesting user does not have CONFIG permission, and
 * the PortletWindow specifies config mode, throws AuthorizationException. Otherwise does
 * nothing.
 *
 * @param httpServletRequest the non-null current HttpServletRequest (for determining requesting
 *     user)
 * @param portletWindow a non-null portlet window that might be in config mode
 * @throws AuthorizationException if the user is not permitted to access config mode yet portlet
 *     window specifies config mode
 * @throws java.lang.IllegalArgumentException if the request or window are null
 * @since 4.0.13.1, 4.0.14, 4.1.
 */
protected void enforceConfigPermission(final HttpServletRequest httpServletRequest, final IPortletWindow portletWindow) {
    Validate.notNull(httpServletRequest, "Servlet request must not be null to determine remote user.");
    Validate.notNull(portletWindow, "Portlet window must not be null to determine its mode.");
    final PortletMode portletMode = portletWindow.getPortletMode();
    if (portletMode != null) {
        if (IPortletRenderer.CONFIG.equals(portletMode)) {
            final IPerson person = this.personManager.getPerson(httpServletRequest);
            final EntityIdentifier ei = person.getEntityIdentifier();
            final AuthorizationServiceFacade authorizationServiceFacade = AuthorizationServiceFacade.instance();
            final IAuthorizationPrincipal ap = authorizationServiceFacade.newPrincipal(ei.getKey(), ei.getType());
            final IPortletEntity portletEntity = portletWindow.getPortletEntity();
            final IPortletDefinition portletDefinition = portletEntity.getPortletDefinition();
            if (!ap.canConfigure(portletDefinition.getPortletDefinitionId().getStringId())) {
                logger.error("User {} attempted to use portlet {} in {} but lacks permission to use that mode.  " + "THIS MAY BE AN ATTEMPT TO EXPLOIT A HISTORICAL SECURITY FLAW.  " + "You should probably figure out who this user is and why they are trying to access " + "unauthorized portlet modes.", person.getUserName(), portletDefinition.getFName(), portletMode);
                throw new AuthorizationException(person.getUserName() + " does not have permission to render '" + portletDefinition.getFName() + "' in " + portletMode + " PortletMode.");
            }
        }
    }
}
Also used : IPerson(org.apereo.portal.security.IPerson) AuthorizationServiceFacade(org.apereo.portal.services.AuthorizationServiceFacade) IPortletEntity(org.apereo.portal.portlet.om.IPortletEntity) AuthorizationException(org.apereo.portal.AuthorizationException) IAuthorizationPrincipal(org.apereo.portal.security.IAuthorizationPrincipal) EntityIdentifier(org.apereo.portal.EntityIdentifier) PortletMode(javax.portlet.PortletMode) IPortletDefinition(org.apereo.portal.portlet.om.IPortletDefinition)

Aggregations

AuthorizationException (org.apereo.portal.AuthorizationException)18 Connection (java.sql.Connection)5 PreparedStatement (java.sql.PreparedStatement)5 SQLException (java.sql.SQLException)5 IPortletDefinition (org.apereo.portal.portlet.om.IPortletDefinition)5 IPerson (org.apereo.portal.security.IPerson)5 ArrayList (java.util.ArrayList)4 RequestCache (org.apereo.portal.concurrency.caching.RequestCache)4 Iterator (java.util.Iterator)3 GroupsException (org.apereo.portal.groups.GroupsException)2 IPortletEntity (org.apereo.portal.portlet.om.IPortletEntity)2 PortletLifecycleState (org.apereo.portal.portlet.om.PortletLifecycleState)2 IAuthorizationPrincipal (org.apereo.portal.security.IAuthorizationPrincipal)2 PortalSecurityException (org.apereo.portal.security.PortalSecurityException)2 PersonImpl (org.apereo.portal.security.provider.PersonImpl)2 Document (org.w3c.dom.Document)2 IOException (java.io.IOException)1 ResultSet (java.sql.ResultSet)1 HashSet (java.util.HashSet)1 LinkedHashSet (java.util.LinkedHashSet)1