dbfdg 3 GgND@sdZddlZddlZddlmZddlmZddlmZddl m Z ddl m Z m Z ddlmZdd lmZdd lmZd Ze red d dddgZneZedddgZeddgZeddgZeddgZddlZejddeddddlmZefZe fZ!e"fZ#y6ddl$m$Z$m%Z%dd l&m&Z&e!e$e%f7Z!ee&f7ZWne'k rPYnXydd!l(m)Z)ee)f7ZWne'k rYnXdd"lm*Z*m+Z+m,Z,ee*f7Ze!e+f7Z!e#e,f7Z#ee-d#d$d%d&d'd(d)d*gfe!e-d$d'd+d,d*gfe#e-d-d.d/d0d1d(gfee-d-d2d$d1d3d'd4d(d5g ffZ.Gd6d7d7eZ/d8d9Z0d:d;Z1dd?Z3Gd@dAdAeZ4GdBdCdCe4Z5yddDl6m7Z7Wne'k rdEdFZ7YnXGdGdHdHe8Z9GdIdJdJe9eZ:GdKdLdLe9eZ;dS)Maj jinja2.sandbox ~~~~~~~~~~~~~~ Adds a sandbox layer to Jinja as it was the default behavior in the old Jinja 1 releases. This sandbox is slightly different from Jinja 1 as the default behavior is easier to use. The behavior can be changed by subclassing the environment. :copyright: (c) 2017 by the Jinja Team. :license: BSD. N)Mapping)update_wrapper) Environment) SecurityError) string_typesPY2)Markup)EscapeFormatter) FormatteriZ func_closureZ func_codeZ func_dictZ func_defaultsZ func_globalsZim_classZim_funcZim_selfgi_framegi_codecr_framecr_codeag_codeag_frameignorezthe sets modulezjinja2.sandbox)module)deque)UserDict DictMixin)UserList)Set) MutableSetMutableMappingMutableSequenceaddcleardifference_updatediscardpopremovesymmetric_difference_updateupdatepopitem setdefaultappendreverseinsertsortextend appendleft extendleftpopleftrotatec@s0eZdZdZddZddZddZdd Zd S) _MagicFormatMappingzThis class implements a dummy wrapper to fix a bug in the Python standard library for string formatting. See https://bugs.python.org/issue13598 for information about why this is necessary. cCs||_||_d|_dS)Nr)_args_kwargs _last_index)selfargskwargsr5/usr/lib/python3.6/sandbox.py__init__ssz_MagicFormatMapping.__init__c CsN|dkrD|j}|jd7_y |j|Stk r:YnXt|}|j|S)N)r1r/ LookupErrorstrr0)r2keyidxr5r5r6 __getitem__xs z_MagicFormatMapping.__getitem__cCs t|jS)N)iterr0)r2r5r5r6__iter__sz_MagicFormatMapping.__iter__cCs t|jS)N)lenr0)r2r5r5r6__len__sz_MagicFormatMapping.__len__N)__name__ __module__ __qualname____doc__r7r>r@rBr5r5r5r6r.ks  r.cGs$t|}t|tkr tdt|S)zWA range that can't generate ranges with a length of more than MAX_RANGE items. z+range too big, maximum size for range is %d)rangerA MAX_RANGE OverflowError)r3rngr5r5r6 safe_ranges  rKcCs d|_|S)znMarks a function or method as unsafe. :: @unsafe def delete(self): pass T)unsafe_callable)fr5r5r6unsafes rNcCst|tjr|tkrdSnt|tjr<|tks6|tkrdSnt|trT|dkrdSnzt|tjtjtj frndSt|tj r|t krdSnFt tdrt|tj r|tkrdSn"t tdrt|tjr|tkrdS|jdS)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 FunctionTypeUNSAFE_FUNCTION_ATTRIBUTES MethodTypeUNSAFE_METHOD_ATTRIBUTEStypeCodeType TracebackType FrameType GeneratorTypeUNSAFE_GENERATOR_ATTRIBUTEShasattrrPUNSAFE_COROUTINE_ATTRIBUTESrQ!UNSAFE_ASYNC_GENERATOR_ATTRIBUTES startswith)objattrr5r5r6is_internal_attributes,    recCs(x"tD]\}}t||r||kSqWdS)aThis function checks if an attribute on a builtin mutable object (list, dict, set or deque) would modify it if called. It also supports the "user"-versions of the objects (`sets.Set`, `UserDict.*` etc.) and with Python 2.6 onwards the abstract base classes `MutableSet`, `MutableMapping`, and `MutableSequence`. >>> 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 (such as unicode) `False` is returned. >>> modifies_known_mutable("foo", "upper") False F) _mutable_specrS)rcrdZtypespecrNr5r5r6modifies_known_mutables  rgc@seZdZdZdZejejejej ej ej ej dZ ejejdZeZeZddZddZd d Zd d Zd dZddZddZddZddZddZddZdS)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**%)rirjcCsdS)aCalled during template compilation with the name of a unary operator to check if it should be intercepted at runtime. If this method returns `True`, :meth:`call_unop` is excuted for this unary operator. The default implementation of :meth:`call_unop` will use the :attr:`unop_table` dictionary to perform the operator with the same logic as the builtin one. The following unary operators are interceptable: ``+`` and ``-`` Intercepted calls are always slower than the native operator call, so make sure only to intercept the ones you are interested in. .. versionadded:: 2.6 Fr5)r2operatorr5r5r6intercept_unop"sz#SandboxedEnvironment.intercept_unopcOs8tj|f||t|jd<|jj|_|jj|_dS)NrG) rr7rKglobalsdefault_binop_tablecopy binop_tabledefault_unop_table unop_table)r2r3r4r5r5r6r74s  zSandboxedEnvironment.__init__cCs|jdpt|| 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. _)rbre)r2rcrdvaluer5r5r6is_safe_attribute:sz&SandboxedEnvironment.is_safe_attributecCst|ddpt|dd S)aCheck if an object is safely callable. Per default a function is considered safe unless the `unsafe_callable` attribute exists and is True. Override this method to alter the behavior, but this won't affect the `unsafe` decorator from this module. rLFZ alters_data)getattr)r2rcr5r5r6is_safe_callableCs z%SandboxedEnvironment.is_safe_callablecCs|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 )rs)r2contextrnleftrightr5r5r6 call_binopLszSandboxedEnvironment.call_binopcCs|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 )ru)r2r{rnargr5r5r6 call_unopUszSandboxedEnvironment.call_unopcCsy||Sttfk rt|try t|}Wntk rFYnZXyt||}Wntk rjYn6X|j|}|dk r|S|j |||r|S|j ||SYnX|j ||dS)z(Subscribe an object from sandboxed code.N)rcname) TypeErrorr:rSrr; ExceptionryAttributeErrorwrap_str_formatrxunsafe_undefined undefined)r2rcZargumentrdrwfmtr5r5r6getitem^s&   zSandboxedEnvironment.getitemcCsyt||}Wn6tk rDy||Sttfk r>YnXYn6X|j|}|dk r\|S|j|||rn|S|j||S|j||dS)zSubscribe an object from sandboxed code and prefer the attribute. The attribute passed *must* be a bytestring. N)rcr)ryrrr:rrxrr)r2rc attributerwrr5r5r6ryvs   zSandboxedEnvironment.getattrcCs|jd||jjf||tdS)z1Return an undefined object for unsafe attributes.z.access to attribute %r of %r object is unsafe.)rrcexc)r __class__rCr)r2rcrr5r5r6rs z%SandboxedEnvironment.unsafe_undefinedcst|tjtjf s|jdkr"dS|jtts6dSt|jdkttrbt |j d}nt |}|j fdd}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_mapN)escapecsLr<|rtdt|dkr0tdt|d|d}f}||S)Nz'format_map() takes no keyword argumentsr9z)format_map() takes exactly one argument (z given)r)rrA)r3r4)f_self is_format_mapstr_typevformatr5r6wrappers z5SandboxedEnvironment.wrap_str_format..wrapper)rr)rSrTrWBuiltinMethodTyperC__self__r;rYrSandboxedEscapeFormatterrSandboxedFormatterrr)r2rwZ formatterrr5)rrrrr6rs     z$SandboxedEnvironment.wrap_str_formatcOs*|j|std|f|j|f||S)z#Call an object from sandboxed code.z%r is not safely callable)rzrcall)Z_SandboxedEnvironment__selfZ_SandboxedEnvironment__contextZ_SandboxedEnvironment__objr3r4r5r5r6rs zSandboxedEnvironment.callN)rCrDrErFZ sandboxedrnrsubmultruedivfloordivpowmodrqposnegrt frozensetZintercepted_binopsZintercepted_unopsror7rxrzr~rrryrrrr5r5r5r6rhs0       $rhc@seZdZdZddZdS)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. cCs tj||||sdSt|| S)NF)rhrxrg)r2rcrdrwr5r5r6rxsz/ImmutableSandboxedEnvironment.is_safe_attributeN)rCrDrErFrxr5r5r5r6rsr)formatter_field_name_splitcCs|jS)N)Z_formatter_field_name_split) field_namer5r5r6rsrc@seZdZddZddZdS)SandboxedFormatterMixincCs ||_dS)N)_env)r2envr5r5r6r7sz SandboxedFormatterMixin.__init__c CsVt|\}}|j|||}x2|D]*\}}|r<|jj||}q |jj||}q W||fS)N)rZ get_valuerryr) r2rr3r4firstrestrcZis_attrir5r5r6 get_fields z!SandboxedFormatterMixin.get_fieldN)rCrDrEr7rr5r5r5r6rsrc@seZdZddZdS)rcCstj||tj|dS)N)rr7r )r2rr5r5r6r7s zSandboxedFormatter.__init__N)rCrDrEr7r5r5r5r6rsrc@seZdZddZdS)rcCstj||tj||dS)N)rr7r )r2rrr5r5r6r7s z!SandboxedEscapeFormatter.__init__N)rCrDrEr7r5r5r5r6rsr)s                        $_