3
 [ð]ª  ã               @   s,  d Z ddlZddl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ZdZe	dƒjZeeddƒZeƒ Zedd„ ejjejjgD ƒƒZeddfdd„Zeddfdd„Zdd„ Zdd„ Z dd„ Z!dd„ Z"d&d d!„Z#d"d#„ Z$d$d%„ Z%dS )'z«
    werkzeug.security
    ~~~~~~~~~~~~~~~~~

    Security related helpers such as secure password hashing tools.

    :copyright: 2007 Pallets
    :license: BSD-3-Clause
é    N)ÚSystemRandom)ÚStructé   )Úizip)ÚPY2)Ú
range_type)Ú	text_type)Úto_bytes)Ú	to_nativeZ>abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789iðI z>IÚcompare_digestc             c   s   | ]}|dkr|V  qd S )Nú/)Nr   © )Ú.0Úsepr   r   ú5/tmp/pip-build-w1as9q70/Werkzeug/werkzeug/security.pyú	<genexpr>!   s    r   c             C   s    t | ||||ƒ}ttj|dƒƒS )a)  Like :func:`pbkdf2_bin`, but returns a hex-encoded string.

    .. versionadded:: 0.9

    :param data: the data to derive.
    :param salt: the salt for the derivation.
    :param iterations: the number of iterations.
    :param keylen: the length of the resulting key.  If not provided,
                   the digest size will be used.
    :param hashfunc: the hash function to use.  This can either be the
                     string name of a known hash function, or a function
                     from the hashlib module.  Defaults to sha256.
    Ú	hex_codec)Ú
pbkdf2_binr
   ÚcodecsÚencode)ÚdataÚsaltÚ
iterationsÚkeylenÚhashfuncÚrvr   r   r   Ú
pbkdf2_hex%   s    r   c             C   sJ   |sd}t | ƒ} t |ƒ}t|ƒr4|ƒ }t|ddƒ}n|}tj|| |||ƒS )aò  Returns a binary digest for the PBKDF2 hash algorithm of `data`
    with the given `salt`. It iterates `iterations` times and produces a
    key of `keylen` bytes. By default, SHA-256 is used as hash function;
    a different hashlib `hashfunc` can be provided.

    .. versionadded:: 0.9

    :param data: the data to derive.
    :param salt: the salt for the derivation.
    :param iterations: the number of iterations.
    :param keylen: the length of the resulting key.  If not provided
                   the digest size will be used.
    :param hashfunc: the hash function to use.  This can either be the
                     string name of a known hash function or a function
                     from the hashlib module.  Defaults to sha256.
    Úsha256ÚnameN)r	   ÚcallableÚgetattrÚhashlibÚpbkdf2_hmac)r   r   r   r   r   Z
_test_hashÚ	hash_namer   r   r   r   9   s    r   c             C   s°   t | tƒr| jdƒ} t |tƒr(|jdƒ}tdk	r:t| |ƒS t| ƒt|ƒkrNdS d}tr„xPt| |ƒD ]\}}|t|ƒt|ƒA O }qbW n$x"t| |ƒD ]\}}|||A O }q�W |dkS )zöThis function compares strings in somewhat constant time.  This
    requires that the length of at least one string is known in advance.

    Returns `True` if the two strings are equal, or `False` if they are not.

    .. versionadded:: 0.7
    zutf-8NFr   )Ú
isinstancer   r   Ú_builtin_safe_str_cmpÚlenr   r   Úord)ÚaÚbr   ÚxÚyr   r   r   Úsafe_str_cmpZ   s    




r,   c             C   s(   | dkrt dƒ‚djdd„ t| ƒD ƒƒS )zAGenerate a random string of SALT_CHARS with specified ``length``.r   zSalt length must be positiveÚ c             s   s   | ]}t jtƒV  qd S )N)Ú_sys_rngÚchoiceÚ
SALT_CHARS)r   Ú_r   r   r   r   |   s    zgen_salt.<locals>.<genexpr>)Ú
ValueErrorÚjoinr   )Úlengthr   r   r   Úgen_saltx   s    r5   c       	      C   sø   | dkr|| fS t |tƒr$|jdƒ}| jdƒrˆ| dd… jdƒ}t|ƒdkrTtd	ƒ‚|jd
ƒ} |rrt|d
 pnd
ƒptt	}d}d| |f }nd}| }|r²|s tdƒ‚t
|||| d�}n>|ràt |tƒrÊ|jdƒ}t||| ƒ}|jƒ }ntj| |ƒjƒ }||fS )z�Internal password hash helper.  Supports plaintext without salt,
    unsalted and salted passwords.  In case salted passwords are used
    hmac is used.
    Úplainzutf-8zpbkdf2:é   Nú:r   é   z&Invalid number of arguments for PBKDF2r   Tzpbkdf2:%s:%dFzSalt is required for PBKDF2)r   )r   r9   )r$   r   r   Ú
startswithÚsplitr&   r2   ÚpopÚintÚDEFAULT_PBKDF2_ITERATIONSr   Ú_create_macÚ	hexdigestr!   Únew)	Úmethodr   ÚpasswordÚargsr   Z	is_pbkdf2Úactual_methodr   Úmacr   r   r   Ú_hash_internal   s2    






rG   c                s8   t ˆ ƒrtj| |ˆ ƒS d‡ fdd„	}||_tj| ||ƒS )Nó    c                s   t jˆ | ƒS )N)r!   rA   )Úd)rB   r   r   r   ¨   s    z_create_mac.<locals>.hashfunc)rH   )r   ÚhmacÚHMACÚ__call__)ÚkeyÚmsgrB   r   r   )rB   r   r?   ¤   s
    r?   úpbkdf2:sha256é   c             C   s2   |dkrt |ƒnd}t||| ƒ\}}d|||f S )aø  Hash a password with the given method and salt with a string of
    the given length. The format of the string returned includes the method
    that was used so that :func:`check_password_hash` can check the hash.

    The format for the hashed string looks like this::

        method$salt$hash

    This method can **not** generate unsalted passwords but it is possible
    to set param method='plain' in order to enforce plaintext passwords.
    If a salt is used, hmac is used internally to salt the password.

    If PBKDF2 is wanted it can be enabled by setting the method to
    ``pbkdf2:method:iterations`` where iterations is optional::

        pbkdf2:sha256:80000$salt$hash
        pbkdf2:sha256$salt$hash

    :param password: the password to hash.
    :param method: the hash method to use (one that hashlib supports). Can
                   optionally be in the format ``pbkdf2:<method>[:iterations]``
                   to enable PBKDF2.
    :param salt_length: the length of the salt in letters.
    r6   r-   z%s$%s$%s)r5   rG   )rC   rB   Zsalt_lengthr   ÚhrE   r   r   r   Úgenerate_password_hash±   s    rR   c             C   s:   | j dƒdk rdS | jddƒ\}}}tt|||ƒd |ƒS )aÉ  check a password against a given salted and hashed password value.
    In order to support unsalted legacy passwords this method supports
    plain text passwords, md5 and sha1 hashes (both salted and unsalted).

    Returns `True` if the password matched, `False` otherwise.

    :param pwhash: a hashed string like returned by
                   :func:`generate_password_hash`.
    :param password: the plaintext password to compare against the hash.
    ú$r9   Fr   )Úcountr;   r,   rG   )ZpwhashrC   rB   r   Zhashvalr   r   r   Úcheck_password_hashÏ   s    rU   c                sr   | g}x`|D ]X‰ ˆ dkr"t jˆ ƒ‰ t‡ fdd„tD ƒƒsVtjjˆ ƒsVˆ dksVˆ jdƒrZdS |jˆ ƒ qW t j	|Ž S )a2  Safely join zero or more untrusted path components to a base
    directory to avoid escaping the base directory.

    :param directory: The trusted base directory.
    :param pathnames: The untrusted path components relative to the
        base directory.
    :return: A safe path, otherwise ``None``.
    r-   c             3   s   | ]}|ˆ kV  qd S )Nr   )r   r   )Úfilenamer   r   r   ð   s    zsafe_join.<locals>.<genexpr>z..z../N)
Ú	posixpathÚnormpathÚanyÚ_os_alt_sepsÚosÚpathÚisabsr:   Úappendr3   )Ú	directoryZ	pathnamesÚpartsr   )rV   r   Ú	safe_joinà   s    	


ra   )rO   rP   )&Ú__doc__r   r!   rJ   r[   rW   Úrandomr   Ústructr   Ú_compatr   r   r   r   r	   r
   r0   r>   ÚpackZ	_pack_intr    r%   r.   Úlistr\   r   ÚaltseprZ   r   r   r,   r5   rG   r?   rR   rU   ra   r   r   r   r   Ú<module>
   s:   
 %
