o g:@s$UdZddlZddlZddlZddlmZddlmZzddl m Z Wne y2ddlm Z Ynwddl m Z ddlmZddlmZdd lmZd d lmZd d lmZd d lmZd dlmZejdejdejfdZdZeZ ej!e"e#d<eZ$ej!e"e#d<ddhZ%ddhZ&ddhZ'ej(e)gdfej*e)gdfej+e)gdfe e)gdffZ,ej-ej-ej.ej/e"fdfe#d<d e0d!e1fd"d#Z2d$ed!efd%d&Z3d'ejd(e"d!e4fd)d*Z5d'ejd(e"d!e4fd+d,Z6Gd-d.d.eZ7Gd/d0d0e7Z8Gd1d2d2eZ9Gd3d4d4e9eZ:dS)5zA sandbox layer that ensures unsafe operations cannot be performed. Useful when the template itself comes from an untrusted source. N)formatter_field_name_split)abc)deque)update_wrapper) Formatter)EscapeFormatter)Markup) Environment) SecurityError)Context) UndefinedF.)boundiUNSAFE_FUNCTION_ATTRIBUTESUNSAFE_METHOD_ATTRIBUTESgi_framegi_codecr_framecr_codeag_codeag_frame)addcleardifference_updatediscardpopremovesymmetric_difference_updateupdate)rrpopitem setdefaultr)appendreverseinsertsortextendr) r" appendleftrr& extendleftrpopleftrrotate _mutable_specargsreturncGs(t|}t|tkrtdtd|S)zWA range that can't generate ranges with a length of more than MAX_RANGE items. z@Range too big. The sandbox blocks ranges larger than MAX_RANGE (z).)rangelen MAX_RANGE OverflowError)r,rngr30/usr/lib/python3/dist-packages/jinja2/sandbox.py safe_rangeWs r5fcCs d|_|S)zMarks a function or method as unsafe. .. code-block: python @unsafe def delete(self): pass T)unsafe_callable)r6r3r3r4unsafefs r8objattrcCst|tjr |tvr dSnZt|tjr|tvs|tvrdSnIt|tr*|dkr)dSn=t|tjtjtj fr7dSt|tj rD|t vrCdSn#t tdrVt|tj rV|tvrUdSnt tdrgt|tjrg|tvrgdS|dS)aTest if the attribute given is an internal python attribute. For example this function returns `True` for the `func_code` attribute of python objects. This is useful if the environment method :meth:`~SandboxedEnvironment.is_safe_attribute` is overridden. >>> from jinja2.sandbox import is_internal_attribute >>> is_internal_attribute(str, "mro") True >>> is_internal_attribute(str, "upper") False Tmro CoroutineTypeAsyncGeneratorType__) isinstancetypes FunctionTyper MethodTypertypeCodeType TracebackType FrameType GeneratorTypeUNSAFE_GENERATOR_ATTRIBUTEShasattrr<UNSAFE_COROUTINE_ATTRIBUTESr=!UNSAFE_ASYNC_GENERATOR_ATTRIBUTES startswith)r9r:r3r3r4is_internal_attributess8      rMcCs(tD]\}}t||r||vSqdS)aThis function checks if an attribute on a builtin mutable object (list, dict, set or deque) or the corresponding ABCs would modify it if called. >>> modifies_known_mutable({}, "clear") True >>> modifies_known_mutable({}, "keys") False >>> modifies_known_mutable([], "append") True >>> modifies_known_mutable([], "index") False If called with an unsupported object, ``False`` is returned. >>> modifies_known_mutable("foo", "upper") False F)r+r?)r9r:typespecr8r3r3r4modifies_known_mutables   rOc seZdZUdZdZejejejej ej ej ej dZ ejeejejejgejffed<ejejdZejeejejgejffed<eZejeed<eZejeed<d ejd ejd d ffd d Zdejdedejd efddZdejd efddZdededejdejd ejf ddZ dededejd ejfddZ!dejdej"eejfd ej"eje#ffd d!Z$dejd"ed ej"eje#ffd#d$Z%dejd"ed e#fd%d&Z&dejd ej'ejd'effd(d)Z(d*ed+ejd ejd ejd ejf d,d-Z)Z*S).SandboxedEnvironmentaThe sandboxed environment. It works like the regular environment but tells the compiler to generate sandboxed code. Additionally subclasses of this environment may override the methods that tell the runtime what attributes or functions are safe to access. If the template tries to access insecure code a :exc:`SecurityError` is raised. However also other exceptions may occur during the rendering so the caller has to ensure that all exceptions are caught. T)+-*/z//z**%default_binop_table)rQrRdefault_unop_tableintercepted_binopsintercepted_unopsr,kwargsr-Ncs8tj|i|t|jd<|j|_|j|_dS)Nr.) super__init__r5globalsrVcopy binop_tablerW unop_table)selfr,rZ __class__r3r4r\s  zSandboxedEnvironment.__init__r9r:valuecCs|dp t|| S)aYThe sandboxed environment will call this method to check if the attribute of an object is safe to access. Per default all attributes starting with an underscore are considered private as well as the special attributes of internal python objects as returned by the :func:`is_internal_attribute` function. _)rLrMrar9r:rdr3r3r4is_safe_attributesz&SandboxedEnvironment.is_safe_attributecCst|ddp t|dd S)zCheck if an object is safely callable. By default callables are considered safe unless decorated with :func:`unsafe`. This also recognizes the Django convention of setting ``func.alters_data = True``. r7F alters_data)getattr)rar9r3r3r4is_safe_callablesz%SandboxedEnvironment.is_safe_callablecontextoperatorleftrightcCs|j|||S)zFor intercepted binary operator calls (:meth:`intercepted_binops`) this function is executed instead of the builtin operator. This can be used to fine tune the behavior of certain operators. .. versionadded:: 2.6 )r_)rarkrlrmrnr3r3r4 call_binop s zSandboxedEnvironment.call_binopargcCs|j||S)zFor intercepted unary operator calls (:meth:`intercepted_unops`) this function is executed instead of the builtin operator. This can be used to fine tune the behavior of certain operators. .. versionadded:: 2.6 )r`)rarkrlrpr3r3r4 call_unopszSandboxedEnvironment.call_unopargumentc Csz||WSttfyVt|trTzt|}Wn ty"Yn2wzt||}Wn ty3Yn!w||}|durA|YS||||rL|YS| ||YSYnw|j ||dS)z(Subscribe an object from sandboxed code.Nr9name) TypeError LookupErrorr?str ExceptionriAttributeErrorwrap_str_formatrgunsafe_undefined undefined)rar9rrr:rdfmtr3r3r4getitem s.      zSandboxedEnvironment.getitem attributec Cszt||}Wnty#z||WYSttfy YnwYnw||}|dur/|S||||r8|S|||S|j||dS)zSubscribe an object from sandboxed code and prefer the attribute. The attribute passed *must* be a bytestring. Nrs)riryrurvrzrgr{r|)rar9rrdr}r3r3r4ri:s"   zSandboxedEnvironment.getattrcCs&|jd|dt|jd||tdS)z1Return an undefined object for unsafe attributes.zaccess to attribute z of z object is unsafe.)rtr9exc)r|rC__name__r )rar9rr3r3r4r{Nsz%SandboxedEnvironment.unsafe_undefined.cst|tjtjfr|jdvrdS|jttsdSt|jdkttr0t |j d}nt |}|j dt jdt jdtffdd }t||S) aIf the given value is a ``str.format`` or ``str.format_map`` method, return a new function than handles sandboxing. This is done at access rather than in :meth:`call`, so that calls made without ``call`` are also sandboxed. )format format_mapNr)escaper,rZr-csLr|rtdt|dkrtdt|d|d}d}||S)Nz'format_map() takes no keyword argumentsr z)format_map() takes exactly one argument (z given)rr3)rur/)r,rZf_self is_format_mapstr_typevformatr3r4wrapperss z5SandboxedEnvironment.wrap_str_format..wrapper)r?r@rBBuiltinMethodTyper__self__rwrCrSandboxedEscapeFormatterrSandboxedFormatterrtAnyr)rard formatterrr3rr4rzXs      $ z$SandboxedEnvironment.wrap_str_format_SandboxedEnvironment__context_SandboxedEnvironment__objcOs0||s t|d|j|g|Ri|S)z#Call an object from sandboxed code.z is not safely callable)rjr call)_SandboxedEnvironment__selfrrr,rZr3r3r4rs zSandboxedEnvironment.call)+r __module__ __qualname____doc__ sandboxedrlrsubmultruedivfloordivpowmodrVrDictrwCallabler__annotations__posnegrW frozensetrX FrozenSetrYr\boolrgrjr rorqUnionr r~rir{Optionalrzr __classcell__r3r3rbr4rPsh  ,(      $$ ,rPcs6eZdZdZdejdedejdeffdd ZZ S)ImmutableSandboxedEnvironmentzWorks exactly like the regular `SandboxedEnvironment` but does not permit modifications on the builtin mutable objects `list`, `set`, and `dict` by using the :func:`modifies_known_mutable` function. r9r:rdr-cs t|||s dSt|| S)NF)r[rgrOrfrbr3r4rgs z/ImmutableSandboxedEnvironment.is_safe_attribute) rrrrrrrwrrgrr3r3rbr4rs*rc sfeZdZdedejddffdd Zdedejejdej eejfdej ejeffd d Z Z S) renvrZr-Nc s||_tjdi|dS)Nr3)_envr[r\)rarrZrbr3r4r\szSandboxedFormatter.__init__ field_namer,c CsRt|\}}||||}|D]\}}|r|j||}q|j||}q||fS)N)r get_valuerrir~) rarr,rZfirstrestr9is_attrir3r3r4 get_fields  zSandboxedFormatter.get_field) rrrr rrr\rwSequenceMappingTuplerrr3r3rbr4rs rc@s eZdZdS)rN)rrrr3r3r3r4rsr);rrlr@typingr_stringr collectionsrcollections.abcr ImportError functoolsrstringr markupsaferr environmentr exceptionsr runtimer r TypeVarrrrr0setrSetrwrrrHrJrK MutableSetrMutableMappingMutableSequencer+rTyperintr.r5r8rrMrOrPrrrr3r3r3r4sh             (+ %d