3

U'íc9ã@sUdZddlZddlZddlZddlmZddlmZddlm	Z	ddl
mZddlm
Z
ddlmZd	d
lmZd	dlmZd	dlmZd	d
lmZejdejdejfdZdZeƒZejeeƒZejeddhZ ddhZ!ddhZ"ej#e$ddddddddgƒfej%e$ddd d!dgƒfej&e$d"d#d$d%d&dgƒfe	e$d"d'dd&d(dd)dd*g	ƒffZ'ej(ej(ej)ej*efdf'ejej+ed+œd,d-„Z,e-e.d.œd/d0„Z/eed1œd2d3„Z0ejee1d4œd5d6„Z2ejee1d4œd7d8„Z3Gd9d:„d:eƒZ4Gd;d<„d<e4ƒZ5Gd=d>„d>eƒZ6Gd?d@„d@e6e
ƒZ7dS)Az„A 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)Ú	Formatter)ÚEscapeFormatter)ÚMarkupé)ÚEnvironment)Ú
SecurityError)ÚContext)Ú	UndefinedÚF.)Zboundi †Úgi_frameÚgi_codeÚcr_frameÚcr_codeÚag_codeÚag_frameÚaddÚclearÚdifference_updateÚdiscardÚpopÚremoveÚsymmetric_difference_updateÚupdateÚpopitemÚ
setdefaultÚappendÚreverseÚinsertÚsortÚextendÚ
appendleftÚ
extendleftÚpopleftÚrotate)ÚcallableÚreturncCs:t|tjtjfƒs|jdkr"dS|j}t|tƒr6|SdS)NÚformatÚ
format_map)r)r*)Ú
isinstanceÚtypesÚ
MethodTypeÚBuiltinMethodTypeÚ__name__Ú__self__Ústr)r'Úobj©r3ú0/tmp/pip-build-gk9425m9/Jinja2/jinja2/sandbox.pyÚinspect_format_methodSs

r5)Úargsr(cGs(t|Ž}t|ƒtkr$tdt›dƒ‚|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).)ÚrangeÚlenÚ	MAX_RANGEÚ
OverflowError)r6Úrngr3r3r4Ú
safe_rangeas
r<)Úfr(cCs
d|_|S)zMarks a function or method as unsafe.

    .. code-block: python

        @unsafe
        def delete(self):
            pass
    T)Úunsafe_callable)r=r3r3r4Úunsafeps	r?)r2Úattrr(cCsØt|tjƒr|tkrÎdSn´t|tjƒr<|tks6|tkrÎdSn’t|tƒrT|dkrÎdSnzt|tjtjtj	fƒrndSt|tj
ƒrˆ|tkrÎdSnFttdƒr¬t|tj
ƒr¬|tkrÎdSn"ttdƒrÎt|tjƒrÎ|tkrÎdS|jdƒS)a´Test 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
    TÚmroÚ
CoroutineTypeÚAsyncGeneratorTypeÚ__)r+r,ÚFunctionTypeÚUNSAFE_FUNCTION_ATTRIBUTESr-ÚUNSAFE_METHOD_ATTRIBUTESÚtypeÚCodeTypeÚ
TracebackTypeÚ	FrameTypeÚ
GeneratorTypeÚUNSAFE_GENERATOR_ATTRIBUTESÚhasattrrBÚUNSAFE_COROUTINE_ATTRIBUTESrCÚ!UNSAFE_ASYNC_GENERATOR_ATTRIBUTESÚ
startswith)r2r@r3r3r4Úis_internal_attribute}s,

rRcCs(x"tD]\}}t||ƒr||kSqWdS)aðThis 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)Ú
_mutable_specr+)r2r@Ztypespecr?r3r3r4Úmodifies_known_mutable¢s
rTcsØeZdZUdZdZejejejej	ej
ejejdœZ
ejeejejejgejff
ejejdœZejeejejgejffeƒZejeeƒZejeejejddœ‡fdd„Zejeejed	œd
d„Zejedœd
d„Zeeejejejdœdd„Zeeejejdœdd„Z ejej!eejfej!eje"fdœdd„Z#ejeej!eje"fdœdd„Z$ejee"dœdd„Z%d$eej&ejdfejeejfej'ejedœdd „Z(eejejejejd!œd"d#„Z)‡Z*S)%ÚSandboxedEnvironmentaéThe 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**ú%)rVrWN)r6Úkwargsr(cs4tƒj||Žt|jd<|jjƒ|_|jjƒ|_dS)Nr7)	ÚsuperÚ__init__r<ÚglobalsÚdefault_binop_tableÚcopyÚbinop_tableÚdefault_unop_tableÚ
unop_table)Úselfr6r[)Ú	__class__r3r4r]üs
zSandboxedEnvironment.__init__)r2r@Úvaluer(cCs|jdƒpt||ƒ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.
        Ú_)rQrR)rdr2r@rfr3r3r4Úis_safe_attributesz&SandboxedEnvironment.is_safe_attribute)r2r(cCst|ddƒpt|ddƒS)zêCheck 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``.
        r>FZalters_data)Úgetattr)rdr2r3r3r4Úis_safe_callablesz%SandboxedEnvironment.is_safe_callable)ÚcontextÚoperatorÚleftÚrightr(cCs|j|||ƒS)z÷For 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
        )ra)rdrkrlrmrnr3r3r4Ú
call_binops	zSandboxedEnvironment.call_binop)rkrlÚargr(cCs|j||ƒS)zõFor 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
        )rc)rdrkrlrpr3r3r4Ú	call_unop!szSandboxedEnvironment.call_unop)r2Úargumentr(cCsžy||Sttfk
rŽt|tƒrŠyt|ƒ}Wntk
rFYnDXyt||ƒ}Wntk
rjYn X|j|||ƒr~|S|j||ƒSYnX|j	||dS)z(Subscribe an object from sandboxed code.)r2Úname)
Ú	TypeErrorÚLookupErrorr+r1Ú	ExceptionriÚAttributeErrorrhÚunsafe_undefinedÚ	undefined)rdr2rrr@rfr3r3r4Úgetitem*s 
zSandboxedEnvironment.getitem)r2Ú	attributer(cCsryt||ƒ}Wn6tk
rDy||Sttfk
r>YnXYn X|j|||ƒrX|S|j||ƒS|j||dS)z€Subscribe an object from sandboxed code and prefer the
        attribute.  The attribute passed *must* be a bytestring.
        )r2rs)rirwrtrurhrxry)rdr2r{rfr3r3r4riAszSandboxedEnvironment.getattrcCs&|jd|›dt|ƒj›d||tdS)z1Return an undefined object for unsafe attributes.zaccess to attribute z of z object is unsafe.)rsr2Úexc)ryrHr/r
)rdr2r{r3r3r4rxRs
z%SandboxedEnvironment.unsafe_undefined.)Úsr6r[Úformat_funcr(cCs†t|tƒrt||jd}nt|ƒ}|dk	rl|jdkrlt|ƒdksD|r`tdt|ƒ|dk	›dƒ‚|d}f}|j|||ƒ}t	|ƒ|ƒS)z…If a format call is detected, then this is routed through this
        method so that our safety sandbox can be used for it.
        )ÚescapeNr*rz(format_map() takes exactly one argument z givenr)
r+rÚSandboxedEscapeFormatterrÚSandboxedFormatterr/r8rtÚvformatrH)rdr}r6r[r~Ú	formatterÚrvr3r3r4Ú
format_string\s
z"SandboxedEnvironment.format_string)Ú_SandboxedEnvironment__contextÚ_SandboxedEnvironment__objr6r[r(cOsJt|ƒ}|dk	r |j||||ƒS|j|ƒs8t|›dƒ‚|j|f|ž|ŽS)z#Call an object from sandboxed code.Nz is not safely callable)r5r…rjr
Úcall)Z_SandboxedEnvironment__selfr†r‡r6r[Úfmtr3r3r4rˆys
zSandboxedEnvironment.call)N)+r/Ú
__module__Ú__qualname__Ú__doc__Z	sandboxedrlrÚsubÚmulÚtruedivÚfloordivÚpowÚmodr_ÚtÚDictr1ÚCallableÚAnyÚposÚnegrbÚ	frozensetZintercepted_binopsÚ	FrozenSetZintercepted_unopsr]ÚboolrhrjrrorqÚUnionrrzrirxÚTupleÚOptionalr…rˆÚ
__classcell__r3r3)rer4rU»s<
	,(		
 *rUcs0eZdZdZejeejedœ‡fdd„Z‡Z	S)ÚImmutableSandboxedEnvironmentzÓWorks 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.
    )r2r@rfr(cs tƒj|||ƒsdSt||ƒS)NF)r\rhrT)rdr2r@rf)rer3r4rh’sz/ImmutableSandboxedEnvironment.is_safe_attribute)
r/rŠr‹rŒr“r–r1r›rhrŸr3r3)rer4r Œsr cs\eZdZeejddœ‡fdd„Zeejejej	eejfej
ejefdœdd„Z‡ZS)rN)Úenvr[r(cs||_tƒjf|ŽdS)N)Ú_envr\r])rdr¡r[)rer3r4r]šszSandboxedFormatter.__init__)Ú
field_namer6r[r(c	CsVt|ƒ\}}|j|||ƒ}x2|D]*\}}|r<|jj||ƒ}q |jj||ƒ}q W||fS)N)rÚ	get_valuer¢rirz)	rdr£r6r[ÚfirstÚrestr2Úis_attrÚir3r3r4Ú	get_fieldžszSandboxedFormatter.get_field)
r/rŠr‹r	r“r–r]r1ÚSequenceÚMappingrr©rŸr3r3)rer4r™src@seZdZdS)r€N)r/rŠr‹r3r3r3r4r€«sr€)8rŒrlr,Útypingr“Ú_stringrÚcollectionsrrÚstringrZ
markupsaferrÚenvironmentr	Ú
exceptionsr
ZruntimerrZTypeVarr•r–r
r9ÚsetrFÚSetr1rGrMrOrPÚ
MutableSetr™ÚMutableMappingÚMutableSequencerSrÚTyperšržr5Úintr7r<r?r›rRrTrUr rr€r3r3r3r4Ú<module>sn,
%R