b3c29e756c75f4cb0ec602442230bf4026557651
[pgp-mime.git] / pgp_mime / crypt.py
1 # Copyright (C) 2012 W. Trevor King <wking@tremily.us>
2 #
3 # This file is part of pgp-mime.
4 #
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
8 # version.
9 #
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.
13 #
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/>.
16
17 import codecs as _codecs
18 import logging as _logging
19 import os as _os
20 import os.path as _os_path
21 from _socket import socket as _Socket
22 import socket as _socket
23 import subprocess as _subprocess
24
25 from pyassuan import client as _client
26 from pyassuan import common as _common
27
28 from . import LOG as _LOG
29
30
31 def connect(client, filename, **kwargs):
32     filename = _os_path.expanduser(filename)
33     if False:
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')
38     else:
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
44         socket = p
45     client.connect()
46     return socket
47
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)
54
55 def disconnect(client, socket):
56     client.make_request(_common.Request('BYE'))
57     client.disconnect()
58     if isinstance(socket, _Socket):
59         socket.shutdown(_socket.SHUT_RDWR)
60         socket.close()
61     else:
62         status = socket.wait()
63         assert status == 0, status
64
65 def hello(client):
66     responses,data = client.get_responses()  # get initial 'OK' from server
67     client.make_request(_common.Request('ARMOR', 'true'))
68
69 def _read(fd, buffersize=512):
70     d = []
71     while True:
72         try:
73             new = _os.read(fd, buffersize)
74         except Exception as e:
75             _LOG.warn('error while reading: {}'.format(e))
76             break
77         if not new:
78             break
79         d.append(new)
80     return b''.join(d)
81
82 def _write(fd, data):
83     i = 0
84     while i < len(data):
85         i += _os.write(fd, data[i:])
86
87
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``.
92
93     Just sign:
94
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'
99
100     Just encrypt:
101
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'
107
108     Sign and encrypt:
109
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'
115     """
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)
121     try:
122         hello(client)
123         if signers:
124             for signer in signers:
125                 client.make_request(_common.Request('SIGNER', signer))
126         if recipients:
127             for recipient in recipients:
128                 client.make_request(_common.Request('RECIPIENT', recipient))
129         client.make_request(
130             _common.Request('INPUT', 'FD={}'.format(input_read)))
131         client.make_request(
132             _common.Request('OUTPUT', 'FD={}'.format(output_write)))
133         parameters = []
134         if signers or allow_default_signer:
135             if recipients:
136                 command = 'SIGN_ENCRYPT'
137             else:
138                 command = 'SIGN'
139                 parameters.append('--{}'.format(mode))
140         elif recipients:
141             command = 'ENCRYPT'
142         else:
143             raise ValueError('must specify at least one signer or recipient')
144         if always_trust:
145             parameters.append('--always-trust')
146         _write(input_write, data)
147         _os.close(input_write)
148         input_write = -1
149         client.make_request(
150             _common.Request(command, ' '.join(parameters)))
151         d = _read(output_read)
152     finally:
153         disconnect(client, socket)
154         for fd in [input_write, output_read]:
155             if fd >= 0:
156                 _os.close(fd)
157     return d
158
159 def decrypt_bytes(data):
160     r"""Decrypt ``data``.
161
162     >>> b = '\n'.join([
163     ...     '-----BEGIN PGP MESSAGE-----',
164     ...     'Version: GnuPG v2.0.17 (GNU/Linux)',
165     ...     '',
166     ...     'hQEMA1Ea7aZDMrbjAQf/TAqLjksZSJxSqkBxYT5gtLQoXY6isvRZg2apjs7CW0y2',
167     ...     'tFK/ptnVYAq2OtWQFhbiJXj8hmwJyyFfb3lghpeu4ihO52JgkkwOpmJb6dxjOi83',
168     ...     'qDwaGOogEPH38BNLuwdrMCW0jmNROwvS796PtqSGUaJTuIiKUB8lETwPwIHrDc11',
169     ...     'N3RWStE5uShNkXXQXplUoeCKf3N4XguXym+GQCqJQzlEMrkkDdr4l7mzvt3Nf8EA',
170     ...     'SgSak086tUoo9x8IN5PJCuOJkcXcjQzFcpqOsA7dyZKO8NeQUZv2JvlZuorckNvN',
171     ...     'xx3PwW0a8VeJgTQrh64ZK/d3F3gNHUTzXkq/UIn25tJFAcmSUwxtsBal7p8zAeCV',
172     ...     '8zefsHRQ5Y03IBeYBcVJBhDS9XfvwLQTJiGGstPCxzKTwSUT1MzV5t5twG/STDCc',
173     ...     'uxW3wSdo',
174     ...     '=bZI+',
175     ...     '-----END PGP MESSAGE-----',
176     ...     ''
177     ...     ]).encode('us-ascii')
178     >>> decrypt_bytes(b)
179     b'Success!\n'
180     """
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)
186     try:
187         hello(client)
188         client.make_request(
189             _common.Request('INPUT', 'FD={}'.format(input_read)))
190         client.make_request(
191             _common.Request('OUTPUT', 'FD={}'.format(output_write)))
192         _write(input_write, data)
193         _os.close(input_write)
194         input_write = -1
195         client.make_request(_common.Request('DECRYPT'))
196         d = _read(output_read)
197     finally:
198         disconnect(client, socket)
199         for fd in [input_write, output_read]:
200             if fd >= 0:
201                 _os.close(fd)
202     return d
203
204 def verify_bytes(data, signature=None, always_trust=False):
205     r"""Verify a signature on ``data``, possibly decrypting first.
206
207     These tests assume you didn't trust the distributed test key.
208
209     >>> b = '\n'.join([
210     ...     '-----BEGIN PGP MESSAGE-----',
211     ...     'Version: GnuPG v2.0.17 (GNU/Linux)',
212     ...     '',
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',
227     ...     '=phHd',
228     ...     '-----END PGP MESSAGE-----',
229     ...     '',
230     ...     ]).encode('us-ascii')
231     >>> output,verified,result = verify_bytes(b)
232     >>> output
233     b'Success!\n'
234     >>> verified
235     False
236     >>> print(str(result, 'utf-8').replace('\x00', ''))
237     ... # doctest: +REPORT_UDIFF
238     <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
239     <gpgme>
240       <verify-result>
241         <signatures>
242           <signature>
243             <summary value="0x0" />
244             <fpr>B2EDBE0E771A4B8708DD16A7511AEDA64332B6E3</fpr>
245             <status value="0x0">Success &lt;Unspecified source&gt;</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 &lt;Unspecified source&gt;</validity-reason>
253             <pubkey-algo value="0x1">RSA</pubkey-algo>
254             <hash-algo value="0x8">SHA256</hash-algo>
255           </signature>
256         </signatures>
257       </verify-result>
258     </gpgme>
259     <BLANKLINE>
260     >>> b = b'Success!\n'
261     >>> signature = '\n'.join([
262     ...     '-----BEGIN PGP SIGNATURE-----',
263     ...     'Version: GnuPG v2.0.17 (GNU/Linux)',
264     ...     '',
265     ...     'iQEcBAEBAgAGBQJPaiw/AAoJEFEa7aZDMrbj93gH/1fQPXLjUTpONJUTmvGoMLNA',
266     ...     'W9ZhjpUL5i6rRqYGUvQ4kTEDuPMxkMrCyFCDHEhSDHufMek6Nso5/HeJn3aqxlgs',
267     ...     'hmNlvAq4FI6JQyFL7eCp/XG9cPx1p42dTI7JAih8FuK21sS4m/H5XP3R/6KXC99D',
268     ...     '39rrXCvvR+yNgKe2dxuJwmKuLteVlcWxiIQwVrYK70GtJHC5BO79G8yGccWoEy9C',
269     ...     '9JkJiyNptqZyFjGBNmMmrCSFZ7ZFA02RB+laRmwuIiozw4TJYEksxPrgZMbbcFzx',
270     ...     'zs3JHyV23+Fz1ftalvwskHE7tJkX9Ub8iBMNZ/KxJXXdPdpuMdEYVjoUehkQBQE=',
271     ...     '=rRBP',
272     ...     '-----END PGP SIGNATURE-----',
273     ...     '',
274     ...     ]).encode('us-ascii')
275     >>> output,verified,result = verify_bytes(b, signature=signature)
276     >>> output
277     b'Success!\n'
278     >>> verified
279     False
280     >>> print(str(result, 'utf-8').replace('\x00', ''))
281     ... # doctest: +REPORT_UDIFF
282     <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
283     <gpgme>
284       <verify-result>
285         <signatures>
286           <signature>
287             <summary value="0x0" />
288             <fpr>B2EDBE0E771A4B8708DD16A7511AEDA64332B6E3</fpr>
289             <status value="0x0">Success &lt;Unspecified source&gt;</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 &lt;Unspecified source&gt;</validity-reason>
297             <pubkey-algo value="0x1">RSA</pubkey-algo>
298             <hash-algo value="0x2">SHA1</hash-algo>
299           </signature>
300         </signatures>
301       </verify-result>
302     </gpgme>
303     <BLANKLINE>
304     """
305     input_read,input_write = _os.pipe()
306     pass_fds = [input_read]
307     if signature:
308         message_read,message_write = _os.pipe()
309         output_read = -1
310         pass_fds.append(message_read)
311     else:
312         message_write = -1
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)
317     if signature:
318         _os.close(message_read)
319     else:
320         _os.close(output_write)
321     verified = result = None
322     try:
323         hello(client)
324         client.make_request(
325             _common.Request('INPUT', 'FD={}'.format(input_read)))
326         if signature:
327             client.make_request(
328                 _common.Request('MESSAGE', 'FD={}'.format(message_read)))
329         else:
330             client.make_request(
331                 _common.Request('OUTPUT', 'FD={}'.format(output_write)))
332         if signature:
333             _write(input_write, signature)
334             _os.close(input_write)
335             input_write = -1
336             _write(message_write, data)
337             _os.close(message_write)
338             message_write = -1
339         else:
340             _write(input_write, data)
341             _os.close(input_write)
342             input_write = -1
343         client.make_request(_common.Request('VERIFY'))
344         if signature:
345             plain = data
346         else:
347             plain = _read(output_read)
348         rs,result = client.make_request(_common.Request('RESULT'))
349         verified = True
350         for line in result.splitlines():
351             if b'<status ' in line and b'Success' not in line:
352                 verified = False
353             elif b'<pka-trust' in line and b'0x2' not in line:
354                 verified = False
355     finally:
356         disconnect(client, socket)
357         for fd in [input_write, message_write, output_read]:
358             if fd >= 0:
359                 _os.close(fd)
360     return (plain, verified, result)