/
core.py
1795 lines (1436 loc) · 61.2 KB
/
core.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import re
import os
import warnings
import weakref
from . import gpgme
from .errors import errorcheck, GPGMEError
from . import constants
from . import errors
from . import util
del absolute_import, print_function, unicode_literals
# Copyright (C) 2016-2018 g10 Code GmbH
# Copyright (C) 2004, 2008 Igor Belyi <belyi@users.sourceforge.net>
# Copyright (C) 2002 John Goerzen <jgoerzen@complete.org>
#
# 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
"""Core functionality
Core functionality of GPGME wrapped in a object-oriented fashion.
Provides the 'Context' class for performing cryptographic operations,
and the 'Data' class describing buffers of data.
"""
class GpgmeWrapper(object):
"""Base wrapper class
Not to be instantiated directly.
"""
def __init__(self, wrapped):
self._callback_excinfo = None
self.wrapped = wrapped
def __repr__(self):
return '<{}/{!r}>'.format(
super(GpgmeWrapper, self).__repr__(), self.wrapped)
def __str__(self):
acc = ['{}.{}'.format(__name__, self.__class__.__name__)]
flags = [f for f in self._boolean_properties if getattr(self, f)]
if flags:
acc.append('({})'.format(' '.join(flags)))
return '<{}>'.format(' '.join(acc))
def __hash__(self):
return hash(repr(self.wrapped))
def __eq__(self, other):
if other is None:
return False
else:
return repr(self.wrapped) == repr(other.wrapped)
@property
def _ctype(self):
"""The name of the c type wrapped by this class
Must be set by child classes.
"""
raise NotImplementedError()
@property
def _cprefix(self):
"""The common prefix of c functions wrapped by this class
Must be set by child classes.
"""
raise NotImplementedError()
def _errorcheck(self, name):
"""Must be implemented by child classes.
This function must return a trueish value for all c functions
returning gpgme_error_t."""
raise NotImplementedError()
"""The set of all boolean properties"""
_boolean_properties = set()
def __wrap_boolean_property(self, key, do_set=False, value=None):
get_func = getattr(gpgme, "{}get_{}".format(self._cprefix, key))
set_func = getattr(gpgme, "{}set_{}".format(self._cprefix, key))
def get(slf):
if not slf.wrapped:
return False
return bool(get_func(slf.wrapped))
def set_(slf, value):
if not slf.wrapped:
return
set_func(slf.wrapped, bool(value))
p = property(get, set_, doc="{} flag".format(key))
setattr(self.__class__, key, p)
if do_set:
set_(self, bool(value))
else:
return get(self)
_munge_docstring = re.compile(r'gpgme_([^(]*)\(([^,]*), (.*\) -> .*)')
def __getattr__(self, key):
"""On-the-fly generation of wrapper methods and properties"""
if key[0] == '_' or self._cprefix is None:
return None
if key in self._boolean_properties:
return self.__wrap_boolean_property(key)
name = self._cprefix + key
func = getattr(gpgme, name)
if self._errorcheck(name):
def _funcwrap(slf, *args):
if not slf.wrapped:
return None
result = func(slf.wrapped, *args)
if slf._callback_excinfo:
gpgme.gpg_raise_callback_exception(slf)
return errorcheck(result, name)
else:
def _funcwrap(slf, *args):
if not slf.wrapped:
return None
result = func(slf.wrapped, *args)
if slf._callback_excinfo:
gpgme.gpg_raise_callback_exception(slf)
return result
doc_orig = getattr(func, "__doc__")
if doc_orig:
doc = self._munge_docstring.sub(r'\2.\1(\3', doc_orig)
else:
doc = None
_funcwrap.__doc__ = doc
# Monkey-patch the class.
setattr(self.__class__, key, _funcwrap)
# Bind the method to 'self'.
def wrapper(*args):
return _funcwrap(self, *args)
wrapper.__doc__ = doc
return wrapper
def __setattr__(self, key, value):
"""On-the-fly generation of properties"""
if key in self._boolean_properties:
self.__wrap_boolean_property(key, True, value)
else:
super(GpgmeWrapper, self).__setattr__(key, value)
class Context(GpgmeWrapper):
"""Context for cryptographic operations
All cryptographic operations in GPGME are performed within a
context, which contains the internal state of the operation as
well as configuration parameters. By using several contexts you
can run several cryptographic operations in parallel, with
different configuration.
Access to a context must be synchronized.
"""
def __init__(self,
armor=False,
textmode=False,
offline=False,
signers=[],
pinentry_mode=constants.PINENTRY_MODE_DEFAULT,
protocol=constants.PROTOCOL_OpenPGP,
wrapped=None,
home_dir=None):
"""Construct a context object
Keyword arguments:
armor -- enable ASCII armoring (default False)
textmode -- enable canonical text mode (default False)
offline -- do not contact external key sources (default False)
signers -- list of keys used for signing (default [])
pinentry_mode -- pinentry mode (default PINENTRY_MODE_DEFAULT)
protocol -- protocol to use (default PROTOCOL_OpenPGP)
home_dir -- state directory (default is the engine default)
"""
if wrapped:
self.own = False
else:
tmp = gpgme.new_gpgme_ctx_t_p()
errorcheck(gpgme.gpgme_new(tmp))
wrapped = gpgme.gpgme_ctx_t_p_value(tmp)
gpgme.delete_gpgme_ctx_t_p(tmp)
self.own = True
super(Context, self).__init__(wrapped)
self.armor = armor
self.textmode = textmode
self.offline = offline
self.signers = signers
self.pinentry_mode = pinentry_mode
self.protocol = protocol
self.home_dir = home_dir
def __read__(self, sink, data):
"""Read helper
Helper function to retrieve the results of an operation, or
None if SINK is given.
"""
if sink or data is None:
return None
data.seek(0, os.SEEK_SET)
return data.read()
def __repr__(self):
return ("Context(armor={0.armor}, "
"textmode={0.textmode}, offline={0.offline}, "
"signers={0.signers}, pinentry_mode={0.pinentry_mode}, "
"protocol={0.protocol}, home_dir={0.home_dir}"
")").format(self)
def encrypt(self,
plaintext,
recipients=[],
sign=True,
sink=None,
passphrase=None,
always_trust=False,
add_encrypt_to=False,
prepare=False,
expect_sign=False,
compress=True):
"""Encrypt data
Encrypt the given plaintext for the given recipients. If the
list of recipients is empty, the data is encrypted
symmetrically with a passphrase.
The passphrase can be given as parameter, using a callback
registered at the context, or out-of-band via pinentry.
Keyword arguments:
recipients -- list of keys to encrypt to
sign -- sign plaintext (default True)
sink -- write result to sink instead of returning it
passphrase -- for symmetric encryption
always_trust -- always trust the keys (default False)
add_encrypt_to -- encrypt to configured additional keys (default False)
prepare -- (ui) prepare for encryption (default False)
expect_sign -- (ui) prepare for signing (default False)
compress -- compress plaintext (default True)
Returns:
ciphertext -- the encrypted data (or None if sink is given)
result -- additional information about the encryption
sign_result -- additional information about the signature(s)
Raises:
InvalidRecipients -- if encryption using a particular key failed
InvalidSigners -- if signing using a particular key failed
GPGMEError -- as signaled by the underlying library
"""
ciphertext = sink if sink else Data()
flags = 0
flags |= always_trust * constants.ENCRYPT_ALWAYS_TRUST
flags |= (not add_encrypt_to) * constants.ENCRYPT_NO_ENCRYPT_TO
flags |= prepare * constants.ENCRYPT_PREPARE
flags |= expect_sign * constants.ENCRYPT_EXPECT_SIGN
flags |= (not compress) * constants.ENCRYPT_NO_COMPRESS
if passphrase is not None:
old_pinentry_mode = self.pinentry_mode
old_passphrase_cb = getattr(self, '_passphrase_cb', None)
self.pinentry_mode = constants.PINENTRY_MODE_LOOPBACK
def passphrase_cb(hint, desc, prev_bad, hook=None):
return passphrase
self.set_passphrase_cb(passphrase_cb)
try:
if sign:
self.op_encrypt_sign(recipients, flags, plaintext, ciphertext)
else:
self.op_encrypt(recipients, flags, plaintext, ciphertext)
except errors.GPGMEError as e:
result = self.op_encrypt_result()
sig_result = self.op_sign_result() if sign else None
results = (self.__read__(sink, ciphertext), result, sig_result)
if e.getcode() == errors.UNUSABLE_PUBKEY:
if result.invalid_recipients:
raise errors.InvalidRecipients(
result.invalid_recipients,
error=e.error,
results=results)
if e.getcode() == errors.UNUSABLE_SECKEY:
sig_result = self.op_sign_result()
if sig_result.invalid_signers:
raise errors.InvalidSigners(
sig_result.invalid_signers,
error=e.error,
results=results)
# Otherwise, just raise the error, but attach the results
# first.
e.results = results
raise e
finally:
if passphrase is not None:
self.pinentry_mode = old_pinentry_mode
gpgme.gpg_set_passphrase_cb(self, old_passphrase_cb)
result = self.op_encrypt_result()
assert not result.invalid_recipients
sig_result = self.op_sign_result() if sign else None
assert not sig_result or not sig_result.invalid_signers
return self.__read__(sink, ciphertext), result, sig_result
def decrypt(self, ciphertext, sink=None, passphrase=None, verify=True, filter_signatures=True):
"""Decrypt data
Decrypt the given ciphertext and verify any signatures. If
VERIFY is an iterable of keys, the ciphertext must be signed
by all those keys, otherwise a MissingSignatures error is
raised. Note: if VERIFY is an empty iterable, that is treated
the same as passing verify=True (that is, verify signatures
and return data about any valid signatures found, but no
signatures are required and no MissingSignatures error will be
raised).
The filter_signatures argument can be used to force this
function to return signatures that are not fully trusted - for
example because they were made by unknown keys.
If the ciphertext is symmetrically encrypted using a
passphrase, that passphrase can be given as parameter, using a
callback registered at the context, or out-of-band via
pinentry.
Keyword arguments:
sink -- write result to sink instead of returning it
passphrase -- for symmetric decryption
verify -- check signatures (boolean or iterable of keys,
see above) (default True)
filter_signatures -- if this function should filter out signatures
that are not completely OK (default True)
Returns:
plaintext -- the decrypted data (or None if sink is given)
result -- additional information about the decryption
verify_result -- additional information about the valid
signature(s) found
Raises:
UnsupportedAlgorithm -- if an unsupported algorithm was used
MissingSignatures -- if expected signatures are missing or bad
GPGMEError -- as signaled by the underlying library
"""
do_sig_verification = False
required_keys = None
plaintext = sink if sink else Data()
if passphrase is not None:
old_pinentry_mode = self.pinentry_mode
old_passphrase_cb = getattr(self, '_passphrase_cb', None)
self.pinentry_mode = constants.PINENTRY_MODE_LOOPBACK
def passphrase_cb(hint, desc, prev_bad, hook=None):
return passphrase
self.set_passphrase_cb(passphrase_cb)
try:
if isinstance(verify, bool):
do_sig_verification = verify
elif verify is None:
warnings.warn(
"ctx.decrypt called with verify=None, should be bool or iterable (treating as False).",
category=DeprecationWarning)
do_sig_verification = False
else:
# we hope this is an iterable:
required_keys = verify
do_sig_verification = True
if do_sig_verification:
self.op_decrypt_verify(ciphertext, plaintext)
else:
self.op_decrypt(ciphertext, plaintext)
except errors.GPGMEError as e:
result = self.op_decrypt_result()
if do_sig_verification:
verify_result = self.op_verify_result()
else:
verify_result = None
# Just raise the error, but attach the results first.
e.results = (self.__read__(sink, plaintext), result, verify_result)
raise e
finally:
if passphrase is not None:
self.pinentry_mode = old_pinentry_mode
gpgme.gpg_set_passphrase_cb(self, old_passphrase_cb)
result = self.op_decrypt_result()
if do_sig_verification:
verify_result = self.op_verify_result()
else:
verify_result = None
results = (self.__read__(sink, plaintext), result, verify_result)
if result.unsupported_algorithm:
raise errors.UnsupportedAlgorithm(result.unsupported_algorithm,
results=results)
if do_sig_verification:
if filter_signatures:
verify_result.signatures = list(filter(lambda s: s.status == errors.NO_ERROR, verify_result.signatures))
if required_keys is not None:
missing = []
for key in required_keys:
ok = False
for subkey in key.subkeys:
for sig in verify_result.signatures:
if sig.summary & constants.SIGSUM_VALID == 0:
continue
if subkey.can_sign and subkey.fpr == sig.fpr:
ok = True
break
if ok:
break
if not ok:
missing.append(key)
if missing:
raise errors.MissingSignatures(verify_result, missing,
results=results)
return results
def sign(self, data, sink=None, mode=constants.SIG_MODE_NORMAL):
"""Sign data
Sign the given data with either the configured default local
key, or the 'signers' keys of this context.
Keyword arguments:
mode -- signature mode (default: normal, see below)
sink -- write result to sink instead of returning it
Returns:
either
signed_data -- encoded data and signature (normal mode)
signature -- only the signature data (detached mode)
cleartext -- data and signature as text (cleartext mode)
(or None if sink is given)
result -- additional information about the signature(s)
Raises:
InvalidSigners -- if signing using a particular key failed
GPGMEError -- as signaled by the underlying library
"""
signeddata = sink if sink else Data()
try:
self.op_sign(data, signeddata, mode)
except errors.GPGMEError as e:
results = (self.__read__(sink, signeddata), self.op_sign_result())
if e.getcode() == errors.UNUSABLE_SECKEY:
if results[1].invalid_signers:
raise errors.InvalidSigners(
results[1].invalid_signers,
error=e.error,
results=results)
e.results = results
raise e
result = self.op_sign_result()
assert not result.invalid_signers
return self.__read__(sink, signeddata), result
def verify(self, signed_data, signature=None, sink=None, verify=[]):
"""Verify signatures
Verify signatures over data. If VERIFY is an iterable of
keys, the ciphertext must be signed by all those keys,
otherwise an error is raised.
Keyword arguments:
signature -- detached signature data
sink -- write result to sink instead of returning it
Returns:
data -- the plain data
(or None if sink is given, or we verified a detached signature)
result -- additional information about the signature(s)
Raises:
BadSignatures -- if a bad signature is encountered
MissingSignatures -- if expected signatures are missing or bad
GPGMEError -- as signaled by the underlying library
"""
if signature:
# Detached signature, we don't return the plain text.
data = None
else:
data = sink if sink else Data()
try:
if signature:
self.op_verify(signature, signed_data, None)
else:
self.op_verify(signed_data, None, data)
except errors.GPGMEError as e:
# Just raise the error, but attach the results first.
e.results = (self.__read__(sink, data), self.op_verify_result())
raise e
results = (self.__read__(sink, data), self.op_verify_result())
if any(s.status != errors.NO_ERROR for s in results[1].signatures):
raise errors.BadSignatures(results[1], results=results)
missing = list()
for key in verify:
ok = False
for subkey in key.subkeys:
for sig in results[1].signatures:
if sig.summary & constants.SIGSUM_VALID == 0:
continue
if subkey.can_sign and subkey.fpr == sig.fpr:
ok = True
break
if ok:
break
if not ok:
missing.append(key)
if missing:
raise errors.MissingSignatures(
results[1], missing, results=results)
return results
def key_import(self, data):
"""Import data
Imports the given data into the Context.
Returns:
-- an object describing the results of imported or updated
keys
Raises:
TypeError -- Very rarely.
GPGMEError -- as signaled by the underlying library:
Import status errors, when they occur, will usually
be of NODATA. NO_PUBKEY indicates something
managed to run the function without any
arguments, while an argument of None triggers
the first NODATA of errors.GPGME in the
exception.
"""
try:
self.op_import(data)
result = self.op_import_result()
if result.considered == 0:
status = constants.STATUS_IMPORT_PROBLEM
else:
status = constants.STATUS_KEY_CONSIDERED
except Exception as e:
if e == errors.GPGMEError:
if e.code_str == "No data":
status = constants.STATUS_NODATA
else:
status = constants.STATUS_FILE_ERROR
elif e == TypeError and hasattr(data, "decode") is True:
status = constants.STATUS_NO_PUBKEY
elif e == TypeError and hasattr(data, "encode") is True:
status = constants.STATUS_FILE_ERROR
else:
status = constants.STATUS_ERROR
if status == constants.STATUS_KEY_CONSIDERED:
import_result = result
else:
import_result = status
return import_result
def key_export(self, pattern=None):
"""Export keys.
Exports public keys matching the pattern specified. If no
pattern is specified then exports all available keys.
Keyword arguments:
pattern -- return keys matching pattern (default: all keys)
Returns:
-- A key block containing one or more OpenPGP keys in
either ASCII armoured or binary format as determined
by the Context(). If there are no matching keys it
returns None.
Raises:
GPGMEError -- as signaled by the underlying library.
"""
data = Data()
mode = 0
try:
self.op_export(pattern, mode, data)
data.seek(0, os.SEEK_SET)
pk_result = data.read()
except GPGMEError as e:
raise e
if len(pk_result) > 0:
result = pk_result
else:
result = None
return result
def key_export_minimal(self, pattern=None):
"""Export keys.
Exports public keys matching the pattern specified in a
minimised format. If no pattern is specified then exports all
available keys.
Keyword arguments:
pattern -- return keys matching pattern (default: all keys)
Returns:
-- A key block containing one or more minimised OpenPGP
keys in either ASCII armoured or binary format as
determined by the Context(). If there are no matching
keys it returns None.
Raises:
GPGMEError -- as signaled by the underlying library.
"""
data = Data()
mode = gpgme.GPGME_EXPORT_MODE_MINIMAL
try:
self.op_export(pattern, mode, data)
data.seek(0, os.SEEK_SET)
pk_result = data.read()
except GPGMEError as e:
raise e
if len(pk_result) > 0:
result = pk_result
else:
result = None
return result
def key_export_secret(self, pattern=None):
"""Export secret keys.
Exports secret keys matching the pattern specified. If no
pattern is specified then exports or attempts to export all
available secret keys.
IMPORTANT: Each secret key to be exported will prompt for its
passphrase via an invocation of pinentry and gpg-agent. If the
passphrase is not entered or does not match then no data will be
exported. This is the same result as when specifying a pattern
that is not matched by the available keys.
Keyword arguments:
pattern -- return keys matching pattern (default: all keys)
Returns:
-- On success a key block containing one or more OpenPGP
secret keys in either ASCII armoured or binary format
as determined by the Context().
-- On failure while not raising an exception, returns None.
Raises:
GPGMEError -- as signaled by the underlying library.
"""
data = Data()
mode = gpgme.GPGME_EXPORT_MODE_SECRET
try:
self.op_export(pattern, mode, data)
data.seek(0, os.SEEK_SET)
sk_result = data.read()
except GPGMEError as e:
raise e
if len(sk_result) > 0:
result = sk_result
else:
result = None
return result
def keylist(self,
pattern=None,
secret=False,
mode=constants.keylist.mode.LOCAL,
source=None):
"""List keys
Keyword arguments:
pattern -- return keys matching pattern (default: all keys)
secret -- return only secret keys (default: False)
mode -- keylist mode (default: list local keys)
source -- read keys from source instead from the keyring
(all other options are ignored in this case)
Returns:
-- an iterator returning key objects
Raises:
GPGMEError -- as signaled by the underlying library
"""
if not source:
self.set_keylist_mode(mode)
self.op_keylist_start(pattern, secret)
else:
# Automatic wrapping of SOURCE is not possible here,
# because the object must not be deallocated until the
# iteration over the results ends.
if not isinstance(source, Data):
source = Data(file=source)
self.op_keylist_from_data_start(source, 0)
key = self.op_keylist_next()
while key:
yield key
key = self.op_keylist_next()
self.op_keylist_end()
def create_key(self,
userid,
algorithm=None,
expires_in=0,
expires=True,
sign=False,
encrypt=False,
certify=False,
authenticate=False,
passphrase=None,
force=False):
"""Create a primary key
Create a primary key for the user id USERID.
ALGORITHM may be used to specify the public key encryption
algorithm for the new key. By default, a reasonable default
is chosen. You may use "future-default" to select an
algorithm that will be the default in a future implementation
of the engine. ALGORITHM may be a string like "rsa", or
"rsa2048" to explicitly request an algorithm and a key size.
EXPIRES_IN specifies the expiration time of the key in number
of seconds since the keys creation. By default, a reasonable
expiration time is chosen. If you want to create a key that
does not expire, use the keyword argument EXPIRES.
SIGN, ENCRYPT, CERTIFY, and AUTHENTICATE can be used to
request the capabilities of the new key. If you don't request
any, a reasonable set of capabilities is selected, and in case
of OpenPGP, a subkey with a reasonable set of capabilities is
created.
If PASSPHRASE is None (the default), then the key will not be
protected with a passphrase. If PASSPHRASE is a string, it
will be used to protect the key. If PASSPHRASE is True, the
passphrase must be supplied using a passphrase callback or
out-of-band with a pinentry.
Keyword arguments:
algorithm -- public key algorithm, see above (default: reasonable)
expires_in -- expiration time in seconds (default: reasonable)
expires -- whether the key should expire (default: True)
sign -- request the signing capability (see above)
encrypt -- request the encryption capability (see above)
certify -- request the certification capability (see above)
authenticate -- request the authentication capability (see above)
passphrase -- protect the key with a passphrase (default: no
passphrase)
force -- force key creation even if a key with the same userid
exists (default: False)
Returns:
-- an object describing the result of the key creation
Raises:
GPGMEError -- as signaled by the underlying library
"""
if util.is_a_string(passphrase):
old_pinentry_mode = self.pinentry_mode
old_passphrase_cb = getattr(self, '_passphrase_cb', None)
self.pinentry_mode = constants.PINENTRY_MODE_LOOPBACK
def passphrase_cb(hint, desc, prev_bad, hook=None):
return passphrase
self.set_passphrase_cb(passphrase_cb)
try:
self.op_createkey(
userid,
algorithm,
0, # reserved
expires_in,
None, # extrakey
((constants.create.SIGN if sign else 0) |
(constants.create.ENCR if encrypt else 0) |
(constants.create.CERT if certify else 0) |
(constants.create.AUTH if authenticate else 0) |
(constants.create.NOPASSWD if passphrase is None else 0) |
(0 if expires else constants.create.NOEXPIRE) |
(constants.create.FORCE if force else 0)))
finally:
if util.is_a_string(passphrase):
self.pinentry_mode = old_pinentry_mode
gpgme.gpg_set_passphrase_cb(self, old_passphrase_cb)
return self.op_genkey_result()
def create_subkey(self,
key,
algorithm=None,
expires_in=0,
expires=True,
sign=False,
encrypt=False,
authenticate=False,
passphrase=None):
"""Create a subkey
Create a subkey for the given KEY. As subkeys are a concept
of OpenPGP, calling this is only valid for the OpenPGP
protocol.
ALGORITHM may be used to specify the public key encryption
algorithm for the new subkey. By default, a reasonable
default is chosen. You may use "future-default" to select an
algorithm that will be the default in a future implementation
of the engine. ALGORITHM may be a string like "rsa", or
"rsa2048" to explicitly request an algorithm and a key size.
EXPIRES_IN specifies the expiration time of the subkey in
number of seconds since the subkeys creation. By default, a
reasonable expiration time is chosen. If you want to create a
subkey that does not expire, use the keyword argument EXPIRES.
SIGN, ENCRYPT, and AUTHENTICATE can be used to request the
capabilities of the new subkey. If you don't request any, an
encryption subkey is generated.
If PASSPHRASE is None (the default), then the subkey will not
be protected with a passphrase. If PASSPHRASE is a string, it
will be used to protect the subkey. If PASSPHRASE is True,
the passphrase must be supplied using a passphrase callback or
out-of-band with a pinentry.
Keyword arguments:
algorithm -- public key algorithm, see above (default: reasonable)
expires_in -- expiration time in seconds (default: reasonable)
expires -- whether the subkey should expire (default: True)
sign -- request the signing capability (see above)
encrypt -- request the encryption capability (see above)
authenticate -- request the authentication capability (see above)
passphrase -- protect the subkey with a passphrase (default: no
passphrase)
Returns:
-- an object describing the result of the subkey creation
Raises:
GPGMEError -- as signaled by the underlying library
"""
if util.is_a_string(passphrase):
old_pinentry_mode = self.pinentry_mode
old_passphrase_cb = getattr(self, '_passphrase_cb', None)
self.pinentry_mode = constants.PINENTRY_MODE_LOOPBACK
def passphrase_cb(hint, desc, prev_bad, hook=None):
return passphrase
self.set_passphrase_cb(passphrase_cb)
try:
self.op_createsubkey(
key,
algorithm,
0, # reserved
expires_in,
((constants.create.SIGN if sign else 0) |
(constants.create.ENCR if encrypt else 0) |
(constants.create.AUTH if authenticate else 0) |
(constants.create.NOPASSWD if passphrase is None else 0) |
(0 if expires else constants.create.NOEXPIRE)))
finally:
if util.is_a_string(passphrase):
self.pinentry_mode = old_pinentry_mode
gpgme.gpg_set_passphrase_cb(self, old_passphrase_cb)
return self.op_genkey_result()
def key_add_uid(self, key, uid):
"""Add a UID
Add the uid UID to the given KEY. Calling this function is
only valid for the OpenPGP protocol.
Raises:
GPGMEError -- as signaled by the underlying library
"""
self.op_adduid(key, uid, 0)
def key_revoke_uid(self, key, uid):
"""Revoke a UID
Revoke the uid UID from the given KEY. Calling this function
is only valid for the OpenPGP protocol.
Raises:
GPGMEError -- as signaled by the underlying library
"""
self.op_revuid(key, uid, 0)
def key_sign(self, key, uids=None, expires_in=False, local=False):
"""Sign a key
Sign a key with the current set of signing keys. Calling this
function is only valid for the OpenPGP protocol.
If UIDS is None (the default), then all UIDs are signed. If
it is a string, then only the matching UID is signed. If it
is a list of strings, then all matching UIDs are signed. Note
that a case-sensitive exact string comparison is done.
EXPIRES_IN specifies the expiration time of the signature in
seconds. If EXPIRES_IN is False, the signature does not
expire.
Keyword arguments:
uids -- user ids to sign, see above (default: sign all)
expires_in -- validity period of the signature in seconds
(default: do not expire)
local -- create a local, non-exportable signature
(default: False)
Raises:
GPGMEError -- as signaled by the underlying library
"""
flags = 0
if uids is None or util.is_a_string(uids):
pass # through unchanged
else:
flags |= constants.keysign.LFSEP