-
Notifications
You must be signed in to change notification settings - Fork 60
/
Copy pathcli_tests.py
executable file
·5199 lines (4743 loc) · 261 KB
/
cli_tests.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
#!/usr/bin/env python
import logging
import os
import os.path
import re
import shutil
import sys
import tempfile
import time
import unittest
import random
from platform import architecture
from cli_common import (file_text, find_utility, is_windows, list_upto,
path_for_gpg, pswd_pipe, raise_err, random_text,
run_proc, decode_string_escape, CONSOLE_ENCODING,
set_workdir)
from gnupg import GnuPG as GnuPG
from rnp import Rnp as Rnp
WORKDIR = ''
RNP = ''
RNPK = ''
GPG = ''
GPGCONF = ''
RNPDIR = ''
GPGHOME = None
PASSWORD = 'password'
RMWORKDIR = True
GPG_AEAD = False
GPG_AEAD_EAX = False
GPG_AEAD_OCB = False
GPG_NO_OLD = False
GPG_BRAINPOOL = False
TESTS_SUCCEEDED = []
TESTS_FAILED = []
TEST_WORKFILES = []
# Supported features
RNP_TWOFISH = True
RNP_BRAINPOOL = True
RNP_AEAD_EAX = True
RNP_AEAD_OCB = True
RNP_AEAD_OCB_AES = False
RNP_AEAD = True
RNP_IDEA = True
RNP_BLOWFISH = True
RNP_CAST5 = True
RNP_RIPEMD160 = True
# Botan may cause AV during OCB decryption in certain cases, see https://github.com/randombit/botan/issues/3812
RNP_BOTAN_OCB_AV = False
if sys.version_info >= (3,):
unichr = chr
def escape_regex(str):
return '^' + ''.join((c, "[\\x{:02X}]".format(ord(c)))[0 <= ord(c) <= 0x20 \
or c in ['[',']','(',')','|','"','$','.','*','^','$','\\','+','?','{','}']] for c in str) + '$'
UNICODE_LATIN_CAPITAL_A_GRAVE = unichr(192)
UNICODE_LATIN_SMALL_A_GRAVE = unichr(224)
UNICODE_LATIN_CAPITAL_A_MACRON = unichr(256)
UNICODE_LATIN_SMALL_A_MACRON = unichr(257)
UNICODE_GREEK_CAPITAL_HETA = unichr(880)
UNICODE_GREEK_SMALL_HETA = unichr(881)
UNICODE_GREEK_CAPITAL_OMEGA = unichr(937)
UNICODE_GREEK_SMALL_OMEGA = unichr(969)
UNICODE_CYRILLIC_CAPITAL_A = unichr(0x0410)
UNICODE_CYRILLIC_SMALL_A = unichr(0x0430)
UNICODE_CYRILLIC_CAPITAL_YA = unichr(0x042F)
UNICODE_CYRILLIC_SMALL_YA = unichr(0x044F)
UNICODE_SEQUENCE_1 = UNICODE_LATIN_CAPITAL_A_GRAVE + UNICODE_LATIN_SMALL_A_MACRON \
+ UNICODE_GREEK_CAPITAL_HETA + UNICODE_GREEK_SMALL_OMEGA \
+ UNICODE_CYRILLIC_CAPITAL_A + UNICODE_CYRILLIC_SMALL_YA
UNICODE_SEQUENCE_2 = UNICODE_LATIN_SMALL_A_GRAVE + UNICODE_LATIN_CAPITAL_A_MACRON \
+ UNICODE_GREEK_SMALL_HETA + UNICODE_GREEK_CAPITAL_OMEGA \
+ UNICODE_CYRILLIC_SMALL_A + UNICODE_CYRILLIC_CAPITAL_YA
WEIRD_USERID_UNICODE_1 = unichr(160) + unichr(161) \
+ UNICODE_SEQUENCE_1 + unichr(40960) + u'@rnp'
WEIRD_USERID_UNICODE_2 = unichr(160) + unichr(161) \
+ UNICODE_SEQUENCE_2 + unichr(40960) + u'@rnp'
WEIRD_USERID_SPECIAL_CHARS = '\\}{][)^*.+(\t\n|$@rnp'
WEIRD_USERID_SPACE = ' '
WEIRD_USERID_QUOTE = '"'
WEIRD_USERID_SPACE_AND_QUOTE = ' "'
WEIRD_USERID_QUOTE_AND_SPACE = '" '
WEIRD_USERID_TOO_LONG = 'x' * 125 + '@rnp' # totaling 129 (MAX_USER_ID + 1)
# Key userids
KEY_ENCRYPT = 'encryption@rnp'
KEY_SIGN_RNP = 'signing@rnp'
KEY_SIGN_GPG = 'signing@gpg'
KEY_ENC_RNP = 'enc@rnp'
AT_EXAMPLE = '@example.com'
# Keyrings
PUBRING = 'pubring.gpg'
SECRING = 'secring.gpg'
PUBRING_1 = 'keyrings/1/pubring.gpg'
SECRING_1 = 'keyrings/1/secring.gpg'
KEYRING_DIR_1 = 'keyrings/1'
KEYRING_DIR_3 = 'keyrings/3'
SECRING_G10 = 'test_stream_key_load/g10'
KEY_ALICE_PUB = 'test_key_validity/alice-pub.asc'
KEY_ALICE_SUB_PUB = 'test_key_validity/alice-sub-pub.pgp'
KEY_ALICE_SEC = 'test_key_validity/alice-sec.asc'
KEY_ALICE_SUB_SEC = 'test_key_validity/alice-sub-sec.pgp'
KEY_ALICE = 'Alice <alice@rnp>'
KEY_25519_NOTWEAK_SEC = 'test_key_edge_cases/key-25519-non-tweaked-sec.asc'
# Messages
MSG_TXT = 'test_messages/message.txt'
MSG_ES_25519 = 'test_messages/message.txt.enc-sign-25519'
MSG_SIG_CRCR = 'test_messages/message.text-sig-crcr.sig'
# Extensions
EXT_SIG = '.txt.sig'
EXT_ASC = '.txt.asc'
EXT_PGP = '.txt.pgp'
# Misc
GPG_LOOPBACK = '--pinentry-mode=loopback'
# Regexps
RE_RSA_KEY = r'(?s)^' \
r'# .*' \
r':public key packet:\s+' \
r'version 4, algo 1, created \d+, expires 0\s+' \
r'pkey\[0\]: \[(\d{4}) bits\]\s+' \
r'pkey\[1\]: \[17 bits\]\s+' \
r'keyid: ([0-9A-F]{16})\s+' \
r'# .*' \
r':user ID packet: "(.+)"\s+' \
r'# .*' \
r':signature packet: algo 1, keyid \2\s+' \
r'.*' \
r'# .*' \
r':public sub key packet:' \
r'.*' \
r':signature packet: algo 1, keyid \2\s+' \
r'.*$'
RE_RSA_KEY_LIST = r'^\s*' \
r'2 keys found\s+' \
r'pub\s+(\d{4})/RSA ([0-9a-z]{16}) \d{4}-\d{2}-\d{2} \[.*\]\s+' \
r'([0-9a-z]{40})\s+' \
r'uid\s+(.+)\s+' \
r'sub.+\s+' \
r'[0-9a-z]{40}\s+$'
RE_MULTIPLE_KEY_LIST = r'(?s)^\s*(\d+) (?:key|keys) found.*$'
RE_MULTIPLE_KEY_5 = r'(?s)^\s*' \
r'10 keys found.*' \
r'.+uid\s+0@rnp-multiple' \
r'.+uid\s+1@rnp-multiple' \
r'.+uid\s+2@rnp-multiple' \
r'.+uid\s+3@rnp-multiple' \
r'.+uid\s+4@rnp-multiple.*$'
RE_MULTIPLE_SUBKEY_3 = r'(?s)^\s*' \
r'3 keys found.*$'
RE_MULTIPLE_SUBKEY_8 = r'(?s)^\s*' \
r'8 keys found.*$'
RE_GPG_SINGLE_RSA_KEY = r'(?s)^\s*' \
r'.+-+\s*' \
r'pub\s+rsa.+' \
r'\s+([0-9A-F]{40})\s*' \
r'uid\s+.+rsakey@gpg.*'
RE_GPG_GOOD_SIGNATURE = r'(?s)^.*' \
r'gpg: Signature made .*' \
r'gpg: Good signature from "(.*)".*'
RE_RNP_GOOD_SIGNATURE = r'(?s)^.*' \
r'Good signature made .*' \
r'using .* key .*' \
r'pub .*' \
r'uid\s+(.*)\s*' \
r'Signature\(s\) verified successfully.*$'
RE_RNP_ENCRYPTED_KEY = r'(?s)^.*' \
r'Secret key packet.*' \
r'secret key material:.*' \
r'encrypted secret key data:.*' \
r'UserID packet.*' \
r'id: enc@rnp.*' \
r'Secret subkey packet.*' \
r'secret key material:.*' \
r'encrypted secret key data:.*$'
RE_RNP_REVOCATION_SIG = r'(?s)' \
r':armored input\n' \
r':off 0: packet header .* \(tag 2, len .*' \
r'Signature packet.*' \
r'version: 4.*' \
r'type: 32 \(Key revocation signature\).*' \
r'public key algorithm:.*' \
r'hashed subpackets:.*' \
r':type 33, len 21.*' \
r'issuer fingerprint:.*' \
r':type 2, len 4.*' \
r'signature creation time:.*' \
r':type 29.*' \
r'reason for revocation: (.*)' \
r'message: (.*)' \
r'unhashed subpackets:.*' \
r':type 16, len 8.*' \
r'issuer key ID: .*$'
RE_GPG_REVOCATION_IMPORT = r'(?s)^.*' \
r'key 0451409669FFDE3C: "Alice <alice@rnp>" revocation certificate imported.*' \
r'Total number processed: 1.*' \
r'new key revocations: 1.*$'
RE_SIG_1_IMPORT = r'(?s)^.*Import finished: 1 new signature, 0 unchanged, 0 unknown.*'
RE_KEYSTORE_INFO = r'(?s)^.*fatal: cannot set keystore info'
RNP_TO_GPG_ZALGS = { 'zip' : '1', 'zlib' : '2', 'bzip2' : '3' }
# These are mostly identical
RNP_TO_GPG_CIPHERS = {'AES' : 'aes128', 'AES192' : 'aes192', 'AES256' : 'aes256',
'TWOFISH' : 'twofish', 'CAMELLIA128' : 'camellia128',
'CAMELLIA192' : 'camellia192', 'CAMELLIA256' : 'camellia256',
'IDEA' : 'idea', '3DES' : '3des', 'CAST5' : 'cast5',
'BLOWFISH' : 'blowfish'}
# Error messages
RNP_DATA_DIFFERS = 'rnp decrypted data differs'
GPG_DATA_DIFFERS = 'gpg decrypted data differs'
KEY_GEN_FAILED = 'key generation failed'
KEY_LIST_FAILED = 'key list failed'
KEY_LIST_WRONG = 'wrong key list output'
PKT_LIST_FAILED = 'packet listing failed'
ALICE_IMPORT_FAIL = 'Alice key import failed'
ENC_FAILED = 'encryption failed'
DEC_FAILED = 'decryption failed'
DEC_DIFFERS = 'Decrypted data differs'
GPG_IMPORT_FAILED = 'gpg key import failed'
def check_packets(fname, regexp):
ret, output, err = run_proc(GPG, ['--homedir', '.',
'--list-packets', path_for_gpg(fname)])
if ret != 0:
logging.error(err)
return None
else:
result = re.match(regexp, output)
if not result:
logging.debug('Wrong packets:')
logging.debug(output)
return result
def clear_keyrings():
shutil.rmtree(RNPDIR, ignore_errors=True)
os.mkdir(RNPDIR, 0o700)
run_proc(GPGCONF, ['--homedir', GPGHOME, '--kill', 'gpg-agent'])
while os.path.isdir(GPGDIR):
try:
shutil.rmtree(GPGDIR)
except Exception:
time.sleep(0.1)
os.mkdir(GPGDIR, 0o700)
def allow_y2k38_on_32bit(filename):
if architecture()[0] == '32bit':
return [filename, filename + '_y2k38']
else:
return [filename]
def compare_files(src, dst, message):
if file_text(src) != file_text(dst):
raise_err(message)
def compare_file(src, string, message):
if file_text(src) != string:
raise_err(message)
def compare_file_any(srcs, string, message):
for src in srcs:
if file_text(src) == string:
return
raise_err(message)
def compare_file_ex(src, string, message, symbol='?'):
ftext = file_text(src)
if len(ftext) != len(string):
raise_err(message)
for i in range(0, len(ftext)):
if (ftext[i] != symbol[0]) and (ftext[i] != string[i]):
raise_err(message)
def remove_files(*args):
for fpath in args:
try:
os.remove(fpath)
except Exception:
# Ignore if file cannot be removed
pass
def reg_workfiles(mainname, *exts):
global TEST_WORKFILES
res = []
for ext in exts:
fpath = os.path.join(WORKDIR, mainname + ext)
if fpath in TEST_WORKFILES:
logging.warn('Warning! Path {} is already in TEST_WORKFILES'.format(fpath))
else:
TEST_WORKFILES += [fpath]
res += [fpath]
return res
def clear_workfiles():
global TEST_WORKFILES
remove_files(*TEST_WORKFILES)
TEST_WORKFILES = []
def rnp_genkey_rsa(userid, bits=2048, pswd=PASSWORD):
pipe = pswd_pipe(pswd)
ret, _, err = run_proc(RNPK, ['--numbits', str(bits), '--homedir', RNPDIR, '--pass-fd', str(pipe),
'--notty', '--s2k-iterations', '50000', '--userid', userid, '--generate-key'])
os.close(pipe)
if ret != 0:
raise_err('rsa key generation failed', err)
def rnp_params_insert_z(params, pos, z):
if z:
if len(z) > 0 and z[0] != None:
params[pos:pos] = ['--' + z[0]]
if len(z) > 1 and z[1] != None:
params[pos:pos] = ['-z', str(z[1])]
def rnp_params_insert_aead(params, pos, aead):
if aead != None:
params[pos:pos] = ['--aead=' + aead[0]] if len(aead) > 0 and aead[0] != None else ['--aead']
if len(aead) > 1 and aead[1] != None:
params[pos + 1:pos + 1] = ['--aead-chunk-bits=' + str(aead[1])]
def rnp_encrypt_file_ex(src, dst, recipients=None, passwords=None, aead=None, cipher=None,
z=None, armor=False, s2k_iter=False, s2k_msec=False):
params = ['--homedir', RNPDIR, src, '--output', dst]
# Recipients. None disables PK encryption, [] to use default key. Otherwise list of ids.
if recipients != None:
params[2:2] = ['--encrypt']
for userid in reversed(recipients):
params[2:2] = ['-r', escape_regex(userid)]
# Passwords to encrypt to. None or [] disables password encryption.
if passwords:
if recipients is None:
params[2:2] = ['-c']
if s2k_iter != False:
params += ['--s2k-iterations', str(s2k_iter)]
if s2k_msec != False:
params += ['--s2k-msec', str(s2k_msec)]
pipe = pswd_pipe('\n'.join(passwords))
params[2:2] = ['--pass-fd', str(pipe), '--passwords', str(len(passwords))]
# Cipher or None for default
if cipher: params[2:2] = ['--cipher', cipher]
# Armor
if armor: params += ['--armor']
rnp_params_insert_aead(params, 2, aead)
rnp_params_insert_z(params, 2, z)
ret, _, err = run_proc(RNP, params)
if passwords: os.close(pipe)
if ret != 0:
raise_err('rnp encryption failed with ' + cipher, err)
def rnp_encrypt_and_sign_file(src, dst, recipients, encrpswd, signers, signpswd,
aead=None, cipher=None, z=None, armor=False):
params = ['--homedir', RNPDIR, '--sign', '--encrypt', src, '--output', dst]
pipe = pswd_pipe('\n'.join(encrpswd + signpswd))
params[2:2] = ['--pass-fd', str(pipe)]
# Encrypting passwords if any
if encrpswd:
params[2:2] = ['--passwords', str(len(encrpswd))]
# Adding recipients. If list is empty then default will be used.
for userid in reversed(recipients):
params[2:2] = ['-r', escape_regex(userid)]
# Adding signers. If list is empty then default will be used.
for signer in reversed(signers):
params[2:2] = ['-u', escape_regex(signer)]
# Cipher or None for default
if cipher: params[2:2] = ['--cipher', cipher]
# Armor
if armor: params += ['--armor']
rnp_params_insert_aead(params, 2, aead)
rnp_params_insert_z(params, 2, z)
ret, _, err = run_proc(RNP, params)
os.close(pipe)
if ret != 0:
raise_err('rnp encrypt-and-sign failed', err)
def rnp_decrypt_file(src, dst, password = PASSWORD):
pipe = pswd_pipe(password)
ret, out, err = run_proc(
RNP, ['--homedir', RNPDIR, '--pass-fd', str(pipe), '--decrypt', src, '--output', dst])
os.close(pipe)
if ret != 0:
raise_err('rnp decryption failed', out + err)
def rnp_sign_file_ex(src, dst, signers, passwords, options = None):
pipe = pswd_pipe('\n'.join(passwords))
params = ['--homedir', RNPDIR, '--pass-fd', str(pipe), src]
if dst: params += ['--output', dst]
if 'cleartext' in options:
params[4:4] = ['--clearsign']
else:
params[4:4] = ['--sign']
if 'armor' in options: params += ['--armor']
if 'detached' in options: params += ['--detach']
for signer in reversed(signers):
params[4:4] = ['--userid', escape_regex(signer)]
ret, _, err = run_proc(RNP, params)
os.close(pipe)
if ret != 0:
raise_err('rnp signing failed', err)
def rnp_sign_file(src, dst, signers, passwords, armor=False):
options = []
if armor: options += ['armor']
rnp_sign_file_ex(src, dst, signers, passwords, options)
def rnp_sign_detached(src, signers, passwords, armor=False):
options = ['detached']
if armor: options += ['armor']
rnp_sign_file_ex(src, None, signers, passwords, options)
def rnp_sign_cleartext(src, dst, signers, passwords):
rnp_sign_file_ex(src, dst, signers, passwords, ['cleartext'])
def rnp_verify_file(src, dst, signer=None):
params = ['--homedir', RNPDIR, '--verify-cat', src, '--output', dst]
ret, out, err = run_proc(RNP, params)
if ret != 0:
raise_err('rnp verification failed', err + out)
# Check RNP output
match = re.match(RE_RNP_GOOD_SIGNATURE, err)
if not match:
raise_err('wrong rnp verification output', err)
if signer and (match.group(1).strip() != signer.strip()):
raise_err('rnp verification failed, wrong signer')
def rnp_verify_detached(sig, signer=None):
ret, out, err = run_proc(RNP, ['--homedir', RNPDIR, '--verify', sig])
if ret != 0:
raise_err('rnp detached verification failed', err + out)
# Check RNP output
match = re.match(RE_RNP_GOOD_SIGNATURE, err)
if not match:
raise_err('wrong rnp detached verification output', err)
if signer and (match.group(1).strip() != signer.strip()):
raise_err('rnp detached verification failed, wrong signer'.format())
def rnp_verify_cleartext(src, signer=None):
params = ['--homedir', RNPDIR, '--verify', src]
ret, out, err = run_proc(RNP, params)
if ret != 0:
raise_err('rnp verification failed', err + out)
# Check RNP output
match = re.match(RE_RNP_GOOD_SIGNATURE, err)
if not match:
raise_err('wrong rnp verification output', err)
if signer and (match.group(1).strip() != signer.strip()):
raise_err('rnp verification failed, wrong signer')
def gpg_import_pubring(kpath=None):
if not kpath:
kpath = os.path.join(RNPDIR, PUBRING)
ret, _, err = run_proc(
GPG, ['--display-charset', CONSOLE_ENCODING, '--batch', '--homedir', GPGHOME, '--import', kpath])
if ret != 0:
raise_err(GPG_IMPORT_FAILED, err)
def gpg_import_secring(kpath=None, password = PASSWORD):
if not kpath:
kpath = os.path.join(RNPDIR, SECRING)
ret, _, err = run_proc(
GPG, ['--display-charset', CONSOLE_ENCODING, '--batch', '--passphrase', password, '--homedir', GPGHOME, '--import', kpath])
if ret != 0:
raise_err('gpg secret key import failed', err)
def gpg_export_secret_key(userid, password, keyfile):
ret, _, err = run_proc(GPG, ['--batch', '--homedir', GPGHOME, GPG_LOOPBACK,
'--yes', '--passphrase', password, '--output',
path_for_gpg(keyfile), '--export-secret-key', userid])
if ret != 0:
raise_err('gpg secret key export failed', err)
def gpg_params_insert_z(params, pos, z):
if z:
if len(z) > 0 and z[0] != None:
params[pos:pos] = ['--compress-algo', RNP_TO_GPG_ZALGS[z[0]]]
if len(z) > 1 and z[1] != None:
params[pos:pos] = ['-z', str(z[1])]
def gpg_encrypt_file(src, dst, cipher=None, z=None, armor=False):
src = path_for_gpg(src)
dst = path_for_gpg(dst)
params = ['--homedir', GPGHOME, '-e', '-r', KEY_ENCRYPT, '--batch',
'--trust-model', 'always', '--output', dst, src]
if z: gpg_params_insert_z(params, 3, z)
if cipher: params[3:3] = ['--cipher-algo', RNP_TO_GPG_CIPHERS[cipher]]
if armor: params[2:2] = ['--armor']
if GPG_NO_OLD: params[2:2] = ['--allow-old-cipher-algos']
ret, out, err = run_proc(GPG, params)
if ret != 0:
raise_err('gpg encryption failed for cipher ' + cipher, err)
def gpg_symencrypt_file(src, dst, cipher=None, z=None, armor=False, aead=None):
src = path_for_gpg(src)
dst = path_for_gpg(dst)
params = ['--homedir', GPGHOME, '-c', '--s2k-count', '65536', '--batch',
'--passphrase', PASSWORD, '--output', dst, src]
if z: gpg_params_insert_z(params, 3, z)
if cipher: params[3:3] = ['--cipher-algo', RNP_TO_GPG_CIPHERS[cipher]]
if GPG_NO_OLD: params[3:3] = ['--allow-old-cipher-algos']
if armor: params[2:2] = ['--armor']
if aead != None:
if len(aead) > 0 and aead[0] != None:
params[3:3] = ['--aead-algo', aead[0]]
if len(aead) > 1 and aead[1] != None:
params[3:3] = ['--chunk-size', str(aead[1] + 6)]
params[3:3] = ['--rfc4880bis', '--force-aead']
ret, out, err = run_proc(GPG, params)
if ret != 0:
raise_err('gpg symmetric encryption failed for cipher ' + cipher, err)
def gpg_decrypt_file(src, dst, keypass):
src = path_for_gpg(src)
dst = path_for_gpg(dst)
ret, out, err = run_proc(GPG, ['--display-charset', CONSOLE_ENCODING, '--homedir', GPGHOME, GPG_LOOPBACK, '--batch',
'--yes', '--passphrase', keypass, '--trust-model',
'always', '-o', dst, '-d', src])
if ret != 0:
raise_err('gpg decryption failed', err)
def gpg_verify_file(src, dst, signer=None):
src = path_for_gpg(src)
dst = path_for_gpg(dst)
ret, out, err = run_proc(GPG, ['--display-charset', CONSOLE_ENCODING, '--homedir', GPGHOME, '--batch',
'--yes', '--trust-model', 'always', '-o', dst, '--verify', src])
if ret != 0:
raise_err('gpg verification failed', err)
# Check GPG output
match = re.match(RE_GPG_GOOD_SIGNATURE, err)
if not match:
raise_err('wrong gpg verification output', err)
if signer and (match.group(1) != signer):
raise_err('gpg verification failed, wrong signer')
def gpg_verify_detached(src, sig, signer=None):
src = path_for_gpg(src)
sig = path_for_gpg(sig)
ret, _, err = run_proc(GPG, ['--display-charset', CONSOLE_ENCODING, '--homedir', GPGHOME, '--batch', '--yes', '--trust-model',
'always', '--verify', sig, src])
if ret != 0:
raise_err('gpg detached verification failed', err)
# Check GPG output
match = re.match(RE_GPG_GOOD_SIGNATURE, err)
if not match:
raise_err('wrong gpg detached verification output', err)
if signer and (match.group(1) != signer):
raise_err('gpg detached verification failed, wrong signer')
def gpg_verify_cleartext(src, signer=None):
src = path_for_gpg(src)
ret, _, err = run_proc(
GPG, ['--display-charset', CONSOLE_ENCODING, '--homedir', GPGHOME, '--batch', '--yes', '--trust-model', 'always', '--verify', src])
if ret != 0:
raise_err('gpg cleartext verification failed', err)
# Check GPG output
match = re.match(RE_GPG_GOOD_SIGNATURE, err)
if not match:
raise_err('wrong gpg verification output', err)
if signer and (match.group(1) != signer):
raise_err('gpg verification failed, wrong signer')
def gpg_sign_file(src, dst, signer, z=None, armor=False):
src = path_for_gpg(src)
dst = path_for_gpg(dst)
params = ['--homedir', GPGHOME, GPG_LOOPBACK, '--batch', '--yes',
'--passphrase', PASSWORD, '--trust-model', 'always', '-u', signer, '-o',
dst, '-s', src]
if z: gpg_params_insert_z(params, 3, z)
if armor: params.insert(2, '--armor')
ret, _, err = run_proc(GPG, params)
if ret != 0:
raise_err('gpg signing failed', err)
def gpg_sign_detached(src, signer, armor=False, textsig=False):
src = path_for_gpg(src)
params = ['--homedir', GPGHOME, GPG_LOOPBACK, '--batch', '--yes',
'--passphrase', PASSWORD, '--trust-model', 'always', '-u', signer,
'--detach-sign', src]
if armor: params.insert(2, '--armor')
if textsig: params.insert(2, '--text')
ret, _, err = run_proc(GPG, params)
if ret != 0:
raise_err('gpg detached signing failed', err)
def gpg_sign_cleartext(src, dst, signer):
src = path_for_gpg(src)
dst = path_for_gpg(dst)
params = ['--homedir', GPGHOME, GPG_LOOPBACK, '--batch', '--yes', '--passphrase',
PASSWORD, '--trust-model', 'always', '-u', signer, '-o', dst, '--clearsign', src]
ret, _, err = run_proc(GPG, params)
if ret != 0:
raise_err('gpg cleartext signing failed', err)
def gpg_agent_clear_cache():
run_proc(GPGCONF, ['--homedir', GPGHOME, '--kill', 'gpg-agent'])
'''
Things to try here later on:
- different symmetric algorithms
- different file sizes (block len/packet len tests)
- different public key algorithms
- different compression levels/algorithms
'''
def gpg_to_rnp_encryption(filesize, cipher=None, z=None):
'''
Encrypts with GPG and decrypts with RNP
'''
src, dst, dec = reg_workfiles('cleartext', '.txt', '.gpg', '.rnp')
# Generate random file of required size
random_text(src, filesize)
for armor in [False, True]:
# Encrypt cleartext file with GPG
gpg_encrypt_file(src, dst, cipher, z, armor)
# Decrypt encrypted file with RNP
rnp_decrypt_file(dst, dec)
compare_files(src, dec, RNP_DATA_DIFFERS)
remove_files(dst, dec)
clear_workfiles()
def file_encryption_rnp_to_gpg(filesize, z=None):
'''
Encrypts with RNP and decrypts with GPG and RNP
'''
# TODO: Would be better to do "with reg_workfiles() as src,dst,enc ... and
# do cleanup at the end"
src, dst, enc = reg_workfiles('cleartext', '.txt', '.gpg', '.rnp')
# Generate random file of required size
random_text(src, filesize)
for armor in [False, True]:
# Encrypt cleartext file with RNP
rnp_encrypt_file_ex(src, enc, [KEY_ENCRYPT], None, None, None, z, armor)
# Decrypt encrypted file with GPG
gpg_decrypt_file(enc, dst, PASSWORD)
compare_files(src, dst, GPG_DATA_DIFFERS)
remove_files(dst)
# Decrypt encrypted file with RNP
rnp_decrypt_file(enc, dst)
compare_files(src, dst, RNP_DATA_DIFFERS)
remove_files(enc, dst)
clear_workfiles()
'''
Things to try later:
- different public key algorithms
- decryption with generated by GPG and imported keys
'''
def rnp_sym_encryption_gpg_to_rnp(filesize, cipher = None, z = None):
src, dst, dec = reg_workfiles('cleartext', '.txt', '.gpg', '.rnp')
# Generate random file of required size
random_text(src, filesize)
for armor in [False, True]:
# Encrypt cleartext file with GPG
gpg_symencrypt_file(src, dst, cipher, z, armor)
# Decrypt encrypted file with RNP
rnp_decrypt_file(dst, dec)
compare_files(src, dec, RNP_DATA_DIFFERS)
remove_files(dst, dec)
clear_workfiles()
def rnp_sym_encryption_rnp_to_gpg(filesize, cipher = None, z = None, s2k_iter = False, s2k_msec = False):
src, dst, enc = reg_workfiles('cleartext', '.txt', '.gpg', '.rnp')
# Generate random file of required size
random_text(src, filesize)
for armor in [False, True]:
# Encrypt cleartext file with RNP
rnp_encrypt_file_ex(src, enc, None, [PASSWORD], None, cipher, z, armor, s2k_iter, s2k_msec)
# Decrypt encrypted file with GPG
gpg_decrypt_file(enc, dst, PASSWORD)
compare_files(src, dst, GPG_DATA_DIFFERS)
remove_files(dst)
# Decrypt encrypted file with RNP
rnp_decrypt_file(enc, dst)
compare_files(src, dst, RNP_DATA_DIFFERS)
remove_files(enc, dst)
clear_workfiles()
def rnp_sym_encryption_rnp_aead(filesize, cipher = None, z = None, aead = None, usegpg = False):
src, dst, enc = reg_workfiles('cleartext', '.txt', '.rnp', '.enc')
# Generate random file of required size
random_text(src, filesize)
# Encrypt cleartext file with RNP
rnp_encrypt_file_ex(src, enc, None, [PASSWORD], aead, cipher, z)
# Decrypt encrypted file with RNP
rnp_decrypt_file(enc, dst)
compare_files(src, dst, RNP_DATA_DIFFERS)
remove_files(dst)
if usegpg:
# Decrypt encrypted file with GPG
gpg_decrypt_file(enc, dst, PASSWORD)
compare_files(src, dst, GPG_DATA_DIFFERS)
remove_files(dst, enc)
# Encrypt cleartext file with GPG
gpg_symencrypt_file(src, enc, cipher, z, False, aead)
# Decrypt encrypted file with RNP
rnp_decrypt_file(enc, dst)
compare_files(src, dst, RNP_DATA_DIFFERS)
clear_workfiles()
def rnp_signing_rnp_to_gpg(filesize):
src, sig, ver = reg_workfiles('cleartext', '.txt', '.sig', '.ver')
# Generate random file of required size
random_text(src, filesize)
for armor in [False, True]:
# Sign file with RNP
rnp_sign_file(src, sig, [KEY_SIGN_RNP], [PASSWORD], armor)
# Verify signed file with RNP
rnp_verify_file(sig, ver, KEY_SIGN_RNP)
compare_files(src, ver, 'rnp verified data differs')
remove_files(ver)
# Verify signed message with GPG
gpg_verify_file(sig, ver, KEY_SIGN_RNP)
compare_files(src, ver, 'gpg verified data differs')
remove_files(sig, ver)
clear_workfiles()
def rnp_detached_signing_rnp_to_gpg(filesize):
src, sig, asc = reg_workfiles('cleartext', '.txt', EXT_SIG, EXT_ASC)
# Generate random file of required size
random_text(src, filesize)
for armor in [True, False]:
# Sign file with RNP
rnp_sign_detached(src, [KEY_SIGN_RNP], [PASSWORD], armor)
sigpath = asc if armor else sig
# Verify signature with RNP
rnp_verify_detached(sigpath, KEY_SIGN_RNP)
# Verify signed message with GPG
gpg_verify_detached(src, sigpath, KEY_SIGN_RNP)
remove_files(sigpath)
clear_workfiles()
def rnp_cleartext_signing_rnp_to_gpg(filesize):
src, asc = reg_workfiles('cleartext', '.txt', EXT_ASC)
# Generate random file of required size
random_text(src, filesize)
# Sign file with RNP
rnp_sign_cleartext(src, asc, [KEY_SIGN_RNP], [PASSWORD])
# Verify signature with RNP
rnp_verify_cleartext(asc, KEY_SIGN_RNP)
# Verify signed message with GPG
gpg_verify_cleartext(asc, KEY_SIGN_RNP)
clear_workfiles()
def rnp_signing_gpg_to_rnp(filesize, z=None):
src, sig, ver = reg_workfiles('cleartext', '.txt', '.sig', '.ver')
# Generate random file of required size
random_text(src, filesize)
for armor in [True, False]:
# Sign file with GPG
gpg_sign_file(src, sig, KEY_SIGN_GPG, z, armor)
# Verify file with RNP
rnp_verify_file(sig, ver, KEY_SIGN_GPG)
compare_files(src, ver, 'rnp verified data differs')
remove_files(sig, ver)
clear_workfiles()
def rnp_detached_signing_gpg_to_rnp(filesize, textsig=False):
src, sig, asc = reg_workfiles('cleartext', '.txt', EXT_SIG, EXT_ASC)
# Generate random file of required size
random_text(src, filesize)
for armor in [True, False]:
# Sign file with GPG
gpg_sign_detached(src, KEY_SIGN_GPG, armor, textsig)
sigpath = asc if armor else sig
# Verify file with RNP
rnp_verify_detached(sigpath, KEY_SIGN_GPG)
clear_workfiles()
def rnp_cleartext_signing_gpg_to_rnp(filesize):
src, asc = reg_workfiles('cleartext', '.txt', EXT_ASC)
# Generate random file of required size
random_text(src, filesize)
# Sign file with GPG
gpg_sign_cleartext(src, asc, KEY_SIGN_GPG)
# Verify signature with RNP
rnp_verify_cleartext(asc, KEY_SIGN_GPG)
# Verify signed message with GPG
gpg_verify_cleartext(asc, KEY_SIGN_GPG)
clear_workfiles()
def gpg_check_features():
global GPG_AEAD, GPG_AEAD_EAX, GPG_AEAD_OCB, GPG_NO_OLD, GPG_BRAINPOOL
_, out, _ = run_proc(GPG, ["--version"])
# AEAD
GPG_AEAD_EAX = re.match(r'(?s)^.*AEAD:.*EAX.*', out) is not None
GPG_AEAD_OCB = re.match(r'(?s)^.*AEAD:.*OCB.*', out) is not None
# Version 2.3.0-beta1598 and up drops support of 64-bit block algos
match = re.match(r'(?s)^.*gpg \(GnuPG\) (\d+)\.(\d+)\.(\d+)(-beta(\d+))?.*$', out)
if not match:
raise_err('Failed to parse GnuPG version.')
ver = [int(match.group(1)), int(match.group(2)), int(match.group(3))]
beta = int(match.group(5)) if match.group(5) else 0
if not beta:
GPG_NO_OLD = ver >= [2, 3, 0]
else:
GPG_NO_OLD = ver == [2, 3, 0] and (beta >= 1598)
# Version 2.4.0 and up doesn't support EAX and doesn't has AEAD in output
if ver >= [2, 4, 0]:
GPG_AEAD_OCB = True
GPG_AEAD_EAX = False
GPG_AEAD = GPG_AEAD_OCB or GPG_AEAD_EAX
# Check whether Brainpool curves are supported
_, out, _ = run_proc(GPG, ["--with-colons", "--list-config", "curve"])
GPG_BRAINPOOL = re.match(r'(?s)^.*brainpoolP256r1.*', out) is not None
print('GPG_AEAD_EAX: ' + str(GPG_AEAD_EAX))
print('GPG_AEAD_OCB: ' + str(GPG_AEAD_OCB))
print('GPG_NO_OLD: ' + str(GPG_NO_OLD))
print('GPG_BRAINPOOL: ' + str(GPG_BRAINPOOL))
def rnp_check_features():
global RNP_TWOFISH, RNP_BRAINPOOL, RNP_AEAD, RNP_AEAD_EAX, RNP_AEAD_OCB, RNP_AEAD_OCB_AES, RNP_IDEA, RNP_BLOWFISH, RNP_CAST5, RNP_RIPEMD160
global RNP_BOTAN_OCB_AV
ret, out, _ = run_proc(RNP, ['--version'])
if ret != 0:
raise_err('Failed to get RNP version.')
# AEAD
RNP_AEAD_EAX = re.match(r'(?s)^.*AEAD:.*EAX.*', out) is not None
RNP_AEAD_OCB = re.match(r'(?s)^.*AEAD:.*OCB.*', out) is not None
RNP_AEAD = RNP_AEAD_EAX or RNP_AEAD_OCB
RNP_AEAD_OCB_AES = RNP_AEAD_OCB and re.match(r'(?s)^.*Backend.*OpenSSL.*', out) is not None
# Botan OCB crash
if re.match(r'(?s)^.*Backend.*Botan.*', out):
match = re.match(r'(?s)^.*Backend version: ([\d]+)\.([\d]+)\.([\d]+).*$', out)
ver = [int(match.group(1)), int(match.group(2)), int(match.group(3))]
if ver <= [2, 19, 3]:
RNP_BOTAN_OCB_AV = True
if (ver >= [3, 0, 0]) and (ver <= [3, 2, 0]):
RNP_BOTAN_OCB_AV = True
# Twofish
RNP_TWOFISH = re.match(r'(?s)^.*Encryption:.*TWOFISH.*', out) is not None
# Brainpool curves
RNP_BRAINPOOL = re.match(r'(?s)^.*Curves:.*brainpoolP256r1.*brainpoolP384r1.*brainpoolP512r1.*', out) is not None
# IDEA encryption algorithm
RNP_IDEA = re.match(r'(?s)^.*Encryption:.*IDEA.*', out) is not None
RNP_BLOWFISH = re.match(r'(?s)^.*Encryption:.*BLOWFISH.*', out) is not None
RNP_CAST5 = re.match(r'(?s)^.*Encryption:.*CAST5.*', out) is not None
RNP_RIPEMD160 = re.match(r'(?s)^.*Hash:.*RIPEMD160.*', out) is not None
print('RNP_TWOFISH: ' + str(RNP_TWOFISH))
print('RNP_BLOWFISH: ' + str(RNP_BLOWFISH))
print('RNP_IDEA: ' + str(RNP_IDEA))
print('RNP_CAST5: ' + str(RNP_CAST5))
print('RNP_RIPEMD160: ' + str(RNP_RIPEMD160))
print('RNP_BRAINPOOL: ' + str(RNP_BRAINPOOL))
print('RNP_AEAD_EAX: ' + str(RNP_AEAD_EAX))
print('RNP_AEAD_OCB: ' + str(RNP_AEAD_OCB))
print('RNP_AEAD_OCB_AES: ' + str(RNP_AEAD_OCB_AES))
print('RNP_BOTAN_OCB_AV: ' + str(RNP_BOTAN_OCB_AV))
def setup(loglvl):
# Setting up directories.
global RMWORKDIR, WORKDIR, RNPDIR, RNP, RNPK, GPG, GPGDIR, GPGHOME, GPGCONF
logging.basicConfig(stream=sys.stderr, format="%(message)s")
logging.getLogger().setLevel(loglvl)
WORKDIR = tempfile.mkdtemp(prefix='rnpctmp')
set_workdir(WORKDIR)
RMWORKDIR = True
logging.info('Running in ' + WORKDIR)
RNPDIR = os.path.join(WORKDIR, '.rnp')
RNP = os.getenv('RNP_TESTS_RNP_PATH') or 'rnp'
RNPK = os.getenv('RNP_TESTS_RNPKEYS_PATH') or 'rnpkeys'
shutil.rmtree(RNPDIR, ignore_errors=True)
os.mkdir(RNPDIR, 0o700)
os.environ["RNP_LOG_CONSOLE"] = "1"
GPGDIR = os.path.join(WORKDIR, '.gpg')
GPGHOME = path_for_gpg(GPGDIR) if is_windows() else GPGDIR
GPG = os.getenv('RNP_TESTS_GPG_PATH') or find_utility('gpg')
GPGCONF = os.getenv('RNP_TESTS_GPGCONF_PATH') or find_utility('gpgconf')
gpg_check_features()
rnp_check_features()
shutil.rmtree(GPGDIR, ignore_errors=True)
os.mkdir(GPGDIR, 0o700)
def data_path(subpath):
''' Constructs path to the tests data file/dir'''
return os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data', subpath)
def key_path(file_base_name, secret):
''' Constructs path to the .gpg file'''
path=os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data/cli_EncryptSign',
file_base_name)
return ''.join([path, '-sec' if secret else '', '.gpg'])
def rnp_supported_ciphers(aead = False):
ciphers = ['AES', 'AES192', 'AES256']
if aead and RNP_AEAD_OCB_AES:
return ciphers
ciphers += ['CAMELLIA128', 'CAMELLIA192', 'CAMELLIA256']
if RNP_TWOFISH:
ciphers += ['TWOFISH']
# AEAD supports only 128-bit block ciphers
if aead:
return ciphers
ciphers += ['3DES']
if RNP_IDEA:
ciphers += ['IDEA']
if RNP_BLOWFISH:
ciphers += ['BLOWFISH']
if RNP_CAST5:
ciphers += ['CAST5']
return ciphers
class TestIdMixin(object):
@property
def test_id(self):
return "".join(self.id().split('.')[1:3])
class KeyLocationChooserMixin(object):
def __init__(self):
# If set it will try to import a key from provided location
# otherwise it will try to generate a key
self.__op_key_location = None
self.__op_key_gen_cmd = None
@property
def operation_key_location(self):
return self.__op_key_location
@operation_key_location.setter
def operation_key_location(self, key):
if (type(key) is not tuple): raise RuntimeError("Key must be tuple(pub,sec)")
self.__op_key_location = key
self.__op_key_gen_cmd = None
@property
def operation_key_gencmd(self):
return self.__op_key_gen_cmd
@operation_key_gencmd.setter
def operation_key_gencmd(self, cmd):
self.__op_key_gen_cmd = cmd
self.__op_key_location = None
'''
Things to try here later on:
- different public key algorithms
- different key protection levels/algorithms
- armored import/export
'''
class Keystore(unittest.TestCase):