1 # Copyright (C) 2012 W. Trevor King <wking@tremily.us>
3 # This file is part of pgp-mime.
5 # pgp-mime is free software: you can redistribute it and/or modify it under the
6 # terms of the GNU General Public License as published by the Free Software
7 # Foundation, either version 3 of the License, or (at your option) any later
10 # pgp-mime is distributed in the hope that it will be useful, but WITHOUT ANY
11 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
14 # You should have received a copy of the GNU General Public License along with
15 # pgp-mime. If not, see <http://www.gnu.org/licenses/>.
17 import codecs as _codecs
18 import logging as _logging
20 import os.path as _os_path
21 from _socket import socket as _Socket
22 import socket as _socket
23 import subprocess as _subprocess
25 from pyassuan import client as _client
26 from pyassuan import common as _common
28 from . import LOG as _LOG
31 def connect(client, filename, **kwargs):
32 filename = _os_path.expanduser(filename)
34 socket = _socket.socket(_socket.AF_UNIX, _socket.SOCK_STREAM)
35 socket.connect(filename)
36 client.input = socket.makefile('rb')
37 client.output = socket.makefile('wb')
39 p = _subprocess.Popen(
40 filename, stdin=_subprocess.PIPE, stdout=_subprocess.PIPE,
41 close_fds=True, **kwargs)
42 client.input = p.stdout
43 client.output = p.stdin
48 def get_client(**kwargs):
49 client = _client.AssuanClient(name='pgp-mime', close_on_disconnect=True)
50 client.logger.setLevel(_LOG.level)
51 socket = connect(client, '~/src/gpgme/build/src/gpgme-tool', **kwargs)
52 #socket = connect(client, '~/.assuan/S.gpgme-tool', **kwargs)
53 return (client, socket)
55 def disconnect(client, socket):
56 client.make_request(_common.Request('BYE'))
58 if isinstance(socket, _Socket):
59 socket.shutdown(_socket.SHUT_RDWR)
62 status = socket.wait()
63 assert status == 0, status
66 responses,data = client.get_responses() # get initial 'OK' from server
67 client.make_request(_common.Request('ARMOR', 'true'))
69 def _read(fd, buffersize=512):
73 new = _os.read(fd, buffersize)
74 except Exception as e:
75 _LOG.warn('error while reading: {}'.format(e))
85 i += _os.write(fd, data[i:])
88 def sign_and_encrypt_bytes(data, signers=None, recipients=None,
89 always_trust=False, mode='detach',
90 allow_default_signer=False):
91 r"""Sign ``data`` with ``signers`` and encrypt to ``recipients``.
95 >>> print(sign_and_encrypt_bytes(
96 ... bytes(b'Hello'), signers=['pgp-mime@invalid.com']))
97 ... # doctest: +ELLIPSIS
98 b'-----BEGIN PGP SIGNATURE-----\n...-----END PGP SIGNATURE-----\n'
102 >>> sign_and_encrypt_bytes(
103 ... bytes(b'Hello'), recipients=['pgp-mime@invalid.com'],
104 ... always_trust=True)
105 ... # doctest: +ELLIPSIS
106 b'-----BEGIN PGP MESSAGE-----\n...-----END PGP MESSAGE-----\n'
110 >>> sign_and_encrypt_bytes(
111 ... bytes(b'Hello'), signers=['pgp-mime@invalid.com'],
112 ... recipients=['pgp-mime@invalid.com'], always_trust=True)
113 ... # doctest: +ELLIPSIS
114 b'-----BEGIN PGP MESSAGE-----\n...-----END PGP MESSAGE-----\n'
116 input_read,input_write = _os.pipe()
117 output_read,output_write = _os.pipe()
118 client,socket = get_client(pass_fds=(input_read, output_write))
119 _os.close(input_read)
120 _os.close(output_write)
124 for signer in signers:
125 client.make_request(_common.Request('SIGNER', signer))
127 for recipient in recipients:
128 client.make_request(_common.Request('RECIPIENT', recipient))
130 _common.Request('INPUT', 'FD={}'.format(input_read)))
132 _common.Request('OUTPUT', 'FD={}'.format(output_write)))
134 if signers or allow_default_signer:
136 command = 'SIGN_ENCRYPT'
139 parameters.append('--{}'.format(mode))
143 raise ValueError('must specify at least one signer or recipient')
145 parameters.append('--always-trust')
146 _write(input_write, data)
147 _os.close(input_write)
150 _common.Request(command, ' '.join(parameters)))
151 d = _read(output_read)
153 disconnect(client, socket)
154 for fd in [input_write, output_read]:
159 def decrypt_bytes(data):
160 r"""Decrypt ``data``.
163 ... '-----BEGIN PGP MESSAGE-----',
164 ... 'Version: GnuPG v2.0.17 (GNU/Linux)',
166 ... 'hQEMA1Ea7aZDMrbjAQf/TAqLjksZSJxSqkBxYT5gtLQoXY6isvRZg2apjs7CW0y2',
167 ... 'tFK/ptnVYAq2OtWQFhbiJXj8hmwJyyFfb3lghpeu4ihO52JgkkwOpmJb6dxjOi83',
168 ... 'qDwaGOogEPH38BNLuwdrMCW0jmNROwvS796PtqSGUaJTuIiKUB8lETwPwIHrDc11',
169 ... 'N3RWStE5uShNkXXQXplUoeCKf3N4XguXym+GQCqJQzlEMrkkDdr4l7mzvt3Nf8EA',
170 ... 'SgSak086tUoo9x8IN5PJCuOJkcXcjQzFcpqOsA7dyZKO8NeQUZv2JvlZuorckNvN',
171 ... 'xx3PwW0a8VeJgTQrh64ZK/d3F3gNHUTzXkq/UIn25tJFAcmSUwxtsBal7p8zAeCV',
172 ... '8zefsHRQ5Y03IBeYBcVJBhDS9XfvwLQTJiGGstPCxzKTwSUT1MzV5t5twG/STDCc',
175 ... '-----END PGP MESSAGE-----',
177 ... ]).encode('us-ascii')
181 input_read,input_write = _os.pipe()
182 output_read,output_write = _os.pipe()
183 client,socket = get_client(pass_fds=(input_read, output_write))
184 _os.close(input_read)
185 _os.close(output_write)
189 _common.Request('INPUT', 'FD={}'.format(input_read)))
191 _common.Request('OUTPUT', 'FD={}'.format(output_write)))
192 _write(input_write, data)
193 _os.close(input_write)
195 client.make_request(_common.Request('DECRYPT'))
196 d = _read(output_read)
198 disconnect(client, socket)
199 for fd in [input_write, output_read]:
204 def verify_bytes(data, signature=None, always_trust=False):
205 r"""Verify a signature on ``data``, possibly decrypting first.
207 These tests assume you didn't trust the distributed test key.
210 ... '-----BEGIN PGP MESSAGE-----',
211 ... 'Version: GnuPG v2.0.17 (GNU/Linux)',
213 ... 'hQEMA1Ea7aZDMrbjAQf/YM1SeFzNGz0DnUynaEyhfGCvcqmjtbN1PtZMpT7VaQLN',
214 ... 'a+c0faskr79Atz0+2IBR7CDOlcETrRtH2EnrWukbRIDtmffNFGuhMRTNfnQ15OIN',
215 ... 'qrmt2P5gXznsgnm2XjzTK7S/Cc3Aq+zjaDrDt7bIedEdz+EyNgaKuL/lB9cAB8xL',
216 ... 'YYp/yn55Myjair2idgzsa7w/QXdE3RhpyRLqR2Jgz4P1I1xOgUYnylbpIZL9FOKN',
217 ... 'NR3RQhkGdANBku8otfthb5ZUGsNMV45ct4V8PE+xChjFb9gcwpaf1hhoIF/sYHD5',
218 ... 'Bkf+v/J8F40KGYY16b0DjQIUlnra9y7q9jj0h2bvc9LAtgHtVUso133LLcVYl7RP',
219 ... 'Vjyz9Ps366BtIdPlAL4CoF5hEcMKS5J3h1vRlyAKN4uHENl5vKvoxn7ID3JhhWQc',
220 ... '6QrPGis64zi3OnYor34HPh/KNJvkgOQkekmtYuTxnkiONA4lhMDJgeaVZ9WZq+GV',
221 ... 'MaCvCFGNYU2TV4V8wMlnUbF8d5bDQ83g8MxIVKdDcnBzzYLZha+qmz4Spry9iB53',
222 ... 'Sg/sM5H8gWWSl7Oj1lxVg7o7IscpQfVt6zL6jD2VjL3L3Hu7WEXIrcGZtvrP4d+C',
223 ... 'TGYWiGlh5B2UCFk2bVctfw8W/QfaVvJYD4Rfqta2V2p14KIJLFRSGa1g26W4ixrH',
224 ... 'XKxgaA3AIfJ+6c5RoisRLuYCxvQi91wkE9hAXR+inXK4Hq4SmiHoeITZFhHP3hh3',
225 ... 'rbpp8mopiMNxWqCbuqgILP6pShn4oPclu9aR8uJ1ziDxISTGYC71mvLUERUjFn2L',
226 ... 'fu6C0+TCC9RmeyL+eNdM6cjs1G7YR6yX',
228 ... '-----END PGP MESSAGE-----',
230 ... ]).encode('us-ascii')
231 >>> output,verified,result = verify_bytes(b)
236 >>> print(str(result, 'utf-8').replace('\x00', ''))
237 ... # doctest: +REPORT_UDIFF
238 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
243 <summary value="0x0" />
244 <fpr>B2EDBE0E771A4B8708DD16A7511AEDA64332B6E3</fpr>
245 <status value="0x0">Success <Unspecified source></status>
246 <timestamp unix="1332357237i" />
247 <exp-timestamp unix="0i" />
248 <wrong-key-usage value="0x0" />
249 <pka-trust value="0x0" />
250 <chain-model value="0x0" />
251 <validity value="0x0" />
252 <validity-reason value="0x0">Success <Unspecified source></validity-reason>
253 <pubkey-algo value="0x1">RSA</pubkey-algo>
254 <hash-algo value="0x8">SHA256</hash-algo>
260 >>> b = b'Success!\n'
261 >>> signature = '\n'.join([
262 ... '-----BEGIN PGP SIGNATURE-----',
263 ... 'Version: GnuPG v2.0.17 (GNU/Linux)',
265 ... 'iQEcBAEBAgAGBQJPaiw/AAoJEFEa7aZDMrbj93gH/1fQPXLjUTpONJUTmvGoMLNA',
266 ... 'W9ZhjpUL5i6rRqYGUvQ4kTEDuPMxkMrCyFCDHEhSDHufMek6Nso5/HeJn3aqxlgs',
267 ... 'hmNlvAq4FI6JQyFL7eCp/XG9cPx1p42dTI7JAih8FuK21sS4m/H5XP3R/6KXC99D',
268 ... '39rrXCvvR+yNgKe2dxuJwmKuLteVlcWxiIQwVrYK70GtJHC5BO79G8yGccWoEy9C',
269 ... '9JkJiyNptqZyFjGBNmMmrCSFZ7ZFA02RB+laRmwuIiozw4TJYEksxPrgZMbbcFzx',
270 ... 'zs3JHyV23+Fz1ftalvwskHE7tJkX9Ub8iBMNZ/KxJXXdPdpuMdEYVjoUehkQBQE=',
272 ... '-----END PGP SIGNATURE-----',
274 ... ]).encode('us-ascii')
275 >>> output,verified,result = verify_bytes(b, signature=signature)
280 >>> print(str(result, 'utf-8').replace('\x00', ''))
281 ... # doctest: +REPORT_UDIFF
282 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
287 <summary value="0x0" />
288 <fpr>B2EDBE0E771A4B8708DD16A7511AEDA64332B6E3</fpr>
289 <status value="0x0">Success <Unspecified source></status>
290 <timestamp unix="1332358207i" />
291 <exp-timestamp unix="0i" />
292 <wrong-key-usage value="0x0" />
293 <pka-trust value="0x0" />
294 <chain-model value="0x0" />
295 <validity value="0x0" />
296 <validity-reason value="0x0">Success <Unspecified source></validity-reason>
297 <pubkey-algo value="0x1">RSA</pubkey-algo>
298 <hash-algo value="0x2">SHA1</hash-algo>
305 input_read,input_write = _os.pipe()
306 pass_fds = [input_read]
308 message_read,message_write = _os.pipe()
310 pass_fds.append(message_read)
313 output_read,output_write = _os.pipe()
314 pass_fds.append(output_write)
315 client,socket = get_client(pass_fds=pass_fds)
316 _os.close(input_read)
318 _os.close(message_read)
320 _os.close(output_write)
321 verified = result = None
325 _common.Request('INPUT', 'FD={}'.format(input_read)))
328 _common.Request('MESSAGE', 'FD={}'.format(message_read)))
331 _common.Request('OUTPUT', 'FD={}'.format(output_write)))
333 _write(input_write, signature)
334 _os.close(input_write)
336 _write(message_write, data)
337 _os.close(message_write)
340 _write(input_write, data)
341 _os.close(input_write)
343 client.make_request(_common.Request('VERIFY'))
347 plain = _read(output_read)
348 rs,result = client.make_request(_common.Request('RESULT'))
350 for line in result.splitlines():
351 if b'<status ' in line and b'Success' not in line:
353 elif b'<pka-trust' in line and b'0x2' not in line:
356 disconnect(client, socket)
357 for fd in [input_write, message_write, output_read]:
360 return (plain, verified, result)