def wrapWorkflowMethod(self, ob, method_id, func, args, kw): ''' Allows the user to request a workflow action. This method must perform its own security checks. ''' sdef = self._getWorkflowStateOf(ob) if sdef is None: raise WorkflowException, 'Object is in an undefined state' if method_id not in sdef.transitions: raise Unauthorized(method_id) tdef = self.transitions.get(method_id, None) if tdef is None or tdef.trigger_type != TRIGGER_WORKFLOW_METHOD: raise WorkflowException, ( 'Transition %s is not triggered by a workflow method' % method_id) if not self._checkTransitionGuard(tdef, ob): raise Unauthorized(method_id) res = func(*args, **kw) try: self._changeStateOf(ob, tdef) except ObjectDeleted: # Re-raise with a different result. raise ObjectDeleted(res) except ObjectMoved, ex: # Re-raise with a different result. raise ObjectMoved(ex.getNewObject(), res)
def guarded_getattr(inst, name, default=_marker): """Retrieves an attribute, checking security in the process. Raises Unauthorized if the attribute is found but the user is not allowed to access the attribute. """ if name[:1] == '_': raise Unauthorized(name) # Try to get the attribute normally so that unusual # exceptions are caught early. try: v = getattr(inst, name) except AttributeError: if default is not _marker: return default raise try: container = v.__self__ except AttributeError: container = aq_parent(aq_inner(v)) or inst assertion = Containers(type(container)) if isinstance(assertion, dict): # We got a table that lets us reason about individual # attrs assertion = assertion.get(name) if assertion: # There's an entry, but it may be a function. if callable(assertion): return assertion(inst, name) # Nope, it's boolean return v raise Unauthorized(name) if assertion: if callable(assertion): factory = assertion(name, v) if callable(factory): return factory(inst, name) assert factory == 1 else: assert assertion == 1 return v # See if we can get the value doing a filtered acquire. # aq_acquire will either return the same value as held by # v or it will return an Unauthorized raised by validate. validate = getSecurityManager().validate aq_acquire(inst, name, aq_validate, validate) return v
def doActionFor(self, ob, action, comment='', **kw): ''' Allows the user to request a workflow action. This method must perform its own security checks. ''' kw['comment'] = comment sdef = self._getWorkflowStateOf(ob) if sdef is None: raise WorkflowException(_(u'Object is in an undefined state.')) if action not in sdef.transitions: raise Unauthorized(action) tdef = self.transitions.get(action, None) if tdef is None or tdef.trigger_type != TRIGGER_USER_ACTION: msg = _(u"Transition '${action_id}' is not triggered by a user " u"action.", mapping={'action_id': action}) raise WorkflowException(msg) if not self._checkTransitionGuard(tdef, ob, **kw): raise Unauthorized(action) self._changeStateOf(ob, tdef, kw)
def __getitem__(self, index): data = self._data try: s = self._seq except AttributeError: return data[index] i = index if i < 0: i = len(self) + i if i < 0: raise IndexError(index) ind = len(data) if i < ind: return data[i] ind = ind - 1 test = self._test e = self._eindex skip = self._skip while i > ind: e = e + 1 try: try: v = guarded_getitem(s, e) except Unauthorized as vv: if skip is None: self._eindex = e msg = '(item %s): %s' % (index, vv) raise Unauthorized(msg) skip_this = 1 else: skip_this = 0 except IndexError: del self._test del self._seq del self._eindex raise IndexError(index) if skip_this: continue if skip and not getSecurityManager().checkPermission(skip, v): continue if test is None or test(v): data.append(v) ind = ind + 1 self._eindex = e return data[i]
def manage_takeOwnership(self, REQUEST, RESPONSE, recursive=0): """Take ownership (responsibility) for an object. If 'recursive' is true, then also take ownership of all sub-objects. """ security = getSecurityManager() want_referer = REQUEST['URL1'] + '/manage_owner' got_referer = ("%s://%s%s" % parse.urlparse(REQUEST['HTTP_REFERER'])[:3]) __traceback_info__ = want_referer, got_referer if (want_referer != got_referer or security.calledByExecutable()): raise Unauthorized( 'manage_takeOwnership was called from an invalid context') self.changeOwnership(security.getUser(), recursive) raise Redirect(REQUEST['HTTP_REFERER'])
def __call__(self): request = self.context.REQUEST token, path = self.split_cookie() tr_annotate = ITokenRolesAnnotate(self.context, None) if tr_annotate and (not tr_annotate.token_dict.has_key(token)): if path: path = base64.b64decode(path) portal_state = getMultiAdapter((self.context, request), name=u'plone_portal_state') navigation_root = portal_state.navigation_root() parent = navigation_root.unrestrictedTraverse( path.replace('/'.join(navigation_root.getPhysicalPath()), '')[1:]) tr_annotate = ITokenRolesAnnotate(parent, None) if self.canView or (tr_annotate and tr_annotate.token_dict.has_key(token)): return self.index() raise Unauthorized(self.__name__)
def __call__(self): if not self.request.method == 'POST': return if not self.context.can_reset_token(): raise Unauthorized("You are not allowed to send token email") email = self.context.official_email if email: # send_newtoken_email(self.context) notify(ResetTokenEvent(self.context)) show_message("Email Sent to {0}".format(email), request=self.request, type="info") else: show_message("Official email is not set", request=self.request, type="error") return self.request.response.redirect(self.context.absolute_url())
def open_url(url, asFile=False, data=None): """Retrieve content from url""" safe_domains = [] for safedomains_utils in component.getUtilitiesFor(IPlominoSafeDomains): safe_domains += safedomains_utils[1].domains is_safe = False for domain in safe_domains: if (url.startswith(domain) or url.split("//")[1].split("/")[0].split('@')[-1] == domain): is_safe = True break if is_safe: if data and not isinstance(data, basestring): data = urllib.urlencode(data) f = urllib.urlopen(url, data) if asFile: return f.fp else: return f.read() else: raise Unauthorized(url)
def unrestrictedTraverse(self, path, default=_marker, restricted=False): """Lookup an object by path. path -- The path to the object. May be a sequence of strings or a slash separated string. If the path begins with an empty path element (i.e., an empty string or a slash) then the lookup is performed from the application root. Otherwise, the lookup is relative to self. Two dots (..) as a path element indicates an upward traversal to the acquisition parent. default -- If provided, this is the value returned if the path cannot be traversed for any reason (i.e., no object exists at that path or the object is inaccessible). restricted -- If false (default) then no security checking is performed. If true, then all of the objects along the path are validated with the security machinery. Usually invoked using restrictedTraverse(). """ if not path: return self if isinstance(path, str): # Unicode paths are not allowed path = path.split('/') else: path = list(path) REQUEST = {'TraversalRequestNameStack': path} path.reverse() path_pop = path.pop if len(path) > 1 and not path[0]: # Remove trailing slash path_pop(0) if restricted: validate = getSecurityManager().validate if not path[-1]: # If the path starts with an empty string, go to the root first. path_pop() obj = self.getPhysicalRoot() if restricted: validate(None, None, None, obj) # may raise Unauthorized else: obj = self # import time ordering problem from webdav.NullResource import NullResource resource = _marker try: while path: name = path_pop() __traceback_info__ = path, name if name[0] == '_': # Never allowed in a URL. raise NotFound, name if name == '..': next = aq_parent(obj) if next is not None: if restricted and not validate(obj, obj, name, next): raise Unauthorized(name) obj = next continue bobo_traverse = getattr(obj, '__bobo_traverse__', None) try: if name and name[:1] in '@+' and name != '+' and nsParse( name)[1]: # Process URI segment parameters. ns, nm = nsParse(name) try: next = namespaceLookup(ns, nm, obj, aq_acquire(self, 'REQUEST')) if IAcquirer.providedBy(next): next = next.__of__(obj) if restricted and not validate( obj, obj, name, next): raise Unauthorized(name) except LocationError: raise AttributeError(name) else: next = UseTraversalDefault # indicator try: if bobo_traverse is not None: next = bobo_traverse(REQUEST, name) if restricted: if aq_base(next) is not next: # The object is wrapped, so the acquisition # context is the container. container = aq_parent(aq_inner(next)) elif getattr(next, 'im_self', None) is not None: # Bound method, the bound instance # is the container container = next.im_self elif getattr(aq_base(obj), name, _marker) is next: # Unwrapped direct attribute of the object so # object is the container container = obj else: # Can't determine container container = None # If next is a simple unwrapped property, its # parentage is indeterminate, but it may have # been acquired safely. In this case validate # will raise an error, and we can explicitly # check that our value was acquired safely. try: ok = validate(obj, container, name, next) except Unauthorized: ok = False if not ok: if (container is not None or guarded_getattr( obj, name, _marker) is not next): raise Unauthorized(name) except UseTraversalDefault: # behave as if there had been no '__bobo_traverse__' bobo_traverse = None if next is UseTraversalDefault: if getattr(aq_base(obj), name, _marker) is not _marker: if restricted: next = guarded_getattr(obj, name) else: next = getattr(obj, name) else: try: next = obj[name] # The item lookup may return a NullResource, # if this is the case we save it and return it # if all other lookups fail. if isinstance(next, NullResource): resource = next raise KeyError(name) except (AttributeError, TypeError): # Raise NotFound for easier debugging # instead of AttributeError: __getitem__ # or TypeError: not subscriptable raise NotFound(name) if restricted and not validate( obj, obj, None, next): raise Unauthorized(name) except (AttributeError, NotFound, KeyError), e: # Try to look for a view next = queryMultiAdapter( (obj, aq_acquire(self, 'REQUEST')), Interface, name) if next is not None: if IAcquirer.providedBy(next): next = next.__of__(obj) if restricted and not validate(obj, obj, name, next): raise Unauthorized(name) elif bobo_traverse is not None: # Attribute lookup should not be done after # __bobo_traverse__: raise e else: # No view, try acquired attributes try: if restricted: next = guarded_getattr(obj, name, _marker) else: next = getattr(obj, name, _marker) except AttributeError: raise e if next is _marker: # If we have a NullResource from earlier use it. next = resource if next is _marker: # Nothing found re-raise error raise e obj = next return obj
def __you_lose(self): name = self.__dict__['_name'] raise Unauthorized('Not authorized to access binding: %s' % name)
def raiseVerbose( msg, accessed, container, name, value, context, required_roles=None, user_roles=None, user=None, eo=None, eo_owner=None, eo_owner_roles=None, eo_proxy_roles=None, ): """Raises an Unauthorized error with a verbose explanation.""" s = '%s. Access to %s of %s' % (msg, repr(name), item_repr(container)) if aq_base(container) is not aq_base(accessed): s += ', acquired through %s,' % item_repr(accessed) info = [s + ' denied.'] if user is not None: try: ufolder = '/'.join(aq_parent(aq_inner(user)).getPhysicalPath()) except: ufolder = '(unknown)' info.append('Your user account, %s, exists at %s.' % (str(user), ufolder)) if required_roles is not None: p = None required_roles = list(required_roles) for r in required_roles: if r.startswith('_') and r.endswith('_Permission'): p = r[1:] required_roles.remove(r) break sr = simplifyRoles(required_roles) if p: # got a permission name info.append('Access requires %s, ' 'granted to the following roles: %s.' % (p, sr)) else: # permission name unknown info.append('Access requires one of the following roles: %s.' % sr) if user_roles is not None: info.append('Your roles in this context are %s.' % simplifyRoles(user_roles)) if eo is not None: s = 'The executing script is %s' % item_repr(eo) if eo_proxy_roles is not None: s += ', with proxy roles: %s' % simplifyRoles(eo_proxy_roles) if eo_owner is not None: s += ', owned by %s' % repr(eo_owner) if eo_owner_roles is not None: s += ', who has the roles %s' % simplifyRoles(eo_owner_roles) info.append(s + '.') text = ' '.join(info) LOG.debug('Unauthorized: %s' % text) raise Unauthorized(text)
def validate(self, accessed, container, name, value, context, roles=_noroles, getattr=getattr, _noroles=_noroles, valid_aq_=('aq_parent', 'aq_inner', 'aq_explicit')): ############################################################ # Provide special rules for the acquisition attributes if isinstance(name, str): if name.startswith('aq_') and name not in valid_aq_: if self._verbose: raiseVerbose( 'aq_* names (other than %s) are not allowed' % ', '.join(valid_aq_), accessed, container, name, value, context) raise Unauthorized(name, value) containerbase = aq_base(container) accessedbase = aq_base(accessed) if accessedbase is accessed: # accessed is not a wrapper, so assume that the # value could not have been acquired. accessedbase = container ############################################################ # If roles weren't passed in, we'll try to get them from the object if roles is _noroles: roles = getRoles(container, name, value, _noroles) ############################################################ # We still might not have any roles if roles is _noroles: ############################################################ # We have an object without roles and we didn't get a list # of roles passed in. Presumably, the value is some simple # object like a string or a list. We'll try to get roles # from its container. if container is None: # Either container or a list of roles is required # for ZopeSecurityPolicy to know whether access is # allowable. if self._verbose: raiseVerbose('No container provided', accessed, container, name, value, context) raise Unauthorized(name, value) roles = getattr(container, '__roles__', roles) if roles is _noroles: if containerbase is container: # Container is not wrapped. if containerbase is not accessedbase: if self._verbose: raiseVerbose( 'Unable to find __roles__ in the container ' 'and the container is not wrapped', accessed, container, name, value, context) raise Unauthorized(name, value) else: # Try to acquire roles try: roles = aq_acquire(container, '__roles__') except AttributeError: if containerbase is not accessedbase: if self._verbose: raiseVerbose( 'Unable to find or acquire __roles__ ' 'from the container', accessed, container, name, value, context) raise Unauthorized(name, value) # We need to make sure that we are allowed to # get unprotected attributes from the container. We are # allowed for certain simple containers and if the # container says we can. Simple containers # may also impose name restrictions. p = Containers(type(container), None) if p is None: p = getattr(container, '__allow_access_to_unprotected_subobjects__', None) if p is not None: if not isinstance(p, int): # catches bool too if isinstance(p, dict): if isinstance(name, basestring): p = p.get(name) else: p = 1 else: p = p(name, value) if not p: if self._verbose: raiseVerbose('The container has no security assertions', accessed, container, name, value, context) raise Unauthorized(name, value) if roles is _noroles: return 1 # We are going to need a security-aware object to pass # to allowed(). We'll use the container. value = container # Short-circuit tests if we can: try: if roles is None or 'Anonymous' in roles: return 1 except TypeError: # 'roles' isn't a sequence LOG.error("'%s' passed as roles" " during validation of '%s' is not a sequence." % ( ` roles `, name)) raise # Check executable security stack = context.stack if stack: eo = stack[-1] # If the executable had an owner, can it execute? if self._ownerous: owner = eo.getOwner() if (owner is not None) and not owner.allowed(value, roles): # We don't want someone to acquire if they can't # get an unacquired! if self._verbose: if len(roles) < 1: raiseVerbose("The object is marked as private", accessed, container, name, value, context) elif userHasRolesButNotInContext(owner, value, roles): raiseVerbose( "The owner of the executing script is defined " "outside the context of the object being " "accessed", accessed, container, name, value, context, required_roles=roles, eo_owner=owner, eo=eo) else: raiseVerbose( "The owner of the executing script does not " "have the required permission", accessed, container, name, value, context, required_roles=roles, eo_owner=owner, eo=eo, eo_owner_roles=getUserRolesInContext( owner, value)) raise Unauthorized(name, value) # Proxy roles, which are a lot safer now. proxy_roles = getattr(eo, '_proxy_roles', None) if proxy_roles: # Verify that the owner actually can state the proxy role # in the context of the accessed item; users in subfolders # should not be able to use proxy roles to access items # above their subfolder! owner = eo.getWrappedOwner() if owner is not None: if container is not containerbase: # Unwrapped objects don't need checking if not owner._check_context(container): # container is higher up than the owner, # deny access if self._verbose: raiseVerbose( "The owner of the executing script is " "defined outside the context of the " "object being accessed. The script has " "proxy roles, but they do not apply in " "this context.", accessed, container, name, value, context, required_roles=roles, eo_owner=owner, eo=eo) raise Unauthorized(name, value) for r in proxy_roles: if r in roles: return 1 # Proxy roles actually limit access! if self._verbose: if len(roles) < 1: raiseVerbose("The object is marked as private", accessed, container, name, value, context) else: raiseVerbose( "The proxy roles set on the executing script " "do not allow access", accessed, container, name, value, context, eo=eo, eo_proxy_roles=proxy_roles, required_roles=roles) raise Unauthorized(name, value) try: if self._authenticated and context.user.allowed(value, roles): return 1 except AttributeError: pass if self._verbose: if len(roles) < 1: raiseVerbose("The object is marked as private", accessed, container, name, value, context) elif not self._authenticated: raiseVerbose( "Authenticated access is not allowed by this " "security policy", accessed, container, name, value, context) elif userHasRolesButNotInContext(context.user, value, roles): raiseVerbose( "Your user account is defined outside " "the context of the object being accessed", accessed, container, name, value, context, required_roles=roles, user=context.user) else: raiseVerbose( "Your user account does not " "have the required permission", accessed, container, name, value, context, required_roles=roles, user=context.user, user_roles=getUserRolesInContext(context.user, value)) raise Unauthorized(name, value)
def __call__(self): self.update() if self.isAnon: raise Unauthorized(msg_unauthorized) return self.index()