%PDF- %PDF-
Mini Shell

Mini Shell

Direktori : /lib/python3/dist-packages/duplicity/__pycache__/
Upload File :
Create Path :
Current File : //lib/python3/dist-packages/duplicity/__pycache__/gpginterface.cpython-312.pyc

�

�2e�Y���dZddlZddlZddlZddlmZddlZdZdZdZ	gd�Z
dd	d
ddd
d
d�Zd
dddd�ZGd�de
�ZGd�de
�ZGd�de
�ZGd�de
�Zd�Zedk(rddlZddlmZej.e�yy)a^Interface to GNU Privacy Guard (GnuPG)

!!! This was renamed to gpginterface.py.
    Please refer to duplicity's README for the reason. !!!

gpginterface is a Python module to interface with GnuPG which based on
GnuPGInterface by Frank J. Tobin.
It concentrates on interacting with GnuPG via filehandles,
providing access to control GnuPG via versatile and extensible means.

This module is based on GnuPG::Interface, a Perl module by the same author.

Normally, using this module will involve creating a
GnuPG object, setting some options in it's 'options' data member
(which is of type Options), creating some pipes
to talk with GnuPG, and then calling the run() method, which will
connect those pipes to the GnuPG process. run() returns a
Process object, which contains the filehandles to talk to GnuPG with.

Example code:

>>> import gpginterface
>>>
>>> plaintext  = b"Three blind mice"
>>> passphrase = "This is the passphrase"
>>>
>>> gnupg = gpginterface.GnuPG()
>>> gnupg.options.armor = 1
>>> gnupg.options.meta_interactive = 0
>>> gnupg.options.extra_args.append('--no-secmem-warning')
>>>
>>> # Normally we might specify something in
>>> # gnupg.options.recipients, like
>>> # gnupg.options.recipients = [ '0xABCD1234', 'bob@foo.bar' ]
>>> # but since we're doing symmetric-only encryption, it's not needed.
>>> # If you are doing standard, public-key encryption, using
>>> # --encrypt, you will need to specify recipients before
>>> # calling gnupg.run()
>>>
>>> # First we'll encrypt the test_text input symmetrically
>>> p1 = gnupg.run(['--symmetric'],
...                create_fhs=['stdin', 'stdout', 'passphrase'])
>>>
>>> ret = p1.handles['passphrase'].write(passphrase)
>>> p1.handles['passphrase'].close()
>>>
>>> ret = p1.handles['stdin'].write(plaintext)
>>> p1.handles['stdin'].close()
>>>
>>> ciphertext = p1.handles['stdout'].read()
>>> p1.handles['stdout'].close()
>>>
>>> # process cleanup
>>> p1.wait()
>>>
>>> # Now we'll decrypt what we just encrypted it,
>>> # using the convience method to get the
>>> # passphrase to GnuPG
>>> gnupg.passphrase = passphrase
>>>
>>> p2 = gnupg.run(['--decrypt'], create_fhs=['stdin', 'stdout'])
>>>
>>> ret = p2.handles['stdin'].write(ciphertext)
>>> p2.handles['stdin'].close()
>>>
>>> decrypted_plaintext = p2.handles['stdout'].read()
>>> p2.handles['stdout'].close()
>>>
>>> # process cleanup
>>> p2.wait()
>>>
>>> # Our decrypted plaintext:
>>> decrypted_plaintext
b'Three blind mice'
>>>
>>> # ...and see it's the same as what we orignally encrypted
>>> assert decrypted_plaintext == plaintext,           "GnuPG decrypted output does not match original input"
>>>
>>>
>>> ##################################################
>>> # Now let's trying using run()'s attach_fhs parameter
>>>
>>> # we're assuming we're running on a unix...
>>> infp = open('/etc/manpaths', 'rb')
>>>
>>> p1 = gnupg.run(['--symmetric'], create_fhs=['stdout'],
...                                 attach_fhs={'stdin': infp})
>>>
>>> # GnuPG will read the stdin from /etc/motd
>>> ciphertext = p1.handles['stdout'].read()
>>>
>>> # process cleanup
>>> p1.wait()
>>>
>>> # Now let's run the output through GnuPG
>>> # We'll write the output to a temporary file,
>>> import tempfile
>>> temp = tempfile.TemporaryFile()
>>>
>>> p2 = gnupg.run(['--decrypt'], create_fhs=['stdin'],
...                               attach_fhs={'stdout': temp})
>>>
>>> # give GnuPG our encrypted stuff from the first run
>>> ret = p2.handles['stdin'].write(ciphertext)
>>> p2.handles['stdin'].close()
>>>
>>> # process cleanup
>>> p2.wait()
>>>
>>> # rewind the tempfile and see what GnuPG gave us
>>> ret = temp.seek(0)
>>> decrypted_plaintext = temp.read()
>>>
>>> # compare what GnuPG decrypted with our original input
>>> ret = infp.seek(0)
>>> input_data = infp.read()
>>> assert decrypted_plaintext == input_data,            "GnuPG decrypted output does not match original input"

To do things like public-key encryption, simply pass do something
like:

gnupg.passphrase = 'My passphrase'
gnupg.options.recipients = [ 'bob@foobar.com' ]
gnupg.run( ['--sign', '--encrypt'], create_fhs=..., attach_fhs=...)

Here is an example of subclassing gpginterface.GnuPG,
so that it has an encrypt_string() method that returns
ciphertext.

>>> import gpginterface
>>>
>>> class MyGnuPG(gpginterface.GnuPG):
...
...     def __init__(self):
...         super().__init__()
...         self.setup_my_options()
...
...     def setup_my_options(self):
...         self.options.armor = 1
...         self.options.meta_interactive = 0
...         self.options.extra_args.append('--no-secmem-warning')
...
...     def encrypt_string(self, string, recipients):
...        gnupg.options.recipients = recipients   # a list!
...
...        proc = gnupg.run(['--encrypt'], create_fhs=['stdin', 'stdout'])
...
...        proc.handles['stdin'].write(string)
...        proc.handles['stdin'].close()
...
...        output = proc.handles['stdout'].read()
...        proc.handles['stdout'].close()
...
...        proc.wait()
...        return output
...
>>> gnupg = MyGnuPG()
>>> ciphertext = gnupg.encrypt_string(b"The secret", ['E477C232'])
>>>
>>> # just a small sanity test here for doctest
>>> import types
>>> assert isinstance(ciphertext, bytes),            "What GnuPG gave back is not bytes!"

Here is an example of generating a key:
>>> import gpginterface
>>> gnupg = gpginterface.GnuPG()
>>> gnupg.options.meta_interactive = 0
>>>
>>> # We will be creative and use the logger filehandle to capture
>>> # what GnuPG says this time, instead stderr; no stdout to listen to,
>>> # but we capture logger to surpress the dry-run command.
>>> # We also have to capture stdout since otherwise doctest complains;
>>> # Normally you can let stdout through when generating a key.
>>>
>>> proc = gnupg.run(['--gen-key'], create_fhs=['stdin', 'stdout',
...                                             'logger'])
>>>
>>> ret = proc.handles['stdin'].write(b'''Key-Type: DSA
... Key-Length: 1024
... # We are only testing syntax this time, so dry-run
... %dry-run
... Subkey-Type: ELG-E
... Subkey-Length: 1024
... Name-Real: Joe Tester
... Name-Comment: with stupid passphrase
... Name-Email: joe@foo.bar
... Expire-Date: 2y
... Passphrase: abc
... %pubring foo.pub
... %secring foo.sec
... ''')
>>>
>>> proc.handles['stdin'].close()
>>>
>>> report = proc.handles['logger'].read()
>>> proc.handles['logger'].close()
>>>
>>> proc.wait()


COPYRIGHT:

Copyright (C) 2001  Frank J. Tobin, ftobin@neverending.org

LICENSE:

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
or see http://www.gnu.org/copyleft/lesser.html
�N)�logz&Frank J. Tobin, ftobin@neverending.orgz0.3.2z>$Id: GnuPGInterface.py,v 1.6 2009/06/06 17:35:19 loafman Exp $)�stdin�stdout�stderr�wb�rb�r�w)rrr�
passphrase�command�logger�statusz--passphrase-fdz--logger-fdz--status-fdz--command-fd)rr
rrc�0�eZdZdZd�Zdd�Zd�Zd�Zd�Zy)	�GnuPGaClass instances represent GnuPG.

    Instance attributes of a GnuPG object are:

    * call -- string to call GnuPG with.  Defaults to "gpg"

    * passphrase -- Since it is a common operation
      to pass in a passphrase to GnuPG,
      and working with the passphrase filehandle mechanism directly
      can be mundane, if set, the passphrase attribute
      works in a special manner.  If the passphrase attribute is set,
      and no passphrase file object is sent in to run(),
      then GnuPG instnace will take care of sending the passphrase to
      GnuPG, the executable instead of having the user sent it in manually.

    * options -- Object of type gpginterface.Options.
      Attribute-setting in options determines
      the command-line options used when calling GnuPG.
    c�>�d|_d|_t�|_y)N�gpg)�callr�Options�options��selfs �8/usr/lib/python3/dist-packages/duplicity/gpginterface.py�__init__zGnuPG.__init__s����	�����y���Nc��|�g}|�g}|�i}tD],}||vs�||vs�
|j|tt|���.d}|j�d|vrd|vrd}|jd�|j
||||�}|rG|jd}|j|j�|j�|jd=|S)a�	Calls GnuPG with the list of string commands gnupg_commands,
        complete with prefixing dashes.
        For example, gnupg_commands could be
        '["--sign", "--encrypt"]'
        Returns a gpginterface.Process object.

        args is an optional list of GnuPG command arguments (not options),
        such as keyID's to export, filenames to process, etc.

        create_fhs is an optional list of GnuPG filehandle
        names that will be set as keys of the returned Process object's
        'handles' attribute.  The generated filehandles can be used
        to communicate with GnuPG via standard input, standard output,
        the status-fd, passphrase-fd, etc.

        Valid GnuPG filehandle names are:
          * stdin
          * stdout
          * stderr
          * status
          * passphase
          * command
          * logger

        The purpose of each filehandle is described in the GnuPG
        documentation.

        attach_fhs is an optional dictionary with GnuPG filehandle
        names mapping to opened files.  GnuPG will read or write
        to the file accordingly.  For example, if 'my_file' is an
        opened file and 'attach_fhs[stdin] is my_file', then GnuPG
        will read its standard input from my_file. This is useful
        if you want GnuPG to read/write to/from an existing file.
        For instance:

            f = open("encrypted.gpg")
            gnupg.run(["--decrypt"], attach_fhs={'stdin': f})

        Using attach_fhs also helps avoid system buffering
        issues that can arise when using create_fhs, which
        can cause the process to deadlock.

        If not mentioned in create_fhs or attach_fhs,
        GnuPG filehandles which are a std* (stdin, stdout, stderr)
        are defaulted to the running process' version of handle.
        Otherwise, that type of handle is simply not used when calling GnuPG.
        For example, if you do not care about getting data from GnuPG's
        status filehandle, simply do not specify it.

        run() returns a Process() object which has a 'handles'
        which is a dictionary mapping from the handle name
        (such as 'stdin' or 'stdout') to the respective
        newly-created FileObject connected to the running GnuPG process.
        For instance, if the call was

          process = gnupg.run(["--decrypt"], stdin=1)

        after run returns 'process.handles["stdin"]'
        is a FileObject connected to GnuPG's standard input,
        and can be written to.
        rr�)
�_stds�
setdefault�getattr�sysr�append�_attach_fork_exec�handles�write�close)	r�gnupg_commands�args�
create_fhs�
attach_fhs�std�handle_passphrase�process�
passphrase_fhs	         r�runz	GnuPG.run!s���~�<��D����J����J��	>�C��*�$��J�)>��%�%�c�7�3��+<�=�	>����?�?�&�<�z�+I�l�bl�Nl� !�����l�+��(�(���z�:�V���#�O�O�L�9�M�������0����!�����-��rc
��t�}|t|j��zD]6}|tvs�t	d|�dttj������|D]�}||vrtd|�d���t
j�}t|dk(st|dk(r
|d|df}t
j|dd	�t
j|dd	�t|d|dd�|j|<��t|j��D];\}}t|j�|j�d�|j|<�=t
j�|_|jdk7rJtj t"d
|jd��|f��|_|j$j'�|jdk(r|j)|||�|j+|�S)
z\This is like run(), but without the passphrase-helping
        (note that run() calls this).zunrecognized filehandle name 'z'; must be one of zcannot have filehandle 'z#' in both create_fhs and attach_fhsr
rrrT�wait�d)�target�namer')�Process�list�keys�	_fd_modes�KeyError�
ValueError�os�pipe�set_inheritable�Pipe�_pipes�items�fileno�fork�pid�	threading�Thread�threaded_waitpid�thread�start�	_as_child�
_as_parent)	rr&r'r(r)r,�fh_namer;�fhs	         rr"zGnuPG._attach_fork_exec{s����)��!�D����):�$;�;�	y�G��i�'��!?��y�H^�_c�dm�dr�dr�dt�_u�^v�w�x�x�	y�"�	@�G��*�$� �#;�G�9�Dg�!h�i�i��7�7�9�D�
��!�S�(�I�g�,>�$�,F��Q���a��)�����t�A�w��-����t�A�w��-�&*�4��7�D��G�Q�&?�G�N�N�7�#�	@�" �
� 0� 0� 2�3�	H�K�G�R�&*�2�9�9�;��	�	��Q�&G�G�N�N�7�#�	H��g�g�i����;�;�!��&�-�-�5E�d�SZ�S^�S^�_`�Ra�Lb�jq�is�t�G�N��N�N� � �"��;�;�!���N�N�7�N�D�9����w�'�'rc� �t|jj��D]e\}}|jr�t	j
|j�t	j|jt|�|j|<�g|`|S)z!Stuff run after forking in parent)r5r>r?�directr:r%�child�fdopen�parentr7r#)rr,�k�ps    rrIzGnuPG._as_parent�sm������-�-�/�0�	G�D�A�q��8�8�������!�%'�Y�Y�q�x�x��1��%F�����"�	G�
�N��rc
�:�tD]Q}|j|}tj|jttd|�d��j���St|jj��D]J\}}|js�|tvs�tj|jtjd��Lg}t|jj��D]_\}}|tvr&|jt||jd�g�|jr�Atj|j ��a|j"g|z|j$j'�z|z|z}tj(|d|�y)z Stuff run after forking in child�__rr1N)rr>r:�dup2rNrr r@r5r?rM�fcntl�F_SETFD�extend�_fd_optionsr%rPrr�get_args�execvp)	rr,r&r'r*rRrQ�fd_argsrs	         rrHzGnuPG._as_child�sA���	B�C����s�#�A��G�G�A�G�G�W�S�B�s�e�2�,�7�>�>�@�A�	B�����-�-�/�0�	7�D�A�q��x�x�A�U�N����A�G�G�U�]�]�A�6�	7�
������-�-�/�0�	#�D�A�q���~�����A��1�7�7�1�+�?�@��8�8�������"�
	#��9�9�+��'�$�,�,�*?�*?�*A�A�N�R�UY�Y��
�	�	�'�!�*�g�&r)NNN)	�__name__�
__module__�__qualname__�__doc__rr.r"rIrH�rrrrs#���(!�
X�t&(�P
�'rrc��eZdZdZd�Zy)r=z.simple struct holding stuff about pipes we usec�.�||_||_||_y�N)rPrNrM)rrPrNrMs    rrz
Pipe.__init__�s�������
���rN)r]r^r_r`rrarrr=r=�s
��8�rr=c�(�eZdZdZd�Zd�Zd�Zd�Zy)ra�Objects of this class encompass options passed to GnuPG.
    This class is responsible for determining command-line arguments
    which are based on options.  It can be said that a GnuPG
    object has-a Options object in its options attribute.

    Attributes which correlate directly to GnuPG options:

    Each option here defaults to false or None, and is described in
    GnuPG documentation.

    Booleans (set these attributes to booleans)

      * armor
      * no_greeting
      * no_verbose
      * quiet
      * batch
      * always_trust
      * rfc1991
      * openpgp
      * force_v3_sigs
      * no_options
      * textmode

    Strings (set these attributes to strings)

      * homedir
      * default_key
      * comment
      * compress_algo
      * options

    Lists (set these attributes to lists)

      * recipients  (***NOTE*** plural of 'recipient')
      * encrypt_to

    Meta options

    Meta options are options provided by this module that do
    not correlate directly to any GnuPG option by name,
    but are rather bundle of options used to accomplish
    a specific goal, such as obtaining compatibility with PGP 5.
    The actual arguments each of these reflects may change with time.  Each
    defaults to false unless otherwise specified.

    meta_pgp_5_compatible -- If true, arguments are generated to try
    to be compatible with PGP 5.x.

    meta_pgp_2_compatible -- If true, arguments are generated to try
    to be compatible with PGP 2.x.

    meta_interactive -- If false, arguments are generated to try to
    help the using program use GnuPG in a non-interactive
    environment, such as CGI scripts.  Default is true.

    extra_args -- Extra option arguments may be passed in
    via the attribute extra_args, a list.

    >>> import gpginterface
    >>>
    >>> gnupg = gpginterface.GnuPG()
    >>> gnupg.options.armor = 1
    >>> gnupg.options.recipients = ['Alice', 'Bob']
    >>> gnupg.options.extra_args = ['--no-secmem-warning']
    >>>
    >>> # no need for users to call this normally; just for show here
    >>> gnupg.options.get_args()
    ['--armor', '--recipient', 'Alice', '--recipient', 'Bob', '--no-secmem-warning']
    c�T�d|_d|_d|_d|_d|_d|_d|_d|_d|_d|_	d|_
d|_d|_d|_
d|_d|_d|_d|_d|_d|_g|_g|_g|_g|_y)Nrr)�armor�no_greeting�verbose�
no_verbose�quiet�batch�always_trust�rfc1991�openpgp�
force_v3_sigs�
no_options�textmode�meta_pgp_5_compatible�meta_pgp_2_compatible�meta_interactive�homedir�default_key�comment�
compress_algor�
encrypt_to�
recipients�hidden_recipients�
extra_argsrs rrzOptions.__init__s�����
������������
���
������������������
�&'��"�%&��"� !������������!������������!#�����rc�^�|j�|j�z|jzS)z9Generate a list of GnuPG arguments based upon attributes.)�
get_meta_args�get_standard_argsr}rs rrZzOptions.get_args>s*���!�!�#�d�&<�&<�&>�>����P�Prc�4�g}|j�|jd|jg�|j�|jd|jg�|j�|jd|jg�|j�|jd|jg�|j
�|jd|j
g�|jr|jd�|jr|jd�|jr|jd�|jr|jd	�|jr|jd
�|jr|jd�|jr|jd�|jr|jd
�|jr|jd�|j r|jd�|j"r|jd�|j$r|jd�|j&D]}|jd|g��|j(D]}|jd|g��|j*D]}|jd|g��|S)z8Generate a list of standard, non-meta or extra argumentsz	--homedirz	--optionsz	--comment�--compress-algoz
--default-keyz--no-optionsz--armorz
--textmodez
--no-greetingz	--verbosez--no-verbosez--quiet�--batchz--always-trust�--force-v3-sigs�	--rfc1991z	--openpgpz--recipientz--hidden-recipientz--encrypt-to)rvrXrrxryrwrqr!rgrrrhrirjrkrlrmrprnror{r|rz)rr'r	s   rr�zOptions.get_standard_argsCs
�����<�<�#��K�K��d�l�l�3�4��<�<�#��K�K��d�l�l�3�4��<�<�#��K�K��d�l�l�3�4����)��K�K�*�D�,>�,>�?�@����'��K�K��$�*:�*:�;�<��?�?��K�K��'��:�:��K�K�	�"��=�=��K�K��%�����K�K��(��<�<��K�K��$��?�?��K�K��'��:�:��K�K�	�"��:�:��K�K�	�"�����K�K�(�)�����K�K�)�*��<�<��K�K��$��<�<��K�K��$����	,�A��K�K���*�+�	,��'�'�	3�A��K�K�-�q�1�2�	3����	-�A��K�K���+�,�	-��rc��g}|jr|jgd��|jr|jd�|js|jddg�|S)z&Get a list of generated meta-arguments)r��1r�r�r�z--no-tty)rsrXrtr!ru)rr's  rrzOptions.get_meta_argsssQ�����%�%��K�K�C�D��%�%��K�K��$��$�$��K�K��J�/�0��rN)r]r^r_r`rrZr�rrarrrr�s ��E�N!�FQ�
.�`rrc�"�eZdZdZdefd�Zd�Zy)r4a�Objects of this class encompass properties of a GnuPG
    process spawned by GnuPG.run().

    # gnupg is a GnuPG object
    process = gnupg.run( [ '--decrypt' ], stdout = 1 )
    out = process.handles['stdout'].read()
    ...
    os.waitpid( process.pid, 0 )

    Data Attributes

    handles -- This is a map of filehandle-names to
    the file handles, if any, that were requested via run() and hence
    are connected to the running GnuPG process.  Valid names
    of this map are only those handles that were requested.

    pid -- The PID of the spawned GnuPG process.
    Useful to know, since once should call
    os.waitpid() to clean up the process, especially
    if multiple calls are made to run().
    �returnc�X�i|_i|_d|_d|_d|_d|_yrd)r>r#rB�_waitedrF�returnedrs rrzProcess.__init__�s,�������������������
rc��|j�|jj�|jdk7rtd|jdz	d����y)z�
        Wait on threaded_waitpid to exit and examine results.
        Will raise an IOError if the process exits non-zero.
        Nrz!GnuPG exited non-zero, with code �r1)r�rF�join�IOErrorrs rr0zProcess.wait�sO��
�=�=� ��K�K�����=�=�A���=�d�m�m�q�>P�QR�=S�T�U�U�rN)r]r^r_r`�objectrr0rarrr4r4�s���,�&��Vrr4c���	tj|jd�d|_y#t$r=}tjtd|j�d���d|_Yd}~yd}~wwxYw)a
    When started as a thread with the Process object, thread
    will execute an immediate waitpid() against the process
    pid and will collect the process termination info.  This
    will allow us to reap child processes as soon as possible,
    thus freeing resources quickly.
    rrzGPG process z terminated before wait()N)r:�waitpidrBr��	Exceptionr�Debug�_)r,�es  rrErE�s]����:�:�g�k�k�1�5�a�8�������	�	�!�l�7�;�;�-�/H�I�J�K�������s�(+�	A1�3A,�,A1�__main__r)�gpginterface)r`rVr:r �	duplicityrrC�
__author__�__version__�__revision__rr7rYr�rr=rr4rEr]�doctest�r��testmodrarr�<module>r�s���_�B
�	�
���
5�
���O��	&���������
�	�$����	��@'�F�@'�F�6��k�f�k�\'V�f�'V�T��z�����G�O�O�L�!�	r

Zerion Mini Shell 1.0