3
¥Yði9  ã               @   s  U d Z ddlZddlZddlZddlmZ ddlmZ ddlm	Z	 ddl
mZ ddlmZ ddlmZ d	d
lmZ d	dlmZ d	dlmZ d	dlmZ ejdejdejf d�ZdZeƒ Zeje eƒ Zeje ddhZ ddhZ!ddhZ"ej#e$ddddddddgƒfej%e$ddd d!dgƒfej&e$d"d#d$d%d&dgƒfe	e$d"d'dd&d(dd)dd*g	ƒffZ'ej(ej(ej)ej*e f df 'ejej+e d+œd,d-„Z,e-e.d.œd/d0„Z/eed1œd2d3„Z0ejee1d4œd5d6„Z2ejee1d4œd7d8„Z3G d9d:„ d:eƒZ4G d;d<„ d<e4ƒZ5G d=d>„ d>eƒZ6G d?d@„ d@e6eƒZ7dS )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.)Zboundi † Ú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Úreturnc             C   s:   t | tjtjfƒ s| jdkr"d S | j}t |tƒr6|S d S )NÚformatÚ
format_map)r)   r*   )Ú
isinstanceÚtypesÚ
MethodTypeÚBuiltinMethodTypeÚ__name__Ú__self__Ústr)r'   Úobj© r3   ú0/tmp/pip-build-8om4l6ph/Jinja2/jinja2/sandbox.pyÚinspect_format_methodS   s    

r5   )Úargsr(   c              G   s(   t | Ž }t|ƒtkr$tdt› 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   Úrngr3   r3   r4   Ú
safe_rangea   s
    r<   )Úfr(   c             C   s
   d| _ | S )z�Marks a function or method as unsafe.

    .. code-block: python

        @unsafe
        def delete(self):
            pass
    T)Úunsafe_callable)r=   r3   r3   r4   Úunsafep   s    	r?   )r2   Úattrr(   c             C   sØ   t | tjƒr|tkrÎdS n´t | tjƒr<|tks6|tkrÎdS n’t | tƒrT|dkrÎdS nzt | tjtjtj	fƒrndS t | tj
ƒrˆ|tkrÎdS nFttdƒr¬t | tjƒr¬|tkrÎdS n"ttdƒrÎt | tjƒrÎ|tkrÎdS |jdƒ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)r2   r@   r3   r3   r4   Úis_internal_attribute}   s,    

rR   c             C   s(   x"t D ]\}}t| |ƒr||kS qW dS )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+   )r2   r@   Ztypespecr?   r3   r3   r4   Úmodifies_known_mutable¢   s    
rT   c                   sØ  e Zd ZU dZdZejejejej	ej
ejejdœZejeejejejgejf f ejejdœZejeejejgejf f eƒ Zeje eƒ Zeje ejejddœ‡ fdd„Zejeejed	œd
d„Zejedœdd„Zeeejejejdœdd„Zeeejejdœdd„Z ejej!eejf ej!eje"f dœdd„Z#ejeej!eje"f dœdd„Z$ejee"dœdd„Z%d$eej&ejdf ejeejf ej'ej edœdd „Z(eejejejejd!œ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**ú%)rV   rW   N)r6   Úkwargsr(   c                s4   t ƒ j||Ž t| jd< | jjƒ | _| jjƒ | _d S )Nr7   )	ÚsuperÚ__init__r<   ÚglobalsÚdefault_binop_tableÚcopyÚbinop_tableÚdefault_unop_tableÚ
unop_table)Úselfr6   r[   )Ú	__class__r3   r4   r]   ü   s    
zSandboxedEnvironment.__init__)r2   r@   Úvaluer(   c             C   s   |j dƒpt||ƒ S )aY  The 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.
        Ú_)rQ   rR   )rd   r2   r@   rf   r3   r3   r4   Úis_safe_attribute  s    z&SandboxedEnvironment.is_safe_attribute)r2   r(   c             C   s   t |ddƒpt |ddƒ 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>   FZalters_data)Úgetattr)rd   r2   r3   r3   r4   Úis_safe_callable  s    z%SandboxedEnvironment.is_safe_callable)ÚcontextÚoperatorÚleftÚrightr(   c             C   s   | 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   )rd   rk   rl   rm   rn   r3   r3   r4   Ú
call_binop  s    	zSandboxedEnvironment.call_binop)rk   rl   Úargr(   c             C   s   | 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   )rd   rk   rl   rp   r3   r3   r4   Ú	call_unop!  s    zSandboxedEnvironment.call_unop)r2   Úargumentr(   c             C   sž   y|| S  t tfk
rŽ   t|tƒrŠyt|ƒ}W n tk
rF   Y nDX yt||ƒ}W n tk
rj   Y n X | j|||ƒr~|S | j||ƒS Y nX | j	||d�S )z(Subscribe an object from sandboxed code.)r2   Úname)
Ú	TypeErrorÚLookupErrorr+   r1   Ú	Exceptionri   ÚAttributeErrorrh   Úunsafe_undefinedÚ	undefined)rd   r2   rr   r@   rf   r3   r3   r4   Úgetitem*  s     
zSandboxedEnvironment.getitem)r2   Ú	attributer(   c             C   sr   yt ||ƒ}W n6 tk
rD   y|| S  ttfk
r>   Y nX Y n 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.
        )r2   rs   )ri   rw   rt   ru   rh   rx   ry   )rd   r2   r{   rf   r3   r3   r4   ri   A  s    zSandboxedEnvironment.getattrc             C   s&   | j d|›dt|ƒj›d�||td�S )z1Return an undefined object for unsafe attributes.zaccess to attribute z of z object is unsafe.)rs   r2   Úexc)ry   rH   r/   r
   )rd   r2   r{   r3   r3   r4   rx   R  s
    z%SandboxedEnvironment.unsafe_undefined.)Úsr6   r[   Úformat_funcr(   c             C   s†   t |tƒrt| |jd�}nt| ƒ}|dk	rl|jdkrlt|ƒdksD|r`tdt|ƒ|dk	 › 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*   r   z(format_map() takes exactly one argument z givenr   )
r+   r   ÚSandboxedEscapeFormatterr   ÚSandboxedFormatterr/   r8   rt   ÚvformatrH   )rd   r}   r6   r[   r~   Ú	formatterÚrvr3   r3   r4   Úformat_string\  s    
z"SandboxedEnvironment.format_string)Ú_SandboxedEnvironment__contextÚ_SandboxedEnvironment__objr6   r[   r(   c             O   sJ   t |ƒ}|dk	r | j||||ƒS | j|ƒs8t|›d�ƒ‚|j|f|ž|ŽS )z#Call an object from sandboxed code.Nz is not safely callable)r5   r…   rj   r
   Úcall)Z_SandboxedEnvironment__selfr†   r‡   r6   r[   Úfmtr3   r3   r4   rˆ   y  s    
zSandboxedEnvironment.call)N)+r/   Ú
__module__Ú__qualname__Ú__doc__Z	sandboxedrl   r   ÚsubÚmulÚtruedivÚfloordivÚpowÚmodr_   ÚtÚDictr1   ÚCallableÚAnyÚposÚnegrb   Ú	frozensetZintercepted_binopsÚ	FrozenSetZintercepted_unopsr]   Úboolrh   rj   r   ro   rq   ÚUnionr   rz   ri   rx   ÚTupleÚOptionalr…   rˆ   Ú__classcell__r3   r3   )re   r4   rU   »   s<   
	,(		
 *rU   c                   s0   e Zd ZdZejeejedœ‡ fdd„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.
    )r2   r@   rf   r(   c                s    t ƒ j|||ƒsdS t||ƒ S )NF)r\   rh   rT   )rd   r2   r@   rf   )re   r3   r4   rh   ’  s    z/ImmutableSandboxedEnvironment.is_safe_attribute)
r/   rŠ   r‹   rŒ   r“   r–   r1   r›   rh   rŸ   r3   r3   )re   r4   r    Œ  s   r    c                   s\   e Zd Zeejddœ‡ fdd„Zeejej ej	eejf ej
ejef dœdd„Z‡  ZS )r�   N)Úenvr[   r(   c                s   || _ tƒ jf |Ž d S )N)Ú_envr\   r]   )rd   r¡   r[   )re   r3   r4   r]   š  s    zSandboxedFormatter.__init__)Ú
field_namer6   r[   r(   c       	      C   sV   t |ƒ\}}| j|||ƒ}x2|D ]*\}}|r<| jj||ƒ}q | jj||ƒ}q W ||fS )N)r   Ú	get_valuer¢   ri   rz   )	rd   r£   r6   r[   ÚfirstÚrestr2   Úis_attrÚir3   r3   r4   Ú	get_fieldž  s    zSandboxedFormatter.get_field)r/   rŠ   r‹   r	   r“   r–   r]   r1   ÚSequenceÚMappingr�   r©   rŸ   r3   r3   )re   r4   r�   ™  s   r�   c               @   s   e Zd ZdS )r€   N)r/   rŠ   r‹   r3   r3   r3   r4   r€   «  s   r€   )8rŒ   rl   r,   Útypingr“   Ú_stringr   Úcollectionsr   r   Ústringr   Z
markupsafer   r   Úenvironmentr	   Ú
exceptionsr
   Zruntimer   r   ZTypeVarr•   r–   r   r9   ÚsetrF   ÚSetr1   rG   rM   rO   rP   Ú
MutableSetr™   ÚMutableMappingÚMutableSequencerS   r�   ÚTyperš   rž   r5   Úintr7   r<   r?   r›   rR   rT   rU   r    r�   r€   r3   r3   r3   r4   Ú<module>   sn   ,% R