Python/POpen/gpg:通过stdin或文件描述符提供密码短语和加密文本

2024-04-25 19:32:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图通过一个python程序通过POpen远程控制gpg。
我有一个包含加密数据的文件,我想对其进行解密、修改并重新加密写入磁盘。
目前我将解密的信息存储在一个临时文件中(当程序结束时,我shred)。然后我对该文件进行修改,然后使用一个函数重新加密它,该函数将密码短语通过stdin
代码如下:

def encrypt(source, dest, passphrase, cipher=None):
  """Encrypts the source file.
  @param source Source file, that should be encrypted.
  @param dest Destination file.
  @param passphrase Passphrase to be used.
  @param cipher Cipher to use. If None or empty string gpg's default cipher is
  used.
  """
  phraseecho = Popen(("echo", passphrase), stdout=subprocess.PIPE)

  gpgargs = [
          "gpg",
          "-c",
          "--passphrase-fd", "0", # read passphrase from stdin
          "--output", dest,
          "--batch",
          "--force-mdc"]
  if not cipher is None and len(cipher) > 0:
      gpgargs.extend(("--cipher-algo", cipher))

  gpgargs.append(source)

  encrypter = Popen(
          gpgargs,
          stdin=phraseecho.stdout,
          stdout=subprocess.PIPE,
          stderr=subprocess.PIPE)
  stdout, stderr = encrypter.communicate()
  rc = encrypter.returncode
  if not rc == 0:
      raise RuntimeError(
              "Calling gpg failed with return code %d: %s" % (rc, stderr))

这很好地工作,但我相当肯定,在临时文件中存储潜在敏感的解密数据是一个相当大的安全漏洞。
因此,我想重写我的加密/解密函数,使它们能够完全在内存中工作,而无需在磁盘上存储敏感数据。
解密也可以通过stdin来传送密码短语,并为解密的数据捕获{}。在

另一方面,加密让我抓狂,因为我不能仅仅通过管道将密码短语和消息发送到“stdin”…至少

^{pr2}$

没用。
我的下一个最佳猜测是提供某种内存文件/pipe/socket或其他任何类型的文件描述符作为--passphrase-fd参数。问题是:我不知道是否有内存文件之类的东西,或者套接字是否适用,因为我从未使用过它们。在

有谁能帮我或者给我指点更好的解决办法吗?
这个解决方案不必是可移植的——我完全可以使用纯Linux的方法。在

提前谢谢。。。在

编辑:
非常感谢你们俩,拉尔斯和瑞兰。两种解决方案都能完美工作!不幸的是我只能接受一个


Tags: 文件数据函数none密码sourceparamstdin
2条回答

克里斯: 因为你有一个简单的例子os.管道感谢Lars,我将提供Pyrite(我的gpg的GTK前端)的功能,希望更多的代码示例更好。由于gui方面的原因,我的用例比你的要复杂一点,因为我实际上使用了一个字典来输入和输出,并且我有代码以stdin作为输入来启动gpg,以及用文件作为输入启动gpg的代码,以及其他一些复杂的情况。在

警告说,我和您一样从列表中的gpg命令行开始;但是,我没有使用 passphrase-fd 0,而是通过os.pipe()创建一个自定义文件描述符,在加载Popen()实例之前发送密码,该实例的输入数据为stdin=subprocess.PIPE。以下是黄铁矿crypt_interface模块的相关(修改)摘录。在

#!/usr/bin/env python
# Adapted excerpts from Pyrite <http://github.com/ryran/pyrite>

from subprocess import Popen, PIPE, check_output
...
 # I/O dictionary obj
 self.io = dict(
    stdin='',   # Stores input text for subprocess
    stdout='',  # Stores stdout stream from subprocess
    stderr=0,   # Stores tuple of r/w file descriptors for stderr stream
    gstatus=0,  # Stores tuple of r/w file descriptors for gpg-status stream
    infile=0,   # Input filename for subprocess
    outfile=0)  # Output filename for subprocess
...
cmd = ['gpg']
fd_pwd_R, fd_pwd_W = os.pipe()
os.write(fd_pwd_W, passwd)
os.close(fd_pwd_W)
cmd.append(' passphrase-fd')
cmd.append(str(fd_pwd_R))
...
# If working direct with files, setup our Popen instance with no stdin
if self.io['infile']:
    self.childprocess = Popen(cmd, stdout=PIPE, stderr=self.io['stderr'][3])
# Otherwise, only difference for Popen is we need the stdin pipe
else:
    self.childprocess = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=self.io['stderr'][4])

# Time to communicate! Save output for later
self.io['stdout'] = self.childprocess.communicate(input=self.io['stdin'])[0]

# Clear stdin from our dictionary asap, in case it's huge
self.io['stdin'] = ''

# Close os file descriptors
if fd_pwd_R:
    os.close(fd_pwd_R)
time.sleep(0.1)  # Sleep a bit to ensure everything gets read
os.close(self.io['stderr'][5])
if self.io['gstatus']:
    os.close(self.io['gstatus'][6])
...

调用所有等待的函数,直到self.childprocess对象具有returncode属性,并假定返回代码是0,并且输入是文本(而不是文件),然后从字典中读取gpg的stdout并将其打印到屏幕上。在

乐于回答问题或尝试从我有限的经验中提供帮助。可以通过以下链接找到我的联系方式。在

编辑:您可能还发现a4crypt很有启发性,因为它是gpg的一个更简单的前端,它是我为了学习python而开始的项目,后来在我“完成”(如果有这样的事情的话)黄铁矿之后被封存。在

下面是我在Obnam中运行gpg的代码, 也许它能对你有所帮助。在

def _gpg_pipe(args, data, passphrase):
    '''Pipe things through gpg.

    With the right args, this can be either an encryption or a decryption
    operation.

    For safety, we give the passphrase to gpg via a file descriptor.
    The argument list is modified to include the relevant options for that.

    The data is fed to gpg via a temporary file, readable only by
    the owner, to avoid congested pipes.

    '''

    # Open pipe for passphrase, and write it there. If passphrase is
    # very long (more than 4 KiB by default), this might block. A better
    # implementation would be to have a loop around select(2) to do pipe
    # I/O when it can be done without blocking. Patches most welcome.

    keypipe = os.pipe()
    os.write(keypipe[1], passphrase + '\n')
    os.close(keypipe[1])

    # Actually run gpg.

    argv = ['gpg', ' passphrase-fd', str(keypipe[0]), '-q', ' batch'] + args
    tracing.trace('argv=%s', repr(argv))
    p = subprocess.Popen(argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE)
    out, err = p.communicate(data)

    os.close(keypipe[0])

    # Return output data, or deal with errors.
    if p.returncode: # pragma: no cover
        raise obnamlib.Error(err)

    return out


def encrypt_symmetric(cleartext, key):
    '''Encrypt data with symmetric encryption.'''
    return _gpg_pipe(['-c'], cleartext, key)


def decrypt_symmetric(encrypted, key):
    '''Decrypt encrypted data with symmetric encryption.'''
    return _gpg_pipe(['-d'], encrypted, key)

相关问题 更多 >

    热门问题