-
Notifications
You must be signed in to change notification settings - Fork 29
/
test_gnupg.py
1649 lines (1513 loc) · 74.6 KB
/
test_gnupg.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 -*-
"""
A test harness for gnupg.py.
Copyright (C) 2008-2024 Vinay Sajip. All rights reserved.
"""
import argparse
import json
import logging
import os.path
import os
import re
import shutil
import stat
import sys
import tempfile
import unittest
try:
unicode
except NameError:
unicode = str
try:
from unittest import skipIf
except ImportError: # pragma: no cover
# For now, for Python < 2.7
def skipIf(condition, message):
if not condition:
return lambda x: x
else:
return lambda x: None
import gnupg
__author__ = 'Vinay Sajip'
__date__ = '$20-Sep-2024 17:23:25$'
ALL_TESTS = True
gnupg.log_everything = True
logger = logging.getLogger(__name__)
GPGBINARY = os.environ.get('GPGBINARY', 'gpg')
KEYS_TO_IMPORT = """-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG v1.4.9 (MingW32)
mQGiBEiH4QERBACm48JJsg2XGzWfL7f/fjp3wtrY+JIz6P07s7smr35kve+wl605
nqHtgjnIVpUVsbI9+xhIAPIkFIR6ZcQ7gRDhoT0bWKGkfdQ7YzXedVRPlQLdbpmR
K2pKKySpF35pJsPAYa73EVaxu2KrII4CyBxVQgNWfGwEbtL5FfzuHhVOZwCg6JF7
bgOMPmEwBLEHLmgiXbb5K48D/2xsXtWMkvgRp/ubcLxzbNjaHH6gSb2IfDi1+W/o
Bmfua6FksPnEDn7PWnBhCEO9rf1tV0FcrvkR9m2FGfx38tjssxDdLvX511gbfc/Q
DJxZ00A63BxI3xav8RiXlqpfQGXpLJmCLdeCh5DXOsVMCfepqRbWyJF0St7LDcq9
SmuXA/47dzb8puo9dNxA5Nj48I5g4ke3dg6nPn7aiBUQ35PfXjIktXB6/sQJtWWx
XNFX/GVUxqMM0/aCMPdtaoDkFtz1C6b80ngEz94vXzmON7PCgDY6LqZP1B1xbrkr
4jGSr68iq7ERT+7E/iF9xp+Ynl91KK7h8llY6zFw+yIe6vGlcLQvR2FyeSBHcm9z
cyAoQSB0ZXN0IHVzZXIpIDxnYXJ5Lmdyb3NzQGdhbW1hLmNvbT6I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2I8tvxsRMPp0I93XnuB
T+z7ykRxRjpMv6MfhWVcw5B0s7lPedLhcx657HfY49t36/CIZ9/zMKsduX7cTOAh
tO8f06R3yfjxLRD8y89frVP3+tGMvt2yGOd5TT0zht5yYcG6QkiHlfdgXqeE8nsU
2392Xn/RETq6xCj3kG6K3wbWqh0=
=2A5s
-----END PGP PRIVATE KEY BLOCK-----
"""
def is_list_with_len(o, n):
return isinstance(o, list) and len(o) == n
BASE64_PATTERN = re.compile(r'^(?:[A-Z0-9+/]{4})*(?:[A-Z0-9+/]{2}==|[A-Z0-9+/]{3}=)?$', re.I)
def get_key_data(s):
lines = s.split('\n')
result = ''
for line in lines:
m = BASE64_PATTERN.match(line)
if m:
result += line
return result
def compare_keys(k1, k2):
"Compare ASCII keys"
# See issue #57: we need to compare only the actual key data,
# ignoring things like spurious blank lines
return get_key_data(k1) != get_key_data(k2)
AGENT_CONFIG = '''allow-loopback-pinentry
log-file socket:///tmp/S.my-gnupg-log
verbose
debug ipc
'''
ENABLE_TOFU = 'ENABLE_TOFU' in os.environ
if ENABLE_TOFU: # pragma: no cover
GPG_CONFIG = 'trust-model tofu+pgp\ntofu-default-policy unknown\n'
def prepare_homedir(hd):
if not os.path.isdir(hd): # pragma: no cover
os.makedirs(hd)
os.chmod(hd, 0x1C0)
fn = os.path.join(hd, 'gpg-agent.conf')
with open(fn, 'w') as f:
f.write(AGENT_CONFIG)
if ENABLE_TOFU: # pragma: no cover
fn = os.path.join(hd, 'gpg.conf')
with open(fn, 'w') as f:
f.write(GPG_CONFIG)
class GPGTestCase(unittest.TestCase):
def setUp(self):
ident = self.id().rsplit('.', 1)[-1]
logger.debug('-- %s starting ---------------------------' % ident)
if 'STATIC_TEST_HOMEDIR' not in os.environ:
hd = tempfile.mkdtemp(prefix='keys-')
else: # pragma: no cover
hd = os.path.join(os.getcwd(), 'keys')
if os.path.exists(hd):
self.assertTrue(os.path.isdir(hd), 'Not a directory: %s' % hd)
shutil.rmtree(hd, ignore_errors=True)
prepare_homedir(hd)
self.homedir = hd
self.gpg = gpg = gnupg.GPG(gnupghome=hd, gpgbinary=GPGBINARY)
v = gpg.version
if v:
if v >= (2, ): # pragma: no cover
gpg.options = ['--debug-quick-random']
else:
gpg.options = ['--quick-random']
self.test_fn = test_fn = 'random_binary_data'
if not os.path.exists(test_fn): # pragma: no cover
data_file = open(test_fn, 'wb')
data_file.write(os.urandom(5120 * 1024))
data_file.close()
def tearDown(self):
if 'STATIC_TEST_HOMEDIR' not in os.environ:
shutil.rmtree(self.homedir, ignore_errors=True)
ident = self.id().rsplit('.', 1)[-1]
logger.debug('-- %s finished ---------------------------' % ident)
def test_environment(self):
"Test the environment by ensuring that setup worked"
hd = self.homedir
self.assertTrue(os.path.exists(hd) and os.path.isdir(hd), 'Not an existing directory: %s' % hd)
def test_list_keys_initial(self):
"Test that initially there are no keys"
public_keys = self.gpg.list_keys()
self.assertEqual(0, public_keys.returncode, 'Non-zero return code')
self.assertTrue(is_list_with_len(public_keys, 0), 'Empty list expected')
private_keys = self.gpg.list_keys(secret=True)
self.assertTrue(is_list_with_len(private_keys, 0), 'Empty list expected')
def generate_key(self, first_name, last_name, domain, passphrase=None, with_subkey=True):
"Generate a key"
params = {
'Key-Type': 'DSA',
'Key-Length': 1024,
'Name-Comment': 'A test user',
'Expire-Date': 0,
}
if with_subkey:
params['Subkey-Type'] = 'ELG-E'
params['Subkey-Length'] = 2048
options = self.gpg.options or []
if '--debug-quick-random' in options or '--quick-random' in options:
# If using the fake RNG, a key isn't regarded as valid
# unless its comment has the text (insecure!) in it.
params['Name-Comment'] = 'A test user (insecure!)'
params['Name-Real'] = '%s %s' % (first_name, last_name)
params['Name-Email'] = ('%s.%s@%s' % (first_name, last_name, domain)).lower()
if passphrase is None:
passphrase = ('%s%s' % (first_name[0], last_name)).lower()
params['Passphrase'] = passphrase
cmd = self.gpg.gen_key_input(**params)
return self.gpg.gen_key(cmd)
def do_key_generation(self):
"Test that key generation succeeds"
result = self.generate_key('Barbara', 'Brown', 'beta.com')
self.assertNotEqual(None, result, 'Non-null result')
return result
def test_key_generation_with_invalid_key_type(self):
"Test that key generation handles invalid key type"
params = {
'Key-Type': 'INVALID',
'Key-Length': 1024,
'Subkey-Type': 'ELG-E',
'Subkey-Length': 2048,
'Name-Comment': 'A test user',
'Expire-Date': 0,
'Name-Real': 'Test Name',
'Name-Email': '[email protected]',
}
cmd = self.gpg.gen_key_input(**params)
result = self.gpg.gen_key(cmd)
self.assertFalse(result.data, 'Null data result')
self.assertFalse(result.fingerprint, 'Null fingerprint result')
self.assertEqual(2, result.returncode, 'Unexpected return code')
def test_key_generation_with_colons(self):
"Test that key generation handles colons in key fields"
params = {
'key_type': 'RSA',
'name_real': 'urn:uuid:731c22c4-830f-422f-80dc-14a9fdae8c19',
'name_comment': 'dummy comment',
'name_email': '[email protected]',
}
if self.gpg.version >= (2, 1):
params['passphrase'] = 'foo'
cmd = self.gpg.gen_key_input(**params)
result = self.gpg.gen_key(cmd)
self.assertEqual(0, result.returncode, 'Non-zero return code')
keys = self.gpg.list_keys()
self.assertEqual(0, keys.returncode, 'Non-zero return code')
self.assertEqual(len(keys), 1)
key = keys[0]
uids = key['uids']
self.assertEqual(len(uids), 1)
uid = uids[0]
self.assertEqual(uid, 'urn:uuid:731c22c4-830f-422f-80dc-14a9fdae8c19 '
'(dummy comment) <[email protected]>')
def test_key_generation_with_escapes(self):
"Test that key generation handles escape characters"
params = {
'name_real': 'Test Name',
'name_comment': 'Funny chars: \\r\\n\\f\\v\\0\\b',
'name_email': '[email protected]',
}
if self.gpg.version >= (2, 1):
params['passphrase'] = 'foo'
cmd = self.gpg.gen_key_input(**params)
result = self.gpg.gen_key(cmd)
self.assertEqual(0, result.returncode, 'Non-zero return code')
keys = self.gpg.list_keys()
self.assertEqual(0, keys.returncode, 'Non-zero return code')
self.assertEqual(len(keys), 1)
key = keys[0]
uids = key['uids']
self.assertEqual(len(uids), 1)
uid = uids[0]
self.assertEqual(uid, 'Test Name (Funny chars: '
'\r\n\x0c\x0b\x00\x08) <[email protected]>')
@skipIf(os.name == 'nt', 'Test requires POSIX-style permissions')
def test_key_generation_failure(self):
if self.gpg.version < (2, 0): # pragma: no cover
raise unittest.SkipTest('gpg 1.x hangs in this test')
if not os.path.exists('rokeys'): # pragma: no cover
os.mkdir('rokeys')
os.chmod('rokeys', 0o400) # no one can write/search this directory
gpg = gnupg.GPG(gnupghome='rokeys', gpgbinary=GPGBINARY)
params = {
'Key-Type': 'RSA',
'Key-Length': 1024,
'Subkey-Type': 'ELG-E',
'Subkey-Length': 2048,
'Name-Comment': 'A test user',
'Expire-Date': 0,
'Name-Real': 'Test Name',
'Name-Email': '[email protected]',
}
cmd = gpg.gen_key_input(**params)
result = gpg.gen_key(cmd)
self.assertNotEqual(result.returncode, 0)
self.assertEqual(result.status, 'key not created')
def test_key_generation_input(self):
"Test that key generation input handles empty values, curves etc."
params = {
'key_type': ' ',
'key_length': 2048,
}
cmd = self.gpg.gen_key_input(**params)
self.assertTrue('Key-Type: RSA\n' in cmd)
params['key_type'] = 'DSA'
cmd = self.gpg.gen_key_input(**params)
self.assertTrue('Key-Type: DSA\n' in cmd)
params = {
'key_type': 'ECDSA',
'key_curve': 'nistp384',
'subkey_type': 'ECDH',
'subkey_curve': 'nistp384',
'name_comment': 'NIST P-384',
}
cmd = self.gpg.gen_key_input(**params)
for s in ('Key-Type: ECDSA', 'Key-Curve: nistp384', 'Subkey-Type: ECDH', 'Subkey-Curve: nistp384',
'Name-Comment: NIST P-384'):
self.assertTrue('%s\n' % s in cmd)
self.assertFalse('Key-Length: ' in cmd)
def test_add_subkey(self):
"Test that subkeys can be added"
if self.gpg.version[0] < 2: # pragma: no cover
raise unittest.SkipTest('Feature unavailable in GnuPG 1.x')
master_key = self.generate_key('Charlie', 'Clark', 'gamma.com', passphrase='123', with_subkey=False)
self.assertEqual(0, master_key.returncode, 'Non-zero return code')
result = self.gpg.add_subkey(master_key=master_key.fingerprint,
master_passphrase='123',
algorithm='dsa',
usage='sign',
expire=0)
self.assertEqual(0, result.returncode, 'Non-zero return code')
def test_add_subkey_with_invalid_key_type(self):
"Test that subkey generation handles invalid key type"
if self.gpg.version[0] < 2: # pragma: no cover
raise unittest.SkipTest('Feature unavailable in GnuPG 1.x')
master_key = self.generate_key('Charlie', 'Clark', 'gamma.com', passphrase='123', with_subkey=False)
self.assertEqual(0, master_key.returncode, 'Non-zero return code')
result = self.gpg.add_subkey(master_key=master_key.fingerprint,
master_passphrase='123',
algorithm='INVALID',
usage='sign',
expire=0)
self.assertFalse(result.data, 'Null data result')
self.assertEqual('', result.fingerprint, 'Empty fingerprint result')
self.assertEqual(2, result.returncode, 'Unexpected return code')
def test_deletion_subkey(self):
"Test that subkey deletion works"
if self.gpg.version[0] < 2: # pragma: no cover
raise unittest.SkipTest('Feature unavailable in GnuPG 1.x')
master_key = self.generate_key('Charlie', 'Clark', 'gamma.com', passphrase='123', with_subkey=False)
self.assertEqual(0, master_key.returncode, 'Non-zero return code')
subkey = self.gpg.add_subkey(master_key=master_key.fingerprint,
master_passphrase='123',
algorithm='dsa',
usage='sign',
expire=0)
self.assertEqual(0, subkey.returncode, 'Non-zero return code')
public_keys = self.gpg.list_keys()
key_info = public_keys[0]
private_keys = self.gpg.list_keys(secret=True)
secret_key_info = private_keys[0]
self.assertEqual(0, public_keys.returncode, 'Non-zero return code')
self.assertTrue(is_list_with_len(public_keys, 1), '1-element list expected')
self.assertEqual(len(key_info['subkeys']), 1, '1-element list expected')
self.assertTrue(is_list_with_len(private_keys, 1), '1-element list expected')
self.assertEqual(len(secret_key_info['subkeys']), 1, '1-element list expected')
result = self.gpg.delete_keys(subkey.fingerprint, secret=True, passphrase='123', exclamation_mode=True)
result = self.gpg.delete_keys(subkey.fingerprint, exclamation_mode=True)
self.assertEqual(0, result.returncode, 'Non-zero return code')
public_keys = self.gpg.list_keys()
key_info = public_keys[0]
private_keys = self.gpg.list_keys(secret=True)
secret_key_info = private_keys[0]
self.assertEqual(0, public_keys.returncode, 'Non-zero return code')
self.assertTrue(is_list_with_len(public_keys, 1), '1-element list expected')
self.assertEqual(len(key_info['subkeys']), 0, '0-element list expected')
self.assertTrue(is_list_with_len(private_keys, 1), '1-element list expected')
self.assertEqual(len(secret_key_info['subkeys']), 0, '1-element list expected')
def test_list_subkey_after_generation(self):
"Test that after subkey generation, the generated subkey is available"
if self.gpg.version[0] < 2: # pragma: no cover
raise unittest.SkipTest('Feature unavailable in GnuPG 1.x')
self.test_list_keys_initial()
master_key = self.generate_key('Charlie', 'Clark', 'gamma.com', passphrase='123', with_subkey=False)
self.assertEqual(0, master_key.returncode, 'Non-zero return code')
subkey_sign = self.gpg.add_subkey(master_key=master_key.fingerprint,
master_passphrase='123',
algorithm='dsa',
usage='sign',
expire=0)
self.assertEqual(0, subkey_sign.returncode, 'Non-zero return code')
subkey_encrypt = self.gpg.add_subkey(master_key=master_key.fingerprint,
master_passphrase='123',
algorithm='rsa',
usage='encrypt',
expire=0)
self.assertEqual(0, subkey_encrypt.returncode, 'Non-zero return code')
public_keys = self.gpg.list_keys()
self.assertEqual(0, public_keys.returncode, 'Non-zero return code')
self.assertTrue(is_list_with_len(public_keys, 1), '1-element list expected')
key_info = public_keys[0]
if self.gpg.version >= (2, 1):
self.assertTrue(key_info['keygrip'])
fp = key_info['fingerprint']
self.assertTrue(fp in public_keys.key_map)
self.assertTrue(public_keys.key_map[fp] is key_info)
self.assertEqual(fp, master_key.fingerprint)
self.assertTrue('subkey_info' in key_info)
skinfo = key_info['subkey_info']
self.assertEqual(len(skinfo), 2)
self.assertEqual(key_info['subkeys'][0][1], 's')
self.assertEqual(key_info['subkeys'][0][2], subkey_sign.fingerprint)
self.assertEqual(key_info['subkeys'][1][1], 'e')
self.assertEqual(key_info['subkeys'][1][2], subkey_encrypt.fingerprint)
for skid, _, sfp, grp in key_info['subkeys']:
self.assertTrue(skid in skinfo)
info = skinfo[skid]
self.assertEqual(info['keyid'], skid)
self.assertEqual(info['type'], 'sub')
self.assertTrue(sfp in public_keys.key_map)
self.assertTrue(public_keys.key_map[sfp] is key_info)
if self.gpg.version >= (2, 1):
self.assertTrue(grp)
def test_list_keys_after_generation(self):
"Test that after key generation, the generated key is available"
self.test_list_keys_initial()
self.do_key_generation()
public_keys = self.gpg.list_keys()
self.assertEqual(0, public_keys.returncode, 'Non-zero return code')
self.assertTrue(is_list_with_len(public_keys, 1), '1-element list expected')
key_info = public_keys[0]
if self.gpg.version >= (2, 1):
self.assertTrue(key_info['keygrip'])
fp = key_info['fingerprint']
self.assertTrue(fp in public_keys.key_map)
self.assertTrue(public_keys.key_map[fp] is key_info)
self.assertTrue('subkey_info' in key_info)
skinfo = key_info['subkey_info']
for skid, _, sfp, grp in key_info['subkeys']:
self.assertTrue(skid in skinfo)
info = skinfo[skid]
self.assertEqual(info['keyid'], skid)
self.assertEqual(info['type'], 'sub')
self.assertTrue(sfp in public_keys.key_map)
self.assertTrue(public_keys.key_map[sfp] is key_info)
if self.gpg.version >= (2, 1):
self.assertTrue(grp)
# now test with sigs=True
public_keys_sigs = self.gpg.list_keys(sigs=True)
self.assertEqual(0, public_keys_sigs.returncode, 'Non-zero return code')
self.assertTrue(is_list_with_len(public_keys_sigs, 1), '1-element list expected')
key_info = public_keys_sigs[0]
if self.gpg.version >= (2, 1):
self.assertTrue(key_info['keygrip'])
fp = key_info['fingerprint']
self.assertTrue(fp in public_keys_sigs.key_map)
self.assertTrue(public_keys_sigs.key_map[fp] is key_info)
self.assertTrue(is_list_with_len(key_info['sigs'], 2))
self.assertTrue('subkey_info' in key_info)
skinfo = key_info['subkey_info']
for siginfo in key_info['sigs']:
self.assertTrue(len(siginfo), 3)
for skid, _, sfp, grp in key_info['subkeys']:
self.assertTrue(skid in skinfo)
info = skinfo[skid]
self.assertEqual(info['keyid'], skid)
self.assertEqual(info['type'], 'sub')
self.assertTrue(sfp in public_keys_sigs.key_map)
self.assertTrue(public_keys_sigs.key_map[sfp] is key_info)
if self.gpg.version >= (2, 1):
self.assertTrue(grp)
private_keys = self.gpg.list_keys(secret=True)
self.assertEqual(0, private_keys.returncode, 'Non-zero return code')
self.assertTrue(is_list_with_len(private_keys, 1), '1-element list expected')
self.assertEqual(len(private_keys.fingerprints), 1)
key_info = private_keys[0]
if self.gpg.version >= (2, 1):
self.assertTrue(key_info['keygrip'])
self.assertTrue('subkey_info' in key_info)
skinfo = key_info['subkey_info']
self.assertTrue(skid in skinfo)
info = skinfo[skid]
self.assertEqual(info['keyid'], skid)
self.assertEqual(info['type'], 'ssb')
# Now do the same test, but using keyring and secret_keyring arguments
if self.gpg.version < (2, 1): # pragma: no cover
pkn = 'pubring.gpg'
skn = 'secring.gpg'
else:
# On GnuPG >= 2.1, --secret-keyring is obsolete and ignored,
# and the keyring file name has changed.
pkn = 'pubring.kbx'
skn = None
hd = self.homedir
if os.name == 'posix':
pkn = os.path.join(hd, pkn)
if skn: # pragma: no cover
skn = os.path.join(hd, skn)
gpg = gnupg.GPG(gnupghome=hd, gpgbinary=GPGBINARY, keyring=pkn, secret_keyring=skn)
logger.debug('Using keyring and secret_keyring arguments')
public_keys_2 = gpg.list_keys()
self.assertEqual(0, public_keys_2.returncode, 'Non-zero return code')
self.assertEqual(public_keys_2, public_keys)
private_keys_2 = gpg.list_keys(secret=True)
self.assertEqual(0, private_keys_2.returncode, 'Non-zero return code')
self.assertEqual(private_keys_2, private_keys)
# generate additional keys so that we can test listing a subset of
# keys
def get_names(key_map):
result = set()
for info in key_map.values():
for uid in info['uids']:
uid = uid.replace(' (A test user (insecure!))', '')
result.add(uid)
return result
result = self.generate_key('Charlie', 'Clark', 'gamma.com')
self.assertNotEqual(None, result, 'Non-null result')
self.assertEqual(0, result.returncode, 'Non-zero return code')
result = self.generate_key('Donna', 'Davis', 'delta.com')
self.assertNotEqual(None, result, 'Non-null result')
self.assertEqual(0, result.returncode, 'Non-zero return code')
public_keys = gpg.list_keys()
self.assertEqual(0, public_keys.returncode, 'Non-zero return code')
self.assertEqual(len(public_keys), 3)
actual = get_names(public_keys.key_map)
expected = set([
'Barbara Brown <[email protected]>', 'Charlie Clark <[email protected]>',
'Donna Davis <[email protected]>'
])
self.assertEqual(actual, expected)
# specify a single key as a string
public_keys = gpg.list_keys(keys='Donna Davis')
self.assertEqual(0, public_keys.returncode, 'Non-zero return code')
actual = get_names(public_keys.key_map)
expected = set(['Donna Davis <[email protected]>'])
self.assertEqual(actual, expected)
# specify multiple keys
public_keys = gpg.list_keys(keys=['Donna', 'Barbara'])
self.assertEqual(0, public_keys.returncode, 'Non-zero return code')
actual = get_names(public_keys.key_map)
expected = set(['Barbara Brown <[email protected]>', 'Donna Davis <[email protected]>'])
self.assertEqual(actual, expected)
def test_key_trust(self):
"Test that trusting keys works"
gpg = self.gpg
result = gpg.import_keys(KEYS_TO_IMPORT)
self.assertEqual(0, result.returncode, 'Non-zero return code')
keys = gpg.list_keys()
self.assertEqual(0, keys.returncode, 'Non-zero return code')
fingerprints = []
for key in keys:
self.assertEqual(key['ownertrust'], '-')
fingerprints.append(key['fingerprint'])
cases = (
('TRUST_NEVER', 'n'),
('TRUST_MARGINAL', 'm'),
('TRUST_FULLY', 'f'),
('TRUST_ULTIMATE', 'u'),
('TRUST_UNDEFINED', 'q'),
('TRUST_EXPIRED', 'e'),
)
for param, expected in cases:
gpg.trust_keys(fingerprints, param)
keys = gpg.list_keys(keys=fingerprints)
for key in keys:
self.assertEqual(key['ownertrust'], expected)
self.assertRaises(ValueError, gpg.trust_keys, fingerprints, 'TRUST_FOOBAR')
self.assertRaises(ValueError, gpg.trust_keys, 'NO_SUCH_FINGERPRINT', 'TRUST_NEVER')
# gpg should raise an error for the following - but it doesn't!
# self.assertRaises(ValueError, gpg.trust_keys,
# 'BADF00DBADF00DBADF00DBADF00DBADF00DBADF0',
# 'TRUST_NEVER')
def test_list_signatures(self):
imported = self.gpg.import_keys(SIGNED_KEYS)
self.assertEqual(0, imported.returncode, 'Non-zero return code')
keys = self.gpg.list_keys(keys=['18897CA2'])
self.assertEqual(0, keys.returncode, 'Non-zero return code')
self.assertTrue(is_list_with_len(keys, 1), 'importing test signed key')
sigs = self.gpg.list_keys(keys=['18897CA2'], sigs=True)[0]['sigs']
logger.debug('testing self-signature')
self.assertTrue(('BC6F350FB3D04076', 'Joshua Calvert (A test user) <[email protected]>', '13x') in sigs)
logger.debug('testing subkey self-signature')
self.assertTrue(('BC6F350FB3D04076', 'Joshua Calvert (A test user) <[email protected]>', '18x') in sigs)
logger.debug('testing other signature')
self.assertTrue(('057CCF658C074FDA', 'Winston Smith (A test user) <[email protected]>', '10x') in sigs)
def test_scan_keys(self):
"Test that external key files can be scanned"
# Don't use SkipTest for now, as not available for Python < 2.7
if self.gpg.version < (2, 1): # pragma: no cover
expected = set([
'Andrew Able (A test user) <[email protected]>',
'Barbara Brown (A test user) <[email protected]>',
'Charlie Clark (A test user) <[email protected]>',
])
test_files = ('test_pubring.gpg', 'test_secring.gpg')
key_fn = None
else:
expected = set([
'Gary Gross (A test user) <[email protected]>',
'Danny Davis (A test user) <[email protected]>',
])
fd, key_fn = tempfile.mkstemp(prefix='pygpg-test-')
os.write(fd, KEYS_TO_IMPORT.encode('ascii'))
os.close(fd)
test_files = (key_fn, )
try:
for fn in test_files:
logger.debug('scanning keys in %s', fn)
data = self.gpg.scan_keys(fn)
self.assertEqual(0, data.returncode, 'Non-zero return code')
uids = set()
for d in data:
uids.add(d['uids'][0])
self.assertEqual(uids, expected)
finally:
if key_fn:
os.remove(key_fn)
def test_scan_keys_mem(self):
"Test that external keys in memory can be scanned"
expected = set([
'Gary Gross (A test user) <[email protected]>',
'Danny Davis (A test user) <[email protected]>',
])
for key in (KEYS_TO_IMPORT, ):
logger.debug('testing scan_keys')
data = self.gpg.scan_keys_mem(key)
self.assertEqual(0, data.returncode, 'Non-zero return code')
uids = set()
for d in data:
uids.add(d['uids'][0])
self.assertEqual(uids, expected)
def test_encryption_and_decryption(self):
"Test that encryption and decryption works"
key = self.generate_key('Andrew', 'Able', 'alpha.com', passphrase='andy')
self.assertEqual(0, key.returncode, 'Non-zero return code')
andrew = key.fingerprint
key = self.generate_key('Barbara', 'Brown', 'beta.com')
self.assertEqual(0, key.returncode, 'Non-zero return code')
barbara = key.fingerprint
gpg = self.gpg
if gnupg._py3k:
data = 'Hello, André!'
else: # pragma: no cover
data = unicode('Hello, André', gpg.encoding)
data = data.encode(gpg.encoding)
result = gpg.encrypt(data, barbara)
self.assertEqual(0, result.returncode, 'Non-zero return code')
edata = str(result)
self.assertNotEqual(data, edata, 'Data must have changed')
self.assertRaises(ValueError, gpg.decrypt, edata, passphrase='bbr\x00own')
self.assertRaises(ValueError, gpg.decrypt, edata, passphrase='bbr\rown')
self.assertRaises(ValueError, gpg.decrypt, edata, passphrase='bbr\nown')
ddata = gpg.decrypt(edata, passphrase='bbrown')
self.assertEqual(0, ddata.returncode, 'Non-zero return code')
if data != ddata.data: # pragma: no cover
logger.debug('was: %r', data)
logger.debug('new: %r', ddata.data)
self.assertEqual(data, ddata.data, 'Round-trip must work')
result = gpg.encrypt(data, [andrew, barbara])
self.assertEqual(0, result.returncode, 'Non-zero return code')
edata = str(result)
self.assertNotEqual(data, edata, 'Data must have changed')
ddata = gpg.decrypt(edata, passphrase='andy')
self.assertEqual(0, ddata.returncode, 'Non-zero return code')
self.assertEqual(data, ddata.data, 'Round-trip must work')
ddata = gpg.decrypt(edata, passphrase='bbrown')
self.assertEqual(data, ddata.data, 'Round-trip must work')
# Test symmetric encryption
data = 'chippy was here'
self.assertRaises(ValueError, gpg.encrypt, data, None, passphrase='bbr\x00own', symmetric=True)
self.assertRaises(ValueError, gpg.encrypt, data, None, passphrase='bbr\rown', symmetric=True)
self.assertRaises(ValueError, gpg.encrypt, data, None, passphrase='bbr\nown', symmetric=True)
result = gpg.encrypt(data, None, passphrase='bbrown', symmetric=True)
self.assertEqual(0, result.returncode, 'Non-zero return code')
edata = str(result)
ddata = gpg.decrypt(edata, passphrase='bbrown')
self.assertEqual(0, ddata.returncode, 'Non-zero return code')
self.assertEqual(data, str(ddata))
# Test symmetric encryption with non-default cipher
result = gpg.encrypt(data, None, passphrase='bbrown', symmetric='AES256')
self.assertEqual(0, result.returncode, 'Non-zero return code')
edata = str(result)
ddata = gpg.decrypt(edata, passphrase='bbrown')
self.assertEqual(0, ddata.returncode, 'Non-zero return code')
self.assertEqual(data, str(ddata))
# Test that you can't encrypt with no recipients
self.assertRaises(ValueError, self.gpg.encrypt, data, [])
# Test extra_args parameter
result = gpg.encrypt(data, barbara, extra_args=['-z', '0'])
self.assertEqual(0, result.returncode, 'Non-zero return code')
edata = str(result)
ddata = gpg.decrypt(edata, passphrase='bbrown')
self.assertEqual(data.encode('ascii'), ddata.data, 'Round-trip must work')
# Test on_data functionality
chunks = []
def collector(data):
chunks.append(data)
gpg.on_data = collector
result = gpg.encrypt(data, barbara)
self.assertEqual(0, result.returncode, 'Non-zero return code')
self.assertIsNone(result.on_data_failure)
edata = str(result)
self.assertTrue(chunks)
expected = type(chunks[0])().join(chunks)
self.assertEqual(expected.decode('ascii'), edata)
chunks = []
ddata = gpg.decrypt(edata, passphrase='bbrown')
self.assertEqual(0, ddata.returncode, 'Non-zero return code')
self.assertEqual(data.encode('ascii'), ddata.data, 'Round-trip must work')
self.assertIsNone(result.on_data_failure)
expected = type(chunks[0])().join(chunks)
self.assertEqual(expected.decode('ascii'), data)
# test with on-data generating an exception
def exceptor(data):
raise ValueError('exception in on_data')
chunks = []
gpg.on_data = exceptor
ddata = gpg.decrypt(edata, passphrase='bbrown')
self.assertIs(type(ddata.on_data_failure), ValueError)
self.assertEqual(str(ddata.on_data_failure), 'exception in on_data')
# test signing with encryption and verification during decryption
logger.debug('encrypting with signature')
gpg.on_data = None
result = gpg.encrypt(data, barbara, sign=andrew, passphrase='andy')
self.assertEqual(0, result.returncode, 'Non-zero return code')
edata = str(result)
logger.debug('decrypting with verification')
ddata = gpg.decrypt(edata, passphrase='bbrown')
self.assertEqual(0, ddata.returncode, 'Non-zero return code')
self.assertEqual(data.encode('ascii'), ddata.data, 'Round-trip must work')
sig_values = list(ddata.sig_info.values())
self.assertTrue(sig_values)
sig_info = sig_values[0]
self.assertEqual(sig_info['fingerprint'], andrew)
logger.debug('decrypting with verification succeeded')
def test_import_and_export(self):
"Test that key import and export works"
self.test_list_keys_initial()
gpg = self.gpg
result = gpg.import_keys(KEYS_TO_IMPORT)
self.assertEqual(0, result.returncode, 'Non-zero return code')
self.assertTrue(bool(result))
self.assertEqual(result.summary(), '2 imported')
public_keys = gpg.list_keys()
self.assertEqual(0, public_keys.returncode, 'Non-zero return code')
self.assertTrue(is_list_with_len(public_keys, 2), '2-element list expected')
private_keys = gpg.list_keys(secret=True)
self.assertEqual(0, private_keys.returncode, 'Non-zero return code')
self.assertTrue(is_list_with_len(private_keys, 0), 'Empty list expected')
ascii = gpg.export_keys([k['keyid'] for k in public_keys])
self.assertTrue(ascii.find('PGP PUBLIC KEY BLOCK') >= 0, 'Exported key should be public')
ascii = ascii.replace('\r', '').strip()
match = compare_keys(ascii, KEYS_TO_IMPORT)
if match: # pragma: no cover
logger.debug('was: %r', KEYS_TO_IMPORT)
logger.debug('now: %r', ascii)
self.assertEqual(0, match, 'Keys must match')
# Generate a key so we can test exporting private keys
key = self.do_key_generation()
if self.gpg.version < (2, 1): # pragma: no cover
passphrase = None
else:
passphrase = 'bbrown'
ascii = gpg.export_keys(key.fingerprint, True, passphrase=passphrase)
self.assertTrue(isinstance(ascii, gnupg.text_type))
self.assertTrue(ascii.find('PGP PRIVATE KEY BLOCK') >= 0, 'Exported key should be private')
binary = gpg.export_keys(key.fingerprint, True, armor=False, passphrase=passphrase)
self.assertFalse(isinstance(binary, gnupg.text_type))
# import a secret key, and confirm that it's found in the list of
# secret keys.
result = gpg.import_keys(SECRET_KEY)
self.assertEqual(0, result.returncode, 'Non-zero return code')
self.assertEqual(result.summary(), '1 imported')
private_keys = gpg.list_keys(secret=True)
self.assertTrue(is_list_with_len(private_keys, 2))
found = False
for pk in private_keys:
if pk['keyid'].endswith('D2209820'):
found = True
break
self.assertTrue(found)
self.assertEqual(pk['uids'][0], 'Autogenerated Key <user1@test>')
def test_import_only(self):
"Test that key import works"
self.test_list_keys_initial()
result = self.gpg.import_keys(KEYS_TO_IMPORT)
self.assertEqual(0, result.returncode, 'Non-zero return code')
public_keys = self.gpg.list_keys()
self.assertEqual(0, public_keys.returncode, 'Non-zero return code')
self.assertTrue(is_list_with_len(public_keys, 2), '2-element list expected')
private_keys = self.gpg.list_keys(secret=True)
self.assertEqual(0, private_keys.returncode, 'Non-zero return code')
self.assertTrue(is_list_with_len(private_keys, 0), 'Empty list expected')
ascii = self.gpg.export_keys([k['keyid'] for k in public_keys])
self.assertTrue(ascii.find('PGP PUBLIC KEY BLOCK') >= 0, 'Exported key should be public')
ascii = ascii.replace('\r', '').strip()
match = compare_keys(ascii, KEYS_TO_IMPORT)
if match: # pragma: no cover
logger.debug('was: %r', KEYS_TO_IMPORT)
logger.debug('now: %r', ascii)
self.assertEqual(0, match, 'Keys must match')
def test_signature_verification(self):
"Test that signing and verification works"
key = self.generate_key('Andrew', 'Able', 'alpha.com')
if gnupg._py3k:
data = 'Hello, André!'
else: # pragma: no cover
data = unicode('Hello, André', self.gpg.encoding)
data = data.encode(self.gpg.encoding)
self.assertRaises(ValueError, self.gpg.sign, data, keyid=key.fingerprint, passphrase='bbr\x00own')
self.assertRaises(ValueError, self.gpg.sign, data, keyid=key.fingerprint, passphrase='bbr\rown')
self.assertRaises(ValueError, self.gpg.sign, data, keyid=key.fingerprint, passphrase='bbr\nown')
sig = self.gpg.sign(data, keyid=key.fingerprint, passphrase='bbrown')
self.assertFalse(sig, 'Bad passphrase should fail')
sig = self.gpg.sign(data, keyid=key.fingerprint, passphrase='aable')
self.assertEqual(0, sig.returncode, 'Non-zero return code')
self.assertTrue(sig, 'Good passphrase should succeed')
if sig.username: # pragma: no cover
# not set in recent versions of GnuPG e.g. 2.2.5
self.assertTrue(sig.username.startswith('Andrew Able'))
if sig.key_id: # pragma: no cover
self.assertTrue(key.fingerprint.endswith(sig.key_id))
self.assertTrue(sig.hash_algo)
logger.debug('verification start')
verified = self.gpg.verify(sig.data)
self.assertEqual(0, verified.returncode, 'Non-zero return code')
logger.debug('verification end')
if key.fingerprint != verified.fingerprint: # pragma: no cover
logger.debug('key: %r', key.fingerprint)
logger.debug('ver: %r', verified.fingerprint)
self.assertEqual(key.fingerprint, verified.fingerprint, 'Fingerprints must match')
self.assertEqual(verified.trust_level, verified.TRUST_ULTIMATE)
self.assertEqual(verified.trust_text, 'TRUST_ULTIMATE')
data_file = open(self.test_fn, 'rb')
sig = self.gpg.sign_file(data_file, keyid=key.fingerprint, passphrase='aable')
self.assertEqual(0, sig.returncode, 'Non-zero return code')
data_file.close()
self.assertTrue(sig, 'File signing should succeed')
self.assertTrue(sig.hash_algo)
try:
stream = gnupg._make_binary_stream(sig.data, self.gpg.encoding)
verified = self.gpg.verify_file(stream)
except UnicodeDecodeError: # pragma: no cover
# sometimes happens in Python 2.6
from io import BytesIO
verified = self.gpg.verify_file(BytesIO(sig.data))
self.assertEqual(0, verified.returncode, 'Non-zero return code')
if key.fingerprint != verified.fingerprint: # pragma: no cover
logger.debug('key: %r', key.fingerprint)
logger.debug('ver: %r', verified.fingerprint)
self.assertEqual(key.fingerprint, verified.fingerprint, 'Fingerprints must match')
data_file = open(self.test_fn, 'rb')
sig = self.gpg.sign_file(data_file, keyid=key.fingerprint, passphrase='aable', detach=True)
self.assertEqual(0, sig.returncode, 'Non-zero return code')
data_file.close()
self.assertTrue(sig, 'File signing should succeed')
self.assertTrue(sig.hash_algo)
try:
file = gnupg._make_binary_stream(sig.data, self.gpg.encoding)