AnonSec Shell
Server IP : 85.193.89.191  /  Your IP : 18.221.181.79
Web Server : Apache
System : Linux 956367-cx40159.tmweb.ru 3.10.0-1160.105.1.el7.x86_64 #1 SMP Thu Dec 7 15:39:45 UTC 2023 x86_64
User : bitrix ( 600)
PHP Version : 8.1.27
Disable Function : NONE
MySQL : OFF  |  cURL : OFF  |  WGET : ON  |  Perl : ON  |  Python : ON  |  Sudo : ON  |  Pkexec : ON
Directory :  /lib/python2.7/site-packages/passlib/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ HOME ]     

Current File : /lib/python2.7/site-packages/passlib/totp.pyc
�
��Xc@`sdZddlmZmZmZddlmZddlZddlZddl	Z	ddl
Z
ddlZeje
�ZddlZddlZddlZddlZddlZer�ddlmZmZmZmZn,ddlmZmZddlmZmZddlmZy?dd	lmZddl Z!ddl"Z!dd
l#m$Z%[!Wn(e&k
r�ej'd�e(Z%ZnXddl)m*Z*dd
l+m,Z,m-Z-m.Z.m/Z/ddl0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8ddl9m:Z:m;Z;m<Z<ddlm=Z=m>Z>m?Z?m@Z@mAZAmBZBmCZCmDZDmEZEmFZFddlGmHZHmIZIddlJmKZKmLZLmMZMddlNmOZOddddddddgZPejQdddfkrddlmRZRd eRkr	eRjSd �ej'd!�n[RnejTe=d"�ejU�ZVdd#d$gZWd%�ZXd&d'�ZYd(�ZZe[e%�Z\ejTd)�Z]de^fd*��YZ_ej`d+�jaZbej`d,�jcZdd-d.Zede^fd/��YZfde6fd0��YZgde6fd1��YZhd2e:d3 d4�ZidS(5s@passlib.totp -- TOTP / RFC6238 / Google Authenticator utilities.i(tabsolute_importtdivisiontprint_function(tPY3N(turlparset	parse_qsltquotetunquote(RR(RR(twarn(tdefault_backend(tcipherss=can't import 'cryptography' package, totp encryption disabled(texc(t
TokenErrortMalformedTokenErrortInvalidTokenErrortUsedTokenError(t
to_unicodetto_bytestconsteqtgetrandbytestrngt
SequenceMixint	xor_bytest
getrandstr(tBASE64_CHARSt	b32encodet	b32decode(
tutunicodetnative_string_typest
bascii_to_strt	int_typest	num_typestirangetbyte_elem_valuet	UnicodeIOtsuppress_cause(t
hybrid_methodtmemoized_property(tlookup_hashtcompile_hmactpbkdf2_hmac(t
pbkdf2_sha256t	AppWallettTOTPRR
RRt	TotpTokent	TotpMatchiii(t
uses_querytotpauths4registered 'otpauth' scheme with urlparse.uses_querys\s|[-=]iicC`sgxtD]}||s|SqWtd}d}x1tD])}|||kr6|}||}q6q6W|S(sb
    helper for group_string() --
    calculates optimal size of group for given string size.
    i(t_chunk_sizes(tklentsizetbesttrem((s0/usr/lib/python2.7/site-packages/passlib/totp.pyt_get_group_sizeZs



t-c`sDt��}t|��|j��fd�td|��D��S(s�
    reformat string into (roughly) evenly-sized groups, separated by **sep**.
    useful for making tokens & keys easier to read by humans.
    c3`s |]}�||�!VqdS(N((t.0to(R3tvalue(s0/usr/lib/python2.7/site-packages/passlib/totp.pys	<genexpr>tsi(tlenR6tjoinR!(R:tsepR2((R3R:s0/usr/lib/python2.7/site-packages/passlib/totp.pytgroup_stringmscC`s�|dkr7t|t�s3tj|dd��n|St|dd�}tjd|�jd�}|dks||dkr�tj	|j
��S|d	kr�t|�Std
|f��dS(sR
    internal TOTP() helper --
    decodes key according to specified format.
    trawtbytestkeytparamtsutf-8thextbase16tbase32s unknown byte-encoding format: %rN(
t
isinstanceR@RtExpectedTypeErrorRt	_clean_retsubtencodetbase64t	b16decodetupperRt
ValueError(RAtformat((s0/usr/lib/python2.7/site-packages/passlib/totp.pyt
_decode_byteszs
s(?i)^[a-z0-9][a-z0-9_.-]*$cB`s�eZdZdZdZdZdZddddd�Zd�Z	d�Z
ed��Zd�Z
eed��Zd	�Zd
�ZRS(s�

    This class stores application-wide secrets that can be used
    to encrypt & decrypt TOTP keys for storage.
    It's mostly an internal detail, applications usually just need
    to pass ``secrets`` or ``secrets_path`` to :meth:`TOTP.using`.

    .. seealso::

        :ref:`totp-storing-instances` for more details on this workflow.

    Arguments
    =========
    :param secrets:
        Dict of application secrets to use when encrypting/decrypting
        stored TOTP keys.  This should include a secret to use when encrypting
        new keys, but may contain additional older secrets to decrypt
        existing stored keys.

        The dict should map tags -> secrets, so that each secret is identified
        by a unique tag.  This tag will be stored along with the encrypted
        key in order to determine which secret should be used for decryption.
        Tag should be string that starts with regex range ``[a-z0-9]``,
        and the remaining characters must be in ``[a-z0-9_.-]``.

        It is recommended to use something like a incremental counter
        ("1", "2", ...), an ISO date ("2016-01-01", "2016-05-16", ...), 
        or a timestamp ("19803495", "19813495", ...) when assigning tags.

        This mapping be provided in three formats:

        * A python dict mapping tag -> secret
        * A JSON-formatted string containing the dict
        * A multiline string with the format ``"tag: value\ntag: value\n..."``

        (This last format is mainly useful when loading from a text file via **secrets_path**)

        .. seealso:: :func:`generate_secret` to create a secret with sufficient entropy

    :param secrets_path:
        Alternately, callers can specify a separate file where the
        application-wide secrets are stored, using either of the string
        formats described in **secrets**.

    :param default_tag:
        Specifies which tag in **secrets** should be used as the default
        for encrypting new keys. If omitted, the tags will be sorted,
        and the largest tag used as the default.

        if all tags are numeric, they will be sorted numerically;
        otherwise they will be sorted alphabetically.
        this permits tags to be assigned numerically,
        or e.g. using ``YYYY-MM-DD`` dates.

    :param encrypt_cost:
        Optional time-cost factor for key encryption.
        This value corresponds to log2() of the number of PBKDF2
        rounds used.

    .. warning::

        The application secret(s) should be stored in a secure location by
        your application, and each secret should contain a large amount
        of entropy (to prevent brute-force attacks if the encrypted keys
        are leaked).

        :func:`generate_secret` is provided as a convenience helper
        to generate a new application secret of suitable size.

        Best practice is to load these values from a file via **secrets_path**,
        and then have your application give up permission to read this file
        once it's running.

    Public Methods
    ==============
    .. autoattribute:: has_secrets
    .. autoattribute:: default_tag

    Semi-Private Methods
    ====================
    The following methods are used internally by the :class:`TOTP`
    class in order to encrypt & decrypt keys using the provided application
    secrets.  They will generally not be publically useful, and may have their
    API changed periodically.

    .. automethod:: get_secret
    .. automethod:: encrypt_key
    .. automethod:: decrypt_key
    iicC`s|dk	rHt|t�r*t|�}n|dks<t�||_n|dk	r�|dk	rotd��nt|d�j�}n|j	|�}|_
|r|dk	r�|j|�n7td�|D��r�t
|dt�}nt
|�}||_ndS(Nis3'secrets' and 'secrets_path' are mutually exclusivetrtcs`s|]}|j�VqdS(N(tisdigit(R8ttag((s0/usr/lib/python2.7/site-packages/passlib/totp.pys	<genexpr>*sRA(tNoneRGRtinttAssertionErrortencrypt_costt	TypeErrortopentreadt_parse_secretst_secretst
get_secrettalltmaxtdefault_tag(tselftsecretsRaRXtsecrets_path((s0/usr/lib/python2.7/site-packages/passlib/totp.pyt__init__s"	c`s�t}t|t�r�|j�jd	�r<tj|�}q�d|krrd|krrd�}||�}t}q�td��n|d
kr�iSt|t
�r�|j�}n|r�td��nt
�fd�|D��S(sf
        parse 'secrets' parameter

        :returns:
            Dict[tag:str, secret:bytes]
        t[t{s
t:cs`soxh|j�D]Z}|j�}|r
|jd�r
|jdd�\}}|j�|j�fVq
q
WdS(Nt#Rhi(t
splitlineststript
startswithtsplit(tsourcetlineRTtsecret((s0/usr/lib/python2.7/site-packages/passlib/totp.pyt
iter_pairsBs
s"unrecognized secrets string formats+'secrets' must be mapping, or list of itemsc3`s'|]\}}�j||�VqdS(N(t_parse_secret_pair(R8RTR:(Rb(s0/usr/lib/python2.7/site-packages/passlib/totp.pys	<genexpr>Ys(RfRgN(
tTrueRGRtlstripRltjsontloadstFalseRORUtdicttitemsRY(RbRnt
check_typeRq((Rbs0/usr/lib/python2.7/site-packages/passlib/totp.pyR\0s"
		cC`s�t|t�rn1t|t�r0t|�}ntd|f��tj|�shtd|f��nt|t�s�t	|dd|f�}n|s�td|f��n||fS(Nstag must be unicode/string: %rs#tag contains invalid characters: %rRBs	secret %rstag contains empty secret: %r(
RGRRVtstrRYt_tag_retmatchROR@R(RbRTR:((s0/usr/lib/python2.7/site-packages/passlib/totp.pyRr\scC`s
|jdk	S(s2whether at least one application secret is presentN(RaRU(Rb((s0/usr/lib/python2.7/site-packages/passlib/totp.pythas_secretsoscC`s[|j}|std��ny||SWn*tk
rVttd|f���nXdS(sh
        resolve a secret tag to the secret (as bytes).
        throws a KeyError if not found.
        s!no application secrets configuredsunknown secret tag: %rN(R]tKeyErrorR$(RbRTRc((s0/usr/lib/python2.7/site-packages/passlib/totp.pyR^ts	
c	C`s�td	krtd��ntd|d|dd|>dd�}tjtjj|d �tjj|d�t	��}|r�|j
�n	|j�}|j|�|j
�S(
s&
        Internal helper for :meth:`encrypt_key` --
        handles lowlevel encryption/decryption.

        Algorithm details:

        This function uses PBKDF2-HMAC-SHA256 to generate a 32-byte AES key
        and a 16-byte IV from the application secret & random salt.
        It then uses AES-256-CTR to encrypt/decrypt the TOTP key.

        CTR mode was chosen over CBC because the main attack scenario here
        is that the attacker has stolen the database, and is trying to decrypt a TOTP key
        (the plaintext value here).  To make it hard for them, we want every password
        to decrypt to a potentially valid key -- thus need to avoid any authentication
        or padding oracle attacks.  While some random padding construction could be devised
        to make this work for CBC mode, a stream cipher mode is just plain simpler.
        OFB/CFB modes would also work here, but seeing as they have malleability
        and cyclic issues (though remote and barely relevant here),
        CTR was picked as the best overall choice.
        sITOTP encryption requires 'cryptography' package (https://cryptography.io)tsha256tsalttroundsitkeyleni0i N(t_cg_ciphersRUtRuntimeErrorR)tCiphert
algorithmstAEStmodestCTRt_cg_default_backendt	decryptort	encryptortupdatetfinalize(R:RpR�tcosttdecrypttkeyivtciphertctx((s0/usr/lib/python2.7/site-packages/passlib/totp.pyt_cipher_aes_key�s%cC`s�|std��ntt|j�}|j}|j}|sNtd��n|j||j|�||�}t	ddd|d|dt
|�dt
|��S(	s0
        Helper used to encrypt TOTP keys for storage.

        :param key:
            TOTP key to encrypt, as raw bytes.

        :returns:
            dict containing encrypted TOTP key & configuration parameters.
            this format should be treated as opaque, and potentially subject
            to change, though it is designed to be easily serialized/deserialized
            (e.g. via JSON).

        .. note::

            This function requires installation of the external
            `cryptography <https://cryptography.io>`_ package.

        To give some algorithm details:  This function uses AES-256-CTR to encrypt
        the provided data.  It takes the application secret and randomly generated salt,
        and uses PBKDF2-HMAC-SHA256 to combine them and generate the AES key & IV.
        sno key provideds8no application secrets configured, can't encrypt OTP keytvitctttstk(RORRt	salt_sizeRXRaRYR�R^RxR(RbRAR�R�RTtckey((s0/usr/lib/python2.7/site-packages/passlib/totp.pytencrypt_key�s		!c	C`s�t|t�std��n|jdd
�}t}|dkrN|j}ntd|f��|d}|d}|dt|d�d	|j	|�d
t|d�d|�}||j
ks�||jkr�t}n||fS(s�
        Helper used to decrypt TOTP keys from storage format.
        Consults configured secrets to decrypt key.

        :param source:
            source object, as returned by :meth:`encrypt_key`.

        :returns:
            ``(key, needs_recrypt)`` --

            **key** will be the decrypted key, as bytes.

            **needs_recrypt** will be a boolean flag indicating
            whether encryption cost or default tag is too old,
            and henace that key needs re-encrypting before storing.

        .. note::

            This function requires installation of the external
            `cryptography <https://cryptography.io>`_ package.
        s'enckey' must be dictionaryR�is+missing / unrecognized 'enckey' version: %rR�R�R:R�RpR�R�R�N(
RGRxRYtgetRURwR�RORR^RXRaRs(Rbtenckeytversiont
needs_recryptt_cipher_keyRTR�RA((s0/usr/lib/python2.7/site-packages/passlib/totp.pytdecrypt_key�s"

		N(t__name__t
__module__t__doc__R�RXRUR]RaReR\RrtpropertyR~R^tstaticmethodRwR�R�R�(((s0/usr/lib/python2.7/site-packages/passlib/totp.pyR+�sX	(	,		%	!s>Qs>IticB`s�eZdZdZdZZd.Zej	Z
d.Zd.Zd.Z
dZdZd.Zd.ZdZeZed.d.d.d.d.d.d��Zed��Zd.ded.d.d.d.d.d.ed	�
Zed
d��Zed��Zed
��Zed��Zejd��Zed��Z e jd��Z ed��Z!ed��Z"ddd�Z#ed��Z$d�Z%d�Z&e'd��Z(d.d�Z)d�Z*ed��Z+d.dd
d.d�Z,d.d�Z-ed��Z.ed ��Z/ed!��Z0ed"��Z1ed.d.d.d.d.d.d#��Z2ed$��Z3ed%��Z4d.d.d&�Z5d'�Z6ed(��Z7d.d)�Z8ed*��Z9ed+��Z:ed,��Z;d.d-�Z<RS(/s9
    Helper for generating and verifying TOTP codes.

    Given a secret key and set of configuration options, this object
    offers methods for token generation, token validation, and serialization.
    It can also be used to track important persistent TOTP state,
    such as the last counter used.

    This class accepts the following options
    (only **key** and **format** may be specified as positional arguments).

    :arg str key:
        The secret key to use. By default, should be encoded as
        a base32 string (see **format** for other encodings).

        Exactly one of **key** or ``new=True`` must be specified.

    :arg str format:
        The encoding used by the **key** parameter. May be one of:
        ``"base32"`` (base32-encoded string),
        ``"hex"`` (hexadecimal string), or ``"raw"`` (raw bytes).
        Defaults to ``"base32"``.

    :param bool new:
        If ``True``, a new key will be generated using :class:`random.SystemRandom`.

        Exactly one ``new=True`` or **key** must be specified.

    :param str label:
        Label to associate with this token when generating a URI.
        Displayed to user by most OTP client applications (e.g. Google Authenticator),
        and typically has format such as ``"John Smith"`` or ``"jsmith@webservice.example.org"``.
        Defaults to ``None``.
        See :meth:`to_uri` for details.

    :param str issuer:
        String identifying the token issuer (e.g. the domain name of your service).
        Used internally by some OTP client applications (e.g. Google Authenticator) to distinguish entries
        which otherwise have the same label.
        Optional but strongly recommended if you're rendering to a URI.
        Defaults to ``None``.
        See :meth:`to_uri` for details.

    :param int size:
        Number of bytes when generating new keys. Defaults to size of hash algorithm (e.g. 20 for SHA1).

        .. warning::

            Overriding the default values for ``digits``, ``period``, or ``alg`` may
            cause problems with some OTP client programs (such as Google Authenticator),
            which may have these defaults hardcoded.

    :param int digits:
        The number of digits in the generated / accepted tokens. Defaults to ``6``.
        Must be in range [6 .. 10].

        .. rst-class:: inline-title
        .. caution::
           Due to a limitation of the HOTP algorithm, the 10th digit can only take on values 0 .. 2,
           and thus offers very little extra security.

    :param str alg:
        Name of hash algorithm to use. Defaults to ``"sha1"``.
        ``"sha256"`` and ``"sha512"`` are also accepted, per :rfc:`6238`.

    :param int period:
        The time-step period to use, in integer seconds. Defaults to ``30``.

    ..
        See the passlib documentation for a full list of attributes & methods.
    i
iitsha1ic	`sctd|fi���fd�}|dk	rE|d|��_n|dk	rf|d|��_n|dk	r�|d|��_n|dk	r�|d|��_n|r�t|��_|rtd��qn?|dk	rt	|t�st
j|td��n|�_n|dk	r_t	|�t�rA|�d	ksMt
d
��t|��_n�S(s:
        Dynamically create subtype of :class:`!TOTP` class
        which has the specified defaults set.

        :parameters: **digits, alg, period, issuer**:

            All these options are the same as in the :class:`TOTP` constructor,
            and the resulting class will use any values you specify here
            as the default for all TOTP instances it creates.

        :param wallet:
            Optional :class:`AppWallet` that will be used for encrypting/decrypting keys.

        :param secrets, secrets_path, encrypt_cost:

            If specified, these options will be passed to the :class:`AppWallet` constructor,
            allowing you to directly specify the secret keys that should be used
            to encrypt & decrypt stored keys.

        :returns:
            subclass of :class:`!TOTP`.

        This method is useful for creating a TOTP class configured
        to use your application's secrets for encrypting & decrypting
        keys, as well as create new keys using it's desired configuration defaults.

        As an example::

            >>> # your application can create a custom class when it initializes
            >>> from passlib.totp import TOTP, generate_secret
            >>> TotpFactory = TOTP.using(secrets={"1": generate_secret()})

            >>> # subsequent TOTP objects created from this factory
            >>> # will use the specified secrets to encrypt their keys...
            >>> totp = TotpFactory.new()
            >>> totp.to_dict()
            {'enckey': {'c': 14,
              'k': 'H77SYXWORDPGVOQTFRR2HFUB3C45XXI7',
              's': 'G5DOQPIHIBUM2OOHHADQ',
              't': '1',
              'v': 1},
             'type': 'totp',
             'v': 1}

        .. seealso:: :ref:`totp-creation` and :ref:`totp-storing-instances` tutorials for a usage example
        R,c`s8tdtdd�}|||<�|�}t||�S(s�
            helper which uses constructor to validate parameter value.
            it returns corresponding attribute, so we use normalized value.
            RARPR?(Rxt
_DUMMY_KEYtgetattr(tattrR:tkwdstobj(tsubcls(s0/usr/lib/python2.7/site-packages/passlib/totp.pyt
norm_param�s
tdigitstalgtperiodtissuers6'wallet' and 'secrets' keywords are mutually exclusivetwalletis1now() function must return non-negative int/floatN(ttypeRUR�R�R�R�R+R�RYRGRRHR RWR�tnow(	tclsR�R�R�R�R�R�R�R�((R�s0/usr/lib/python2.7/site-packages/passlib/totp.pytusing�s.8
$	cK`s|dt|�S(sY
        convenience alias for creating new TOTP key, same as ``TOTP(new=True)``
        tnew(Rs(R�R�((s0/usr/lib/python2.7/site-packages/passlib/totp.pyR��sRFcK`sPtt|�j|�|
r(|
|_nt|p7|j�}|j|_|j}
|
dkrqtd|��n|r�|r�t	d��n|dkr�|
}n||
kr�td|
��ntt
|�|_nH|s�t	d��n3|dkr||_n|rt||�|_nt|j�|jkrpd|j}|rWt|��qpt|tjdd	�n|dkr�|j}nt|t�s�t	d
t|���n|dks�|dkr�td
��n||_|r�|j|�||_n|	r|j|	�|	|_n|dk	rL|j|ddd	�||_ndS(Nis%r hash digest too smalls+'key' and 'new=True' are mutually exclusives+'size' should be less than digest size (%d)s4must specify either an existing 'key', or 'new=True't	encrypteds5for security purposes, secret key must be >= %d bytest
stacklevelis#digits must be an integer, not a %rii
sdigits must in range(6,11)R�tminval( tsuperR,RetchangedR'R�tnametdigest_sizeR�RYRURORRRAt
encrypted_keyRQR;t
_min_key_sizeRRtPasslibSecurityWarningR�RGRR�t_check_labeltlabelt
_check_issuerR�t
_check_serialR�(RbRARPR�R�R�R3R�R�R�R�R�tinfoR�tmsg((s0/usr/lib/python2.7/site-packages/passlib/totp.pyResX		

	

icC`sPt|t�s'tj|d|��n||krLtd||f��ndS(sR
        check that serial value (e.g. 'counter') is non-negative integer
        RVs%s must be >= %dN(RGRRRHRO(R:RBR�((s0/usr/lib/python2.7/site-packages/passlib/totp.pyR�QscC`s%|r!d|kr!td��ndS(sQ
        check that label doesn't contain chars forbidden by KeyURI spec
        Rhslabel may not contain ':'N(RO(R�((s0/usr/lib/python2.7/site-packages/passlib/totp.pyR�[scC`s%|r!d|kr!td��ndS(sR
        check that issuer doesn't contain chars forbidden by KeyURI spec
        Rhsissuer may not contain ':'N(RO(R�((s0/usr/lib/python2.7/site-packages/passlib/totp.pyR�cscC`s|jS(s)
        secret key as raw bytes
        (t_key(Rb((s0/usr/lib/python2.7/site-packages/passlib/totp.pyRArscC`sDt|t�s'tj|td��n||_d|_|_dS(NRA(RGR@RRHR�RUt_encrypted_keyt_keyed_hmac(RbR:((s0/usr/lib/python2.7/site-packages/passlib/totp.pyRAys	cC`sS|j}|dkrO|j}|s3td��n|j|j�}|_n|S(s�
        secret key, encrypted using application secret.
        this match the output of :meth:`AppWallet.encrypt_key`,
        and should be treated as an opaque json serializable object.
        s6no application secrets present, can't encrypt TOTP keyN(R�RUR�RYR�RA(RbR�R�((s0/usr/lib/python2.7/site-packages/passlib/totp.pyR��s		cC`sU|j}|std��n|j|�\|_}|rHt|_n	||_dS(Ns6no application secrets present, can't decrypt TOTP key(R�RYR�RARsR�R�(RbR:R�R�((s0/usr/lib/python2.7/site-packages/passlib/totp.pyR��s	cC`sttj|j��j�S(s:
        secret key encoded as hexadecimal string
        (RRLt	b16encodeRAtlower(Rb((s0/usr/lib/python2.7/site-packages/passlib/totp.pythex_key�scC`s
t|j�S(s5
        secret key encoded as base32 string
        (RRA(Rb((s0/usr/lib/python2.7/site-packages/passlib/totp.pyt
base32_key�sR7cC`sk|dks|dkr$|j}n+|dkr<|j}ntd|f��|rgt||�}n|S(s�
        pretty-print the secret key.

        This is mainly useful for situations where the user cannot get the qrcode to work,
        and must enter the key manually into their TOTP client. It tries to format
        the key in a manner that is easier for humans to read.

        :param format:
            format to output secret key. ``"hex"`` and ``"base32"`` are both accepted.

        :param sep:
            separator to insert to break up key visually.
            can be any of ``"-"`` (the default), ``" "``, or ``False`` (no separator).

        :return:
            key as native string.

        Usage example::

            >>> t = TOTP('s3jdvb7qd2r7jpxx')
            >>> t.pretty_key()
            'S3JD-VB7Q-D2R7-JPXX'
        RDRERFs unknown byte-encoding format: %r(R�R�ROR>(RbRPR=RA((s0/usr/lib/python2.7/site-packages/passlib/totp.pyt
pretty_key�scC`s�t|t�r|St|t�r,t|�S|dkrHt|j��St|d�rjtj|j	��St
j|dd��dS(ss
        Normalize time value to unix epoch seconds.

        :arg time:
            Can be ``None``, :class:`!datetime`,
            or unix epoch timestamp as :class:`!float` or :class:`!int`.
            If ``None``, uses current system time.
            Naive datetimes are treated as UTC.

        :returns:
            unix epoch timestamp as :class:`int`.
        tutctimetuplesint, float, or datetimettimeN(RGRtfloatRVRUR�thasattrtcalendarttimegmR�RRH(R�R�((s0/usr/lib/python2.7/site-packages/passlib/totp.pytnormalize_time�s
cC`s||jS(sI
        convert timestamp to HOTP counter using :attr:`period`.
        (R�(RbR�((s0/usr/lib/python2.7/site-packages/passlib/totp.pyt_time_to_counter�scC`s||jS(sI
        convert HOTP counter to timestamp using :attr:`period`.
        (R�(Rbtcounter((s0/usr/lib/python2.7/site-packages/passlib/totp.pyt_counter_to_time�scC`s�|j}t|t�r1td�||f}nEt|dd�}tjtd�|�}|j�svtd��nt	|�|kr�td|��n|S(s�
        Normalize OTP token representation:
        strips whitespace, converts integers to a zero-padded string,
        validates token content & number of digits.

        This is a hybrid method -- it can be called at the class level,
        as ``TOTP.normalize_token()``, or the instance level as ``TOTP().normalize_token()``.
        It will normalize to the instance-specific number of :attr:`~TOTP.digits`,
        or use the class default.

        :arg token:
            token as ascii bytes, unicode, or an integer.

        :raises ValueError:
            if token has wrong number of digits, or contains non-numeric characters.

        :returns:
            token as :class:`!unicode` string, containing only digits 0-9.
        s%0*dRBttokenRCs&Token must contain only the digits 0-9s!Token must have exactly %d digits(
R�RGRRRRIRJRSR
R;(tself_or_clsR�R�((s0/usr/lib/python2.7/site-packages/passlib/totp.pytnormalize_tokens	cC`sX|j|�}|j|�}|dkr9td��n|j|�}t|||�S(s�
        Generate token for specified time
        (uses current time if none specified).

        :arg time:
            Can be ``None``, a :class:`!datetime`,
            or class:`!float` / :class:`!int` unix epoch timestamp.
            If ``None`` (the default), uses current system time.
            Naive datetimes are treated as UTC.

        :returns:

            A :class:`TotpToken` instance, which can be treated
            as a sequence of ``(token, expire_time)`` -- see that class
            for more details.

        Usage example::

            >>> # generate a new token, wrapped in a TotpToken instance...
            >>> otp = TOTP('s3jdvb7qd2r7jpxx')
            >>> otp.generate(1419622739)
            <TotpToken token='897212' expire_time=1419622740>

            >>> # when you just need the token...
            >>> otp.generate(1419622739).token
            '897212'
        istimestamp must be >= 0(R�R�ROt	_generateR-(RbR�R�R�((s0/usr/lib/python2.7/site-packages/passlib/totp.pytgenerate0scC`s8t|t�std��|dks3td��|j}|dkrgt|j|j�}|_n|t|��}|j	j
}t|�|ks�td��|dks�td��t|d�d@}t
|||d	!�dd
@}|j}d|kodknstd��td
�||f|S(s�
        base implementation of HOTP token generation algorithm.

        :arg counter: HOTP counter, as non-negative integer
        :returns: token as unicode string
        scounter must be integeriscounter must be non-negatives digest_size: sanity check failedis"digest_size: sanity check 2 failedi����iii���isdigits: sanity check faileds%0*dN(RGRRWR�RUR(R�RAt_pack_uint64tdigest_infoR�R;R"t_unpack_uint32R�R(RbR�t
keyed_hmactdigestR�toffsetR:R�((s0/usr/lib/python2.7/site-packages/passlib/totp.pyR�Ss		(cK`s|j|�j||�S(s�
        Convenience wrapper around :meth:`TOTP.from_source` and :meth:`TOTP.match`.

        This parses a TOTP key & configuration from the specified source,
        and tries and match the token.
        It's designed to parallel the :meth:`passlib.ifc.PasswordHash.verify` method.

        :param token:
            Token string to match.

        :param source:
            Serialized TOTP key.
            Can be anything accepted by :meth:`TOTP.from_source`.

        :param \*\*kwds:
            All additional keywords passed to :meth:`TOTP.match`.

        :return:
            A :class:`TotpMatch` instance, or raises a :exc:`TokenError`.
        (tfrom_sourceR}(R�R�RnR�((s0/usr/lib/python2.7/site-packages/passlib/totp.pytverifyusc
C`s�|j|�}|j|d�||}|dkr>d}nt||j||��}|j||�d}|j|||�}	|	|ks�td��|	|kr�td|d|j��nt	||	||�S(sP
        Match TOTP token against specified timestamp.
        Searches within a window before & after the provided time,
        in order to account for transmission delay and small amounts of skew in the client's clock.

        :arg token:
            Token to validate.
            may be integer or string (whitespace and hyphens are ignored).

        :param time:
            Unix epoch timestamp, can be any of :class:`!float`, :class:`!int`, or :class:`!datetime`.
            if ``None`` (the default), uses current system time.
            *this should correspond to the time the token was received from the client*.

        :param int window:
            How far backward and forward in time to search for a match.
            Measured in seconds. Defaults to ``30``.  Typically only useful if set
            to multiples of :attr:`period`.

        :param int skew:
            Adjust timestamp by specified value, to account for excessive
            client clock skew. Measured in seconds. Defaults to ``0``.

            Negative skew (the common case) indicates transmission delay,
            and/or that the client clock is running behind the server.

            Positive skew indicates the client clock is running ahead of the server
            (and by enough that it cancels out any negative skew added by
            the transmission delay).

            You should ensure the server clock uses a reliable time source such as NTP,
            so that only the client clock's inaccuracy needs to be accounted for.

            This is an advanced parameter that should usually be left at ``0``;
            The **window** parameter is usually enough to account
            for any observed transmission delay.

        :param last_counter:
            Optional value of last counter value that was successfully used.
            If specified, verify will never search earlier counters,
            no matter how large the window is.

            Useful when client has previously authenticated,
            and thus should never provide a token older than previously
            verified value.

        :raises ~passlib.exc.TokenError:

            If the token is malformed, fails to match, or has already been used.

        :returns TotpMatch:

            Returns a :class:`TotpMatch` instance on successful match.
            Can be treated as tuple of ``(counter, time)``.
            Raises error if token is malformed / can't be verified.

        Usage example::

            >>> totp = TOTP('s3jdvb7qd2r7jpxx')

            >>> # valid token for this time period
            >>> totp.match('897212', 1419622729)
            <TotpMatch counter=47320757 time=1419622729 cache_seconds=60>

            >>> # token from counter step 30 sec ago (within allowed window)
            >>> totp.match('000492', 1419622729)
            <TotpMatch counter=47320756 time=1419622729 cache_seconds=60>

            >>> # invalid token -- token from 60 sec ago (outside of window)
            >>> totp.match('760389', 1419622729)
            Traceback:
                ...
            InvalidTokenError: Token did not match
        twindowi����is*sanity check failed: counter went backwardtexpire_timeN(
R�R�RUR`R�t_find_matchRWRR�R.(
RbR�R�R�tskewtlast_countertclient_timetstarttendR�((s0/usr/lib/python2.7/site-packages/passlib/totp.pyR}�sK
	cC`s�|j|�}|dkr$d}n||kr<t��n|j}|dkpZ||krwt|||��rw|S|}x3||kr�t|||��r�|S|d7}q�Wt��dS(sw
        helper for verify() --
        returns counter value within specified range that matches token.

        :arg token:
            token value to match (will be normalized internally)

        :arg start:
            starting counter value to check

        :arg end:
            check up to (but not including) this counter value

        :arg expected:
            optional expected value where search should start,
            to help speed up searches.

        :raises ~passlib.exc.TokenError:
            If the token is malformed, or fails to verify.

        :returns:
            counter value that matched
        iiN(R�RR�RUR(RbR�R�R�texpectedR�R�((s0/usr/lib/python2.7/site-packages/passlib/totp.pyR��s		.cC`s�t|t�r:|j|jkr%|S|jdt�}nt|t�rV|j|�St|dd�}|jd�r�|j	|�S|j
|�SdS(s�
        Load / create a TOTP object from a serialized source.
        This acts as a wrapper for the various deserialization methods:

        * TOTP URIs are handed off to :meth:`from_uri`
        * Any other strings are handed off to :meth:`from_json`
        * Dicts are handed off to :meth:`from_dict`

        :param source:
            Serialized TOTP object.

        :raises ValueError:
            If the key has been encrypted, but the application secret isn't available;
            or if the string cannot be recognized, parsed, or decoded.

            See :meth:`TOTP.using()` for how to configure application secrets.

        :returns:
            a :class:`TOTP` instance.
        tencryptRBstotp sources
otpauth://N(RGR,R�tto_dictRwRxt	from_dictRRltfrom_urit	from_json(R�Rn((s0/usr/lib/python2.7/site-packages/passlib/totp.pyR�'s

cC`sbt|dd�j�}t|�}|jdkrE|jd��n|j|j�|j|�S(s<
        create an OTP instance from a URI (such as returned by :meth:`to_uri`).

        :returns:
            :class:`TOTP` instance.

        :raises ValueError:
            if the uri cannot be parsed or contains errors.

        .. seealso:: :ref:`totp-configuring-clients` tutorial for a usage example
        RBturiR0swrong uri scheme(RRkRtschemet_uri_parse_errort_check_otp_typetnetloct_from_parsed_uri(R�R�tresult((s0/usr/lib/python2.7/site-packages/passlib/totp.pyR�OscC`s?|dkrtS|dkr+td��ntd|��dS(sg
        validate otp URI type is supported.
        returns True or raises appropriate error.
        ttotpthotpsHOTP not supportedsunknown otp type: %rN(RstNotImplementedErrorRO(R�R�((s0/usr/lib/python2.7/site-packages/passlib/totp.pyR�fs
cC`sj|j}|jd�r=t|�dkr=t|d�}n|jd��d|kr�y|jd�\}}Wq�tk
r�|jd��q�Xnd
}|r�|j�p�d
}nt	d|�}xIt
|j�D]8\}}||kr|jd|��n|||<q�W|rWd|kr2||d<qW|d|krW|jd	��qWn||j|��S(s�
        internal from_uri() helper --
        handles parsing a validated TOTP URI

        :param result:
            a urlparse() instance

        :returns:
            cls instance
        t/is
missing labelRhsmalformed labelR�sduplicate parameter (%r)R�sconflicting issuer identifiersN(
tpathRlR;RR�RmRORURkRxRtqueryt_adapt_uri_params(R�R�R�R�tparamsR�R�((s0/usr/lib/python2.7/site-packages/passlib/totp.pyR�rs.	!

c		K`s�|std��|s*|jd��ntd|d|d|dd�}|rj|j|d�|d<n|r}||d	<n|r�|j|d
�|d
<n|r�td||ftj�n|S(sY
        from_uri() helper --
        converts uri params into constructor args.
        s"from_uri() failed to provide labelsmissing 'secret' parameterR�R�RARPRFR�R�R�s4%s: unexpected parameters encountered in otp uri: %r(RWR�Rxt_uri_parse_intRRtPasslibRuntimeWarning(	R�R�RpR�R�t	algorithmR�textraR�((s0/usr/lib/python2.7/site-packages/passlib/totp.pyR�s!
cC`std|f�S(s8uri parsing helper -- creates preformatted error messagesInvalid otpauth uri: %s(RO(treason((s0/usr/lib/python2.7/site-packages/passlib/totp.pyR��scC`s9yt|�SWn$tk
r4|jd|��nXdS(s#uri parsing helper -- int() wrappersMalformed %r parameterN(RVROR�(R�RnRB((s0/usr/lib/python2.7/site-packages/passlib/totp.pyR�s
cC`s�|dkr|j}n|s-td��n|j|�t|d�}|j�}|dkrm|j}n|r�|j|�|jd|f�nt	d�j
d�|D��}|s�td��t	d�||fS(	s1
        Serialize key and configuration into a URI, per
        Google Auth's `KeyUriFormat <http://code.google.com/p/google-authenticator/wiki/KeyUriFormat>`_.

        :param str label:
            Label to associate with this token when generating a URI.
            Displayed to user by most OTP client applications (e.g. Google Authenticator),
            and typically has format such as ``"John Smith"`` or ``"jsmith@webservice.example.org"``.

            Defaults to **label** constructor argument. Must be provided in one or the other location.
            May not contain ``:``.

        :param str issuer:
            String identifying the token issuer (e.g. the domain or canonical name of your service).
            Optional but strongly recommended if you're rendering to a URI.
            Used internally by some OTP client applications (e.g. Google Authenticator) to distinguish entries
            which otherwise have the same label.

            Defaults to **issuer** constructor argument, or ``None``.
            May not contain ``:``.

        :raises ValueError:
            * if a label was not provided either as an argument, or in the constructor.
            * if the label or issuer contains invalid characters.

        :returns:
            all the configuration information for this OTP token generator,
            encoded into a URI.

        These URIs are frequently converted to a QRCode for transferring
        to a TOTP client application such as Google Auth.
        Usage example::

            >>> from passlib.totp import TOTP
            >>> tp = TOTP('s3jdvb7qd2r7jpxx')
            >>> uri = tp.to_uri("user@example.org", "myservice.another-example.org")
            >>> uri
            'otpauth://totp/user@example.org?secret=S3JDVB7QD2R7JPXX&issuer=myservice.another-example.org'
        s<a label must be specified as argument, or in the constructort@R�t&cs`s4|]*\}}td�|t|d�fVqdS(s%s=%sRCN(RR(R8RAR:((s0/usr/lib/python2.7/site-packages/passlib/totp.pys	<genexpr>ssargstr should never be emptysotpauth://totp/%s?%sN(RUR�ROR�Rt_to_uri_paramsR�R�tappendRR<RW(RbR�R�targstargstr((s0/usr/lib/python2.7/site-packages/passlib/totp.pytto_uri�s )


cC`s�d|jfg}|jdkr@|jd|jj�f�n|jdkrn|jdt|j�f�n|jdkr�|jdt|j�f�n|S(s+return list of (key, param) entries for URIRpR�R
iR�iR�(R�R�RRNR�R{R�(RbR((s0/usr/lib/python2.7/site-packages/passlib/totp.pyRscC`s(t|dd�}|jtj|��S(sn
        Load / create an OTP object from a serialized json string
        (as generated by :meth:`to_json`).

        :arg json:
            Serialized output from :meth:`to_json`, as unicode or ascii bytes.

        :raises ValueError:
            If the key has been encrypted, but the application secret isn't available;
            or if the string cannot be recognized, parsed, or decoded.

            See :meth:`TOTP.using()` for how to configure application secrets.

        :returns:
            a :class:`TOTP` instance.

        .. seealso:: :ref:`totp-storing-instances` tutorial for a usage example
        RBsjson source(RR�RuRv(R�Rn((s0/usr/lib/python2.7/site-packages/passlib/totp.pyR�scC`s+|jd|�}tj|dtdd�S(s
        Serialize configuration & internal state to a json string,
        mainly useful for persisting client-specific state in a database.
        All keywords passed to :meth:`to_dict`.

        :returns:
            json string containing serializes configuration & state.
        R�t	sort_keyst
separatorst,Rh(RRh(R�RutdumpsRs(RbR�tstate((s0/usr/lib/python2.7/site-packages/passlib/totp.pytto_json5s	cC`sAt|t�sd|kr.|jd��n||j|��S(sU
        Load / create a TOTP object from a dictionary
        (as generated by :meth:`to_dict`)

        :param source:
            dict containing serialized TOTP key & configuration.

        :raises ValueError:
            If the key has been encrypted, but the application secret isn't available;
            or if the dict cannot be recognized, parsed, or decoded.

            See :meth:`TOTP.using()` for how to configure application secrets.

        :returns:
            A :class:`TOTP` instance.

        .. seealso:: :ref:`totp-storing-instances` tutorial for a usage example
        R�sunrecognized format(RGRxt_dict_parse_errort_adapt_dict_kwds(R�Rn((s0/usr/lib/python2.7/site-packages/passlib/totp.pyR�EscK`s�|j|�st�|jdd
�}|sL||jksL||jkre|jd|f��n||jkr�t|d<nd|kr�d|ks�t�|jd|jd�dd�nd|kr�|jd��n|jd	d
�|S(st
        Internal helper for .from_json() --
        Adapts serialized json dict into constructor keywords.
        R�s missing/unsupported version (%r)R�R�RARPR�smissing 'enckey' / 'key'R�N(	R�RWtpopRUtmin_json_versiontjson_versionRRsR�(R�R�R�tver((s0/usr/lib/python2.7/site-packages/passlib/totp.pyR]s	%
"cC`std|f�S(s9dict parsing helper -- creates preformatted error messagesInvalid totp data: %s(RO(R((s0/usr/lib/python2.7/site-packages/passlib/totp.pyR|scC`s
td|jdd�}|jdkr7|j|d<n|jdkrV|j|d<n|jdkru|j|d	<n|jr�|j|d
<n|j}|r�|t|�jkr�||d<n|dkr�|j	}|o�|j
}n|r�|j|d<n
|j|d
<|S(sw
        Serialize configuration & internal state to a dict,
        mainly useful for persisting client-specific state in a database.

        :param encrypt:
            Whether to output should be encrypted.

            * ``None`` (the default) -- uses encrypted key if application
              secrets are available, otherwise uses plaintext key.
            * ``True`` -- uses encrypted key, or raises TypeError
              if application secret wasn't provided to OTP constructor.
            * ``False`` -- uses raw key.

        :returns:
            dictionary, containing basic (json serializable) datatypes.
        R�R�RR�R�iR�iR�R�R�R�RAN(
RxRR�R�R�R�R�R�RUR�R~R�R�(RbR�RR�R�((s0/usr/lib/python2.7/site-packages/passlib/totp.pyR��s&		
	
N(=R�R�R�R�RRRUR�t_timeR�R�R�R�R�R�R�R�R�R�RwR�tclassmethodR�R�ReR�R�R�R�R�RAtsetterR�R�R�R�R�R�R�R%R�R�R�R�R}R�R�R�R�R�RR�RRRR�RR�RRR�(((s0/usr/lib/python2.7/site-packages/passlib/totp.pyR,stG
			gJ	
&		.#	"b8(0	D	cB`sweZdZdZdZdZd�Zed��Z	ed��Z
ed��Zed��Z
d�Zd�ZRS(	s@
    Object returned by :meth:`TOTP.generate`.
    It can be treated as a sequence of ``(token, expire_time)``,
    or accessed via the following attributes:

    .. autoattribute:: token
    .. autoattribute:: expire_time
    .. autoattribute:: counter
    .. autoattribute:: remaining
    .. autoattribute:: valid
    cC`s||_||_||_dS(su
        .. warning::
            the constructor signature is an internal detail, and is subject to change.
        N(RR�R�(RbRR�R�((s0/usr/lib/python2.7/site-packages/passlib/totp.pyRe�s		cC`s|jj|j�S(s9Timestamp marking beginning of period when token is valid(RR�R�(Rb((s0/usr/lib/python2.7/site-packages/passlib/totp.pyt
start_time�scC`s|jj|jd�S(s3Timestamp marking end of period when token is validi(RR�R�(Rb((s0/usr/lib/python2.7/site-packages/passlib/totp.pyR��scC`std|j|jj��S(s.number of (float) seconds before token expiresi(R`R�RR�(Rb((s0/usr/lib/python2.7/site-packages/passlib/totp.pyt	remaining�scC`s
t|j�S(swhether token is still valid(tboolR$(Rb((s0/usr/lib/python2.7/site-packages/passlib/totp.pytvalid�scC`s|j|jfS(N(R�R�(Rb((s0/usr/lib/python2.7/site-packages/passlib/totp.pyt	_as_tuple�scC`s,|jrdnd}d|j|j|fS(NRCs expireds'<TotpToken token='%s' expire_time=%d%s>(R$R�R�(Rbtexpired((s0/usr/lib/python2.7/site-packages/passlib/totp.pyt__repr__�sN(R�R�R�RURR�R�ReR&R#R�R�R$R&R'R)(((s0/usr/lib/python2.7/site-packages/passlib/totp.pyR-�s			cB`s�eZdZdZdZdZdZdd�Ze	d��Z
e	d��Ze	d��Ze	d��Z
e	d��Zd	�Zd
�ZRS(s�
    Object returned by :meth:`TOTP.match` and :meth:`TOTP.verify` on a successful match.

    It can be treated as a sequence of ``(counter, time)``,
    or accessed via the following attributes:

    .. autoattribute:: counter
        :annotation: = 0

    .. autoattribute:: time
        :annotation: = 0

    .. autoattribute:: expected_counter
        :annotation: = 0

    .. autoattribute:: skipped
        :annotation: = 0

    .. autoattribute:: expire_time
        :annotation: = 0

    .. autoattribute:: cache_seconds
        :annotation: = 60

    .. autoattribute:: cache_time
        :annotation: = 0

    This object will always have a ``True`` boolean value.
    iicC`s(||_||_||_||_dS(su
        .. warning::
            the constructor signature is an internal detail, and is subject to change.
        N(RR�R�R�(RbRR�R�R�((s0/usr/lib/python2.7/site-packages/passlib/totp.pyRes			cC`s|jj|j�S(s7
        Counter value expected for timestamp.
        (RR�R�(Rb((s0/usr/lib/python2.7/site-packages/passlib/totp.pytexpected_counter(scC`s|j|jS(s�
        How many steps were skipped between expected and actual matched counter
        value (may be positive, zero, or negative).
        (R�R*(Rb((s0/usr/lib/python2.7/site-packages/passlib/totp.pytskipped/scC`s|jj|jd�S(s3Timestamp marking end of period when token is validi(RR�R�(Rb((s0/usr/lib/python2.7/site-packages/passlib/totp.pyR�<scC`s|jj|jS(s�
        Number of seconds counter should be cached
        before it's guaranteed to have passed outside of verification window.
        (RR�R�(Rb((s0/usr/lib/python2.7/site-packages/passlib/totp.pyt
cache_secondsAscC`s|j|jS(s[
        Timestamp marking when counter has passed outside of verification window.
        (R�R�(Rb((s0/usr/lib/python2.7/site-packages/passlib/totp.pyt
cache_timeKscC`s|j|jfS(N(R�R�(Rb((s0/usr/lib/python2.7/site-packages/passlib/totp.pyR'RscC`s |j|j|jf}d|S(Ns/<TotpMatch counter=%d time=%d cache_seconds=%d>(R�R�R,(RbR((s0/usr/lib/python2.7/site-packages/passlib/totp.pyR)UsN(R�R�R�RURR�R�R�ReR&R*R+R�R,R-R'R)(((s0/usr/lib/python2.7/site-packages/passlib/totp.pyR.�s


	ii����cC`se|dkst�t|�dks*t�ttj|tjdt|����}tt||�S(s�
    generate a random string suitable for use as an
    :class:`AppWallet` application secret.

    :param entropy:
        number of bits of entropy (controls size/complexity of password).
    iii(RWR;RVtmathtceiltlogRR(tentropytcharsettcount((s0/usr/lib/python2.7/site-packages/passlib/totp.pytgenerate_secret]s+(jR�t
__future__RRRtpasslib.utils.compatRRLtcollectionsR�Rutloggingt	getLoggerR�R0R.tstructtsysR�R treturllib.parseRRRRturllibtwarningsRtcryptography.hazmat.backendsR	R�t1cryptography.hazmat.primitives.ciphers.algorithmstcryptographyt,cryptography.hazmat.primitives.ciphers.modestcryptography.hazmat.primitivesR
R�tImportErrortdebugRUtpasslibRtpasslib.excRR
RRt
passlib.utilsRRRRRRRRtpasslib.utils.binaryRRRRRRRRR R!R"R#R$tpasslib.utils.decorR%R&tpasslib.crypto.digestR'R(R)tpasslib.hashR*t__all__tversion_infoR/RtcompiletURIR1R6R>RQR%tAES_SUPPORTR|tobjectR+tStructtpackR�tunpackR�R�R,R-R.R4(((s0/usr/lib/python2.7/site-packages/passlib/totp.pyt<module>s�%

":F	

	
	�g
�����;l

Anon7 - 2022
AnonSec Team