-
Notifications
You must be signed in to change notification settings - Fork 143
/
test_public_key.py
2054 lines (1600 loc) · 85.5 KB
/
test_public_key.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
# Copyright (c) 2014-2018 by Ron Frederick <ronf@timeheart.net> and others.
#
# This program and the accompanying materials are made available under
# the terms of the Eclipse Public License v2.0 which accompanies this
# distribution and is available at:
#
# http://www.eclipse.org/legal/epl-2.0/
#
# This program may also be made available under the following secondary
# licenses when the conditions for such availability set forth in the
# Eclipse Public License v2.0 are satisfied:
#
# GNU General Public License, Version 2.0, or any later versions of
# that license
#
# SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later
#
# Contributors:
# Ron Frederick - initial implementation, API, and documentation
"""Unit tests for reading and writing public and private keys
Note: These tests look for the openssl and ssh-keygen commands in
the user's path and will whenever possible use them to perform
interoperability tests. Otherwise, these tests will only test
AsyncSSH against itself.
"""
import binascii
from datetime import datetime
import os
from pathlib import Path
import shutil
import subprocess
import sys
import unittest
import asyncssh
from asyncssh.asn1 import der_encode, BitString, ObjectIdentifier
from asyncssh.asn1 import TaggedDERObject
from asyncssh.packet import MPInt, String, UInt32
from asyncssh.pbe import pkcs1_decrypt
from asyncssh.public_key import CERT_TYPE_USER, CERT_TYPE_HOST, SSHKey
from asyncssh.public_key import SSHX509CertificateChain
from asyncssh.public_key import decode_ssh_certificate
from asyncssh.public_key import get_public_key_algs, get_certificate_algs
from asyncssh.public_key import get_x509_certificate_algs
from asyncssh.public_key import import_certificate_subject
from .util import bcrypt_available, libnacl_available, x509_available
from .util import make_certificate, run, TempDirTestCase
_ES1_SHA1_DES = ObjectIdentifier('1.2.840.113549.1.5.10')
_P12_RC4_40 = ObjectIdentifier('1.2.840.113549.1.12.1.2')
_ES2 = ObjectIdentifier('1.2.840.113549.1.5.13')
_ES2_PBKDF2 = ObjectIdentifier('1.2.840.113549.1.5.12')
_ES2_AES128 = ObjectIdentifier('2.16.840.1.101.3.4.1.2')
_ES2_DES3 = ObjectIdentifier('1.2.840.113549.3.7')
try:
_openssl_version = run('openssl version')
except subprocess.CalledProcessError: # pragma: no cover
_openssl_version = b''
_openssl_available = _openssl_version != b''
# The openssl "-v2prf" option is only available in OpenSSL 1.0.2 or later
_openssl_supports_v2prf = _openssl_version >= b'OpenSSL 1.0.2'
try:
if sys.platform != 'win32':
_openssh_version = run('ssh -V')
else: # pragma: no cover
_openssh_version = b''
except subprocess.CalledProcessError: # pragma: no cover
_openssh_version = b''
_openssh_available = _openssh_version != b''
# GCM & Chacha tests require OpenSSH 6.9 due to a bug in earlier versions:
# https://bugzilla.mindrot.org/show_bug.cgi?id=2366
_openssh_supports_gcm_chacha = _openssh_version >= b'OpenSSH_6.9'
_openssh_supports_arcfour_blowfish_cast = (_openssh_available and
_openssh_version < b'OpenSSH_7.6')
# pylint: disable=bad-whitespace
pkcs1_ciphers = (('aes128-cbc', '-aes128'),
('aes192-cbc', '-aes192'),
('aes256-cbc', '-aes256'),
('des-cbc', '-des'),
('des3-cbc', '-des3'))
pkcs8_ciphers = (
('aes128-cbc', 'sha224', 2, '-v2 aes-128-cbc '
'-v2prf hmacWithSHA224', _openssl_supports_v2prf),
('aes128-cbc', 'sha256', 2, '-v2 aes-128-cbc '
'-v2prf hmacWithSHA256', _openssl_supports_v2prf),
('aes128-cbc', 'sha384', 2, '-v2 aes-128-cbc '
'-v2prf hmacWithSHA384', _openssl_supports_v2prf),
('aes128-cbc', 'sha512', 2, '-v2 aes-128-cbc '
'-v2prf hmacWithSHA512', _openssl_supports_v2prf),
('des-cbc', 'md5', 1, '-v1 PBE-MD5-DES', _openssl_available),
('des-cbc', 'sha1', 1, '-v1 PBE-SHA1-DES', _openssl_available),
('des2-cbc', 'sha1', 1, '-v1 PBE-SHA1-2DES', _openssl_available),
('des3-cbc', 'sha1', 1, '-v1 PBE-SHA1-3DES', _openssl_available),
('rc4-40', 'sha1', 1, '-v1 PBE-SHA1-RC4-40', _openssl_available),
('rc4-128', 'sha1', 1, '-v1 PBE-SHA1-RC4-128', _openssl_available),
('aes128-cbc', 'sha1', 2, '-v2 aes-128-cbc', _openssl_available),
('aes192-cbc', 'sha1', 2, '-v2 aes-192-cbc', _openssl_available),
('aes256-cbc', 'sha1', 2, '-v2 aes-256-cbc', _openssl_available),
('blowfish-cbc', 'sha1', 2, '-v2 bf-cbc', _openssl_available),
('cast128-cbc', 'sha1', 2, '-v2 cast-cbc', _openssl_available),
('des-cbc', 'sha1', 2, '-v2 des-cbc', _openssl_available),
('des3-cbc', 'sha1', 2, '-v2 des-ede3-cbc', _openssl_available))
openssh_ciphers = (
('aes128-gcm@openssh.com', _openssh_supports_gcm_chacha),
('aes256-gcm@openssh.com', _openssh_supports_gcm_chacha),
('arcfour', _openssh_supports_arcfour_blowfish_cast),
('arcfour128', _openssh_supports_arcfour_blowfish_cast),
('arcfour256', _openssh_supports_arcfour_blowfish_cast),
('blowfish-cbc', _openssh_supports_arcfour_blowfish_cast),
('cast128-cbc', _openssh_supports_arcfour_blowfish_cast),
('aes128-cbc', _openssh_available),
('aes192-cbc', _openssh_available),
('aes256-cbc', _openssh_available),
('aes128-ctr', _openssh_available),
('aes192-ctr', _openssh_available),
('aes256-ctr', _openssh_available),
('3des-cbc', _openssh_available)
)
# pylint: enable=bad-whitespace
# Only test Chacha if libnacl is installed
if libnacl_available: # pragma: no branch
openssh_ciphers += (('chacha20-poly1305@openssh.com',
_openssh_supports_gcm_chacha),)
def select_passphrase(cipher, pbe_version=0):
"""Randomize between string and bytes version of passphrase"""
if cipher is None:
return None
elif os.urandom(1)[0] & 1:
return 'passphrase'
elif pbe_version == 1 and cipher in ('des2-cbc', 'des3-cbc',
'rc4-40', 'rc4-128'):
return 'passphrase'.encode('utf-16-be')
else:
return 'passphrase'.encode('utf-8')
class _TestPublicKey(TempDirTestCase):
"""Unit tests for public key modules"""
# pylint: disable=too-many-public-methods
keyclass = None
base_format = None
private_formats = ()
public_formats = ()
default_cert_version = ''
x509_supported = False
generate_args = ()
def __init__(self, methodName='runTest'):
super().__init__(methodName)
self.privkey = None
self.pubkey = None
self.privca = None
self.pubca = None
self.usercert = None
self.hostcert = None
self.rootx509 = None
self.userx509 = None
self.hostx509 = None
self.otherx509 = None
def make_certificate(self, *args, **kwargs):
"""Construct an SSH certificate"""
return make_certificate(self.default_cert_version, *args, **kwargs)
def validate_openssh(self, cert, cert_type, name):
"""Check OpenSSH certificate validation"""
self.assertIsNone(cert.validate(cert_type, name))
def validate_x509(self, cert, user_principal=None):
"""Check X.509 certificate validation"""
self.assertIsNone(cert.validate_chain([], [self.rootx509], [], 'any',
user_principal, None))
with self.assertRaises(ValueError):
cert.validate_chain([self.rootx509], [], [], 'any', None, None)
chain = SSHX509CertificateChain.construct_from_certs([cert])
self.assertEqual(chain, decode_ssh_certificate(chain.public_data))
self.assertIsNone(chain.validate_chain([self.rootx509], [], [], 'any',
user_principal, None))
self.assertIsNone(chain.validate_chain([self.rootx509],
[], [self.otherx509], 'any',
user_principal, None))
with self.assertRaises(ValueError):
chain.validate_chain([], [], [], 'any', user_principal, None)
with self.assertRaises(ValueError):
chain.validate_chain([self.rootx509], [], [cert], 'any',
user_principal, None)
def check_private(self, format_name, passphrase=None):
"""Check for a private key match"""
newkey = asyncssh.read_private_key('new', passphrase)
algorithm = newkey.get_algorithm()
keydata = newkey.export_private_key()
pubdata = newkey.public_data
self.assertEqual(newkey, self.privkey)
self.assertEqual(hash(newkey), hash(self.privkey))
keypair = asyncssh.load_keypairs(newkey, passphrase)[0]
self.assertEqual(keypair.get_key_type(), 'local')
self.assertEqual(keypair.get_algorithm(), algorithm)
self.assertEqual(keypair.public_data, pubdata)
self.assertIsNotNone(keypair.get_agent_private_key())
keypair = asyncssh.load_keypairs([keypair])[0]
self.assertEqual(keypair.public_data, pubdata)
keypair = asyncssh.load_keypairs(keydata)[0]
self.assertEqual(keypair.public_data, pubdata)
keypair = asyncssh.load_keypairs('new', passphrase)[0]
self.assertEqual(keypair.public_data, pubdata)
keypair = asyncssh.load_keypairs([newkey])[0]
self.assertEqual(keypair.public_data, pubdata)
keypair = asyncssh.load_keypairs([(newkey, None)])[0]
self.assertEqual(keypair.public_data, pubdata)
keypair = asyncssh.load_keypairs([keydata])[0]
self.assertEqual(keypair.public_data, pubdata)
keypair = asyncssh.load_keypairs([(keydata, None)])[0]
self.assertEqual(keypair.public_data, pubdata)
keypair = asyncssh.load_keypairs(['new'], passphrase)[0]
self.assertEqual(keypair.public_data, pubdata)
keypair = asyncssh.load_keypairs([('new', None)], passphrase)[0]
self.assertEqual(keypair.public_data, pubdata)
keypair = asyncssh.load_keypairs(Path('new'), passphrase)[0]
self.assertEqual(keypair.public_data, pubdata)
keypair = asyncssh.load_keypairs([Path('new')], passphrase)[0]
self.assertEqual(keypair.public_data, pubdata)
keypair = asyncssh.load_keypairs([(Path('new'), None)], passphrase)[0]
self.assertEqual(keypair.public_data, pubdata)
keylist = asyncssh.load_keypairs([])
self.assertEqual(keylist, [])
if passphrase:
with self.assertRaises((asyncssh.KeyEncryptionError,
asyncssh.KeyImportError)):
asyncssh.load_keypairs('new', 'xxx')
else:
newkey.write_private_key('list', format_name)
newkey.append_private_key('list', format_name)
keylist = asyncssh.load_keypairs('list')
self.assertEqual(keylist[0].public_data, pubdata)
self.assertEqual(keylist[1].public_data, pubdata)
newkey.write_private_key(Path('list'), format_name)
newkey.append_private_key(Path('list'), format_name)
keylist = asyncssh.load_keypairs(Path('list'))
self.assertEqual(keylist[0].public_data, pubdata)
self.assertEqual(keylist[1].public_data, pubdata)
if self.x509_supported and format_name[-4:] == '-pem':
cert = newkey.generate_x509_user_certificate(newkey, 'OU=user')
chain = SSHX509CertificateChain.construct_from_certs([cert])
cert.write_certificate('new_cert')
keypair = asyncssh.load_keypairs(('new', 'new_cert'), passphrase)[0]
self.assertEqual(keypair.public_data, chain.public_data)
self.assertIsNotNone(keypair.get_agent_private_key())
newkey.write_private_key('new_bundle', format_name, passphrase)
cert.append_certificate('new_bundle', 'pem')
keypair = asyncssh.load_keypairs('new_bundle', passphrase)[0]
self.assertEqual(keypair.public_data, chain.public_data)
with self.assertRaises(OSError):
asyncssh.load_keypairs(('new', 'not_found'), passphrase)
def check_public(self, format_name):
"""Check for a public key match"""
newkey = asyncssh.read_public_key('new')
pubdata = newkey.export_public_key()
self.assertEqual(newkey, self.pubkey)
self.assertEqual(hash(newkey), hash(self.pubkey))
keypair = asyncssh.load_public_keys('new')[0]
self.assertEqual(keypair, newkey)
keypair = asyncssh.load_public_keys([newkey])[0]
self.assertEqual(keypair, newkey)
keypair = asyncssh.load_public_keys([pubdata])[0]
self.assertEqual(keypair, newkey)
keypair = asyncssh.load_public_keys(['new'])[0]
self.assertEqual(keypair, newkey)
keypair = asyncssh.load_public_keys(Path('new'))[0]
self.assertEqual(keypair, newkey)
keypair = asyncssh.load_public_keys([Path('new')])[0]
self.assertEqual(keypair, newkey)
newkey.write_public_key('list', format_name)
newkey.append_public_key('list', format_name)
keylist = asyncssh.load_public_keys('list')
self.assertEqual(keylist[0], newkey)
self.assertEqual(keylist[1], newkey)
newkey.write_public_key(Path('list'), format_name)
newkey.append_public_key(Path('list'), format_name)
keylist = asyncssh.load_public_keys(Path('list'))
self.assertEqual(keylist[0], newkey)
self.assertEqual(keylist[1], newkey)
def check_certificate(self, cert_type, format_name):
"""Check for a certificate match"""
cert = asyncssh.read_certificate('cert')
certdata = cert.export_certificate()
self.assertEqual(cert.key, self.pubkey)
if cert.is_x509:
self.validate_x509(cert)
else:
self.validate_openssh(cert, cert_type, 'name')
certlist = asyncssh.load_certificates(cert)
self.assertEqual(certlist[0], cert)
self.assertEqual(hash(certlist[0]), hash(cert))
if cert.is_x509:
self.assertEqual(certlist[0].x509_cert, cert.x509_cert)
self.assertEqual(hash(certlist[0].x509_cert), hash(cert.x509_cert))
certlist = asyncssh.load_certificates(certdata)
self.assertEqual(certlist[0], cert)
certlist = asyncssh.load_certificates([cert])
self.assertEqual(certlist[0], cert)
certlist = asyncssh.load_certificates([certdata])
self.assertEqual(certlist[0], cert)
certlist = asyncssh.load_certificates('cert')
self.assertEqual(certlist[0], cert)
certlist = asyncssh.load_certificates(Path('cert'))
self.assertEqual(certlist[0], cert)
certlist = asyncssh.load_certificates([Path('cert')])
self.assertEqual(certlist[0], cert)
cert.write_certificate('list', format_name)
cert.append_certificate('list', format_name)
certlist = asyncssh.load_certificates('list')
self.assertEqual(certlist[0], cert)
self.assertEqual(certlist[1], cert)
cert.write_certificate(Path('list'), format_name)
cert.append_certificate(Path('list'), format_name)
certlist = asyncssh.load_certificates(Path('list'))
self.assertEqual(certlist[0], cert)
self.assertEqual(certlist[1], cert)
certlist = asyncssh.load_certificates(['list', [cert]])
self.assertEqual(certlist[0], cert)
self.assertEqual(certlist[1], cert)
self.assertEqual(certlist[2], cert)
certlist = asyncssh.load_certificates(['list', certdata])
self.assertEqual(certlist[0], cert)
self.assertEqual(certlist[1], cert)
self.assertEqual(certlist[2], cert)
def import_pkcs1_private(self, fmt, cipher=None, args=None):
"""Check import of a PKCS#1 private key"""
format_name = 'pkcs1-%s' % fmt
if _openssl_available: # pragma: no branch
if cipher:
run('openssl %s %s -in priv -inform pem -out new -outform %s '
'-passout pass:passphrase' % (self.keyclass, args, fmt))
else:
run('openssl %s -in priv -inform pem -out new -outform %s' %
(self.keyclass, fmt))
else: # pragma: no cover
self.privkey.write_private_key('new', format_name,
select_passphrase(cipher), cipher)
self.check_private(format_name, select_passphrase(cipher))
def export_pkcs1_private(self, fmt, cipher=None):
"""Check export of a PKCS#1 private key"""
format_name = 'pkcs1-%s' % fmt
self.privkey.write_private_key('privout', format_name,
select_passphrase(cipher), cipher)
if _openssl_available: # pragma: no branch
if cipher:
run('openssl %s -in privout -inform %s -out new -outform pem '
'-passin pass:passphrase' % (self.keyclass, fmt))
else:
run('openssl %s -in privout -inform %s -out new -outform pem' %
(self.keyclass, fmt))
else: # pragma: no cover
priv = asyncssh.read_private_key('privout',
select_passphrase(cipher))
priv.write_private_key('new', format_name)
self.check_private(format_name)
def import_pkcs1_public(self, fmt):
"""Check import of a PKCS#1 public key"""
format_name = 'pkcs1-%s' % fmt
if (not _openssl_available or self.keyclass == 'dsa' or
_openssl_version < b'OpenSSL 1.0.0'): # pragma: no cover
# OpenSSL no longer has support for PKCS#1 DSA, and PKCS#1
# RSA is not supported before OpenSSL 1.0.0, so we only test
# against ourselves in these cases.
self.pubkey.write_public_key('new', format_name)
else:
run('openssl %s -pubin -in pub -inform pem -RSAPublicKey_out '
'-out new -outform %s' % (self.keyclass, fmt))
self.check_public(format_name)
def export_pkcs1_public(self, fmt):
"""Check export of a PKCS#1 public key"""
format_name = 'pkcs1-%s' % fmt
self.privkey.write_public_key('pubout', format_name)
if not _openssl_available or self.keyclass == 'dsa': # pragma: no cover
# OpenSSL no longer has support for PKCS#1 DSA, so we can
# only test against ourselves.
pub = asyncssh.read_public_key('pubout')
pub.write_public_key('new', 'pkcs1-%s' % fmt)
else:
run('openssl %s -RSAPublicKey_in -in pubout -inform %s -out new '
'-outform pem' % (self.keyclass, fmt))
self.check_public(format_name)
def import_pkcs8_private(self, fmt, use_openssl, cipher=None,
hash_alg=None, pbe_version=None, args=None):
"""Check import of a PKCS#8 private key"""
format_name = 'pkcs8-%s' % fmt
if use_openssl: # pragma: no branch
if cipher:
run('openssl pkcs8 -topk8 %s -in priv -inform pem -out new '
'-outform %s -passout pass:passphrase' % (args, fmt))
else:
run('openssl pkcs8 -topk8 -nocrypt -in priv -inform pem '
'-out new -outform %s' % fmt)
else: # pragma: no cover
self.privkey.write_private_key('new', format_name,
select_passphrase(cipher,
pbe_version),
cipher, hash_alg, pbe_version)
self.check_private(format_name, select_passphrase(cipher, pbe_version))
def export_pkcs8_private(self, fmt, use_openssl, cipher=None,
hash_alg=None, pbe_version=None):
"""Check export of a PKCS#8 private key"""
format_name = 'pkcs8-%s' % fmt
self.privkey.write_private_key('privout', format_name,
select_passphrase(cipher, pbe_version),
cipher, hash_alg, pbe_version)
if use_openssl: # pragma: no branch
if cipher:
run('openssl pkcs8 -in privout -inform %s -out new '
'-outform pem -passin pass:passphrase' % fmt)
else:
run('openssl pkcs8 -nocrypt -in privout -inform %s -out new '
'-outform pem' % fmt)
else: # pragma: no cover
priv = asyncssh.read_private_key('privout',
select_passphrase(cipher,
pbe_version))
priv.write_private_key('new', format_name)
self.check_private(format_name)
def import_pkcs8_public(self, fmt):
"""Check import of a PKCS#8 public key"""
format_name = 'pkcs8-%s' % fmt
if _openssl_available: # pragma: no branch
run('openssl %s -pubin -in pub -inform pem -out new -outform %s' %
(self.keyclass, fmt))
else: # pragma: no cover
self.pubkey.write_public_key('new', format_name)
self.check_public(format_name)
def export_pkcs8_public(self, fmt):
"""Check export of a PKCS#8 public key"""
format_name = 'pkcs8-%s' % fmt
self.privkey.write_public_key('pubout', format_name)
if _openssl_available: # pragma: no branch
run('openssl %s -pubin -in pubout -inform %s -out new '
'-outform pem' % (self.keyclass, fmt))
else: # pragma: no cover
pub = asyncssh.read_public_key('pubout')
pub.write_public_key('new', format_name)
self.check_public(format_name)
def import_openssh_private(self, use_openssh, cipher=None):
"""Check import of an OpenSSH private key"""
if use_openssh: # pragma: no branch
shutil.copy('priv', 'new')
if cipher:
run('ssh-keygen -p -a 1 -N passphrase -Z %s -o -f new' %
cipher)
else:
run('ssh-keygen -p -N "" -o -f new')
else: # pragma: no cover
self.privkey.write_private_key('new', 'openssh',
select_passphrase(cipher), cipher,
rounds=1, ignore_few_rounds=True)
self.check_private('openssh', select_passphrase(cipher))
def export_openssh_private(self, use_openssh, cipher=None):
"""Check export of an OpenSSH private key"""
self.privkey.write_private_key('new', 'openssh',
select_passphrase(cipher), cipher,
rounds=1, ignore_few_rounds=True)
if use_openssh: # pragma: no branch
os.chmod('new', 0o600)
if cipher:
run('ssh-keygen -p -P passphrase -N "" -o -f new')
else:
run('ssh-keygen -p -N "" -o -f new')
else: # pragma: no cover
priv = asyncssh.read_private_key('new', select_passphrase(cipher))
priv.write_private_key('new', 'openssh')
self.check_private('openssh')
def import_openssh_public(self):
"""Check import of an OpenSSH public key"""
shutil.copy('sshpub', 'new')
self.check_public('openssh')
def export_openssh_public(self):
"""Check export of an OpenSSH public key"""
self.privkey.write_public_key('pubout', 'openssh')
if _openssh_available: # pragma: no branch
run('ssh-keygen -e -f pubout -m rfc4716 > new')
else: # pragma: no cover
pub = asyncssh.read_public_key('pubout')
pub.write_public_key('new', 'rfc4716')
self.check_public('openssh')
def import_openssh_certificate(self, cert_type, cert):
"""Check import of an OpenSSH certificate"""
shutil.copy(cert, 'cert')
self.check_certificate(cert_type, 'openssh')
def export_openssh_certificate(self, cert_type, cert):
"""Check export of an OpenSSH certificate"""
cert.write_certificate('certout', 'openssh')
if _openssh_available: # pragma: no branch
run('ssh-keygen -e -f certout -m rfc4716 > cert')
else: # pragma: no cover
cert = asyncssh.read_certificate('certout')
cert.write_certificate('cert', 'rfc4716')
self.check_certificate(cert_type, 'openssh')
def import_rfc4716_public(self):
"""Check import of an RFC4716 public key"""
if _openssh_available: # pragma: no branch
run('ssh-keygen -e -f sshpub -m rfc4716 > new')
else: # pragma: no cover
self.pubkey.write_public_key('new', 'rfc4716')
self.check_public('rfc4716')
def export_rfc4716_public(self):
"""Check export of an RFC4716 public key"""
self.pubkey.write_public_key('pubout', 'rfc4716')
if _openssh_available: # pragma: no branch
run('ssh-keygen -i -f pubout -m rfc4716 > new')
else: # pragma: no cover
pub = asyncssh.read_public_key('pubout')
pub.write_public_key('new', 'openssh')
self.check_public('rfc4716')
def import_rfc4716_certificate(self, cert_type, cert):
"""Check import of an RFC4716 certificate"""
if _openssh_available: # pragma: no branch
run('ssh-keygen -e -f %s -m rfc4716 > cert' % cert)
else: # pragma: no cover
if cert_type == CERT_TYPE_USER:
cert = self.usercert
else:
cert = self.hostcert
cert.write_certificate('cert', 'rfc4716')
self.check_certificate(cert_type, 'rfc4716')
def export_rfc4716_certificate(self, cert_type, cert):
"""Check export of an RFC4716 certificate"""
cert.write_certificate('certout', 'rfc4716')
if _openssh_available: # pragma: no branch
run('ssh-keygen -i -f certout -m rfc4716 > cert')
else: # pragma: no cover
cert = asyncssh.read_certificate('certout')
cert.write_certificate('cert', 'openssh')
self.check_certificate(cert_type, 'rfc4716')
def import_der_x509_certificate(self, cert_type, cert):
"""Check import of a DER X.509 certificate"""
if cert_type == CERT_TYPE_USER:
cert = self.userx509
else:
cert = self.hostx509
cert.write_certificate('cert', 'der')
self.check_certificate(cert_type, 'der')
def export_der_x509_certificate(self, cert_type, cert):
"""Check export of a DER X.509 certificate"""
cert.write_certificate('certout', 'der')
cert = asyncssh.read_certificate('certout')
cert.write_certificate('cert', 'openssh')
self.check_certificate(cert_type, 'der')
def import_pem_x509_certificate(self, cert_type, cert):
"""Check import of a PEM X.509 certificate"""
if cert_type == CERT_TYPE_USER:
cert = self.userx509
else:
cert = self.hostx509
cert.write_certificate('cert', 'pem')
self.check_certificate(cert_type, 'pem')
def export_pem_x509_certificate(self, cert_type, cert):
"""Check export of a PEM X.509 certificate"""
cert.write_certificate('certout', 'pem')
cert = asyncssh.read_certificate('certout')
cert.write_certificate('cert', 'openssh')
self.check_certificate(cert_type, 'pem')
def import_openssh_x509_certificate(self, cert_type, cert):
"""Check import of an OpenSSH X.509 certificate"""
if cert_type == CERT_TYPE_USER:
cert = self.userx509
else:
cert = self.hostx509
cert.write_certificate('cert')
self.check_certificate(cert_type, 'openssh')
def export_openssh_x509_certificate(self, cert_type, cert):
"""Check export of an OpenSSH X.509 certificate"""
cert.write_certificate('certout')
cert = asyncssh.read_certificate('certout')
cert.write_certificate('cert', 'pem')
self.check_certificate(cert_type, 'openssh')
def check_encode_errors(self):
"""Check error code paths in key encoding"""
for fmt in ('pkcs1-der', 'pkcs1-pem', 'pkcs8-der', 'pkcs8-pem',
'openssh', 'rfc4716', 'xxx'):
with self.subTest('Encode private from public (%s)' % fmt):
with self.assertRaises(asyncssh.KeyExportError):
self.pubkey.export_private_key(fmt)
with self.subTest('Encode with unknown key format'):
with self.assertRaises(asyncssh.KeyExportError):
self.privkey.export_public_key('xxx')
with self.subTest('Encode encrypted pkcs1-der'):
with self.assertRaises(asyncssh.KeyExportError):
self.privkey.export_private_key('pkcs1-der', 'x')
if self.keyclass == 'ec':
with self.subTest('Encode EC public key with PKCS#1'):
with self.assertRaises(asyncssh.KeyExportError):
self.privkey.export_public_key('pkcs1-pem')
if 'pkcs1' in self.private_formats:
with self.subTest('Encode with unknown PKCS#1 cipher'):
with self.assertRaises(asyncssh.KeyEncryptionError):
self.privkey.export_private_key('pkcs1-pem', 'x', 'xxx')
if 'pkcs8' in self.private_formats:
with self.subTest('Encode with unknown PKCS#8 cipher'):
with self.assertRaises(asyncssh.KeyEncryptionError):
self.privkey.export_private_key('pkcs8-pem', 'x', 'xxx')
with self.subTest('Encode with unknown PKCS#8 hash'):
with self.assertRaises(asyncssh.KeyEncryptionError):
self.privkey.export_private_key('pkcs8-pem', 'x',
'aes128-cbc', 'xxx')
with self.subTest('Encode with unknown PKCS#8 version'):
with self.assertRaises(asyncssh.KeyEncryptionError):
self.privkey.export_private_key('pkcs8-pem', 'x',
'aes128-cbc', 'sha1', 3)
if bcrypt_available: # pragma: no branch
with self.subTest('Encode with unknown openssh cipher'):
with self.assertRaises(asyncssh.KeyEncryptionError):
self.privkey.export_private_key('openssh', 'x', 'xxx')
with self.subTest('Encode agent cert private from public'):
with self.assertRaises(asyncssh.KeyExportError):
self.pubkey.encode_agent_cert_private()
def check_decode_errors(self):
"""Check error code paths in key decoding"""
private_errors = [
('Non-ASCII', '\xff'),
('Incomplete ASN.1', b''),
('Invalid PKCS#1', der_encode(None)),
('Invalid PKCS#1 params',
der_encode((1, b'', TaggedDERObject(0, b'')))),
('Invalid PKCS#1 EC named curve OID',
der_encode((1, b'',
TaggedDERObject(0, ObjectIdentifier('1.1'))))),
('Invalid PKCS#8',
der_encode((0, (self.privkey.pkcs8_oid, ()), der_encode(None)))),
('Invalid PKCS#8 ASN.1',
der_encode((0, (self.privkey.pkcs8_oid, None), b''))),
('Invalid PKCS#8 params',
der_encode((1, (self.privkey.pkcs8_oid, b''),
der_encode((1, b''))))),
('Invalid PEM header', b'-----BEGIN XXX-----\n'),
('Missing PEM footer', b'-----BEGIN PRIVATE KEY-----\n'),
('Invalid PEM key type',
b'-----BEGIN XXX PRIVATE KEY-----\n' +
binascii.b2a_base64(der_encode(None)) +
b'-----END XXX PRIVATE KEY-----'),
('Invalid PEM Base64',
b'-----BEGIN PRIVATE KEY-----\n'
b'X\n'
b'-----END PRIVATE KEY-----'),
('Missing PKCS#1 passphrase',
b'-----BEGIN DSA PRIVATE KEY-----\n'
b'Proc-Type: 4,ENCRYPTED\n'
b'-----END DSA PRIVATE KEY-----'),
('Incomplete PEM ASN.1',
b'-----BEGIN PRIVATE KEY-----\n'
b'-----END PRIVATE KEY-----'),
('Missing PEM PKCS#8 passphrase',
b'-----BEGIN ENCRYPTED PRIVATE KEY-----\n' +
binascii.b2a_base64(der_encode(None)) +
b'-----END ENCRYPTED PRIVATE KEY-----'),
('Invalid PEM PKCS#1 key',
b'-----BEGIN DSA PRIVATE KEY-----\n' +
binascii.b2a_base64(der_encode(None)) +
b'-----END DSA PRIVATE KEY-----'),
('Invalid PEM PKCS#8 key',
b'-----BEGIN PRIVATE KEY-----\n' +
binascii.b2a_base64(der_encode(None)) +
b'-----END PRIVATE KEY-----'),
('Unknown format OpenSSH key',
b'-----BEGIN OPENSSH PRIVATE KEY-----\n' +
binascii.b2a_base64(b'XXX') +
b'-----END OPENSSH PRIVATE KEY-----'),
('Incomplete OpenSSH key',
b'-----BEGIN OPENSSH PRIVATE KEY-----\n' +
binascii.b2a_base64(b'openssh-key-v1\0') +
b'-----END OPENSSH PRIVATE KEY-----'),
('Invalid OpenSSH nkeys',
b'-----BEGIN OPENSSH PRIVATE KEY-----\n' +
binascii.b2a_base64(b''.join(
(b'openssh-key-v1\0', String(''), String(''), String(''),
UInt32(2), String(''), String('')))) +
b'-----END OPENSSH PRIVATE KEY-----'),
('Missing OpenSSH passphrase',
b'-----BEGIN OPENSSH PRIVATE KEY-----\n' +
binascii.b2a_base64(b''.join(
(b'openssh-key-v1\0', String('xxx'), String(''), String(''),
UInt32(1), String(''), String('')))) +
b'-----END OPENSSH PRIVATE KEY-----'),
('Mismatched OpenSSH check bytes',
b'-----BEGIN OPENSSH PRIVATE KEY-----\n' +
binascii.b2a_base64(b''.join(
(b'openssh-key-v1\0', String('none'), String(''), String(''),
UInt32(1), String(''), String(b''.join((UInt32(1),
UInt32(2))))))) +
b'-----END OPENSSH PRIVATE KEY-----'),
('Invalid OpenSSH algorithm',
b'-----BEGIN OPENSSH PRIVATE KEY-----\n' +
binascii.b2a_base64(b''.join(
(b'openssh-key-v1\0', String('none'), String(''), String(''),
UInt32(1), String(''), String(b''.join((UInt32(1), UInt32(1),
String('xxx'))))))) +
b'-----END OPENSSH PRIVATE KEY-----'),
('Invalid OpenSSH pad',
b'-----BEGIN OPENSSH PRIVATE KEY-----\n' +
binascii.b2a_base64(b''.join(
(b'openssh-key-v1\0', String('none'), String(''), String(''),
UInt32(1), String(''), String(b''.join((UInt32(1), UInt32(1),
String('ssh-dss'),
5*MPInt(0),
String(''),
b'\0')))))) +
b'-----END OPENSSH PRIVATE KEY-----')
]
decrypt_errors = [
('Invalid PKCS#1', der_encode(None)),
('Invalid PKCS#8', der_encode((0, (self.privkey.pkcs8_oid, ()),
der_encode(None)))),
('Invalid PEM params', b'-----BEGIN DSA PRIVATE KEY-----\n'
b'Proc-Type: 4,ENCRYPTED\n'
b'DEK-Info: XXX\n'
b'-----END DSA PRIVATE KEY-----'),
('Invalid PEM cipher', b'-----BEGIN DSA PRIVATE KEY-----\n'
b'Proc-Type: 4,ENCRYPTED\n'
b'DEK-Info: XXX,00\n'
b'-----END DSA PRIVATE KEY-----'),
('Invalid PEM IV', b'-----BEGIN DSA PRIVATE KEY-----\n'
b'Proc-Type: 4,ENCRYPTED\n'
b'DEK-Info: AES-256-CBC,XXX\n'
b'-----END DSA PRIVATE KEY-----'),
('Invalid PEM PKCS#8 encrypted data',
b'-----BEGIN ENCRYPTED PRIVATE KEY-----\n' +
binascii.b2a_base64(der_encode(None)) +
b'-----END ENCRYPTED PRIVATE KEY-----'),
('Invalid PEM PKCS#8 encrypted header',
b'-----BEGIN ENCRYPTED PRIVATE KEY-----\n' +
binascii.b2a_base64(der_encode((None, None))) +
b'-----END ENCRYPTED PRIVATE KEY-----'),
('Invalid PEM PKCS#8 encryption algorithm',
b'-----BEGIN ENCRYPTED PRIVATE KEY-----\n' +
binascii.b2a_base64(der_encode(((None, None), b''))) +
b'-----END ENCRYPTED PRIVATE KEY-----'),
('Invalid PEM PKCS#8 PBES1 encryption parameters',
b'-----BEGIN ENCRYPTED PRIVATE KEY-----\n' +
binascii.b2a_base64(der_encode(((_ES1_SHA1_DES, None), b''))) +
b'-----END ENCRYPTED PRIVATE KEY-----'),
('Invalid PEM PKCS#8 PBES1 PKCS#12 encryption parameters',
b'-----BEGIN ENCRYPTED PRIVATE KEY-----\n' +
binascii.b2a_base64(der_encode(((_P12_RC4_40, None), b''))) +
b'-----END ENCRYPTED PRIVATE KEY-----'),
('Invalid PEM PKCS#8 PBES1 PKCS#12 salt',
b'-----BEGIN ENCRYPTED PRIVATE KEY-----\n' +
binascii.b2a_base64(der_encode(((_P12_RC4_40, (b'', 0)), b''))) +
b'-----END ENCRYPTED PRIVATE KEY-----'),
('Invalid PEM PKCS#8 PBES1 PKCS#12 iteration count',
b'-----BEGIN ENCRYPTED PRIVATE KEY-----\n' +
binascii.b2a_base64(der_encode(((_P12_RC4_40, (b'x', 0)), b''))) +
b'-----END ENCRYPTED PRIVATE KEY-----'),
('Invalid PEM PKCS#8 PBES2 encryption parameters',
b'-----BEGIN ENCRYPTED PRIVATE KEY-----\n' +
binascii.b2a_base64(der_encode(((_ES2, None), b''))) +
b'-----END ENCRYPTED PRIVATE KEY-----'),
('Invalid PEM PKCS#8 PBES2 KDF algorithm',
b'-----BEGIN ENCRYPTED PRIVATE KEY-----\n' +
binascii.b2a_base64(der_encode(
((_ES2, ((None, None), (None, None))), b''))) +
b'-----END ENCRYPTED PRIVATE KEY-----'),
('Invalid PEM PKCS#8 PBES2 encryption algorithm',
b'-----BEGIN ENCRYPTED PRIVATE KEY-----\n' +
binascii.b2a_base64(der_encode(
((_ES2, ((_ES2_PBKDF2, None), (None, None))), b''))) +
b'-----END ENCRYPTED PRIVATE KEY-----'),
('Invalid PEM PKCS#8 PBES2 PBKDF2 parameters',
b'-----BEGIN ENCRYPTED PRIVATE KEY-----\n' +
binascii.b2a_base64(der_encode(
((_ES2, ((_ES2_PBKDF2, None), (_ES2_AES128, None))), b''))) +
b'-----END ENCRYPTED PRIVATE KEY-----'),
('Invalid PEM PKCS#8 PBES2 PBKDF2 salt',
b'-----BEGIN ENCRYPTED PRIVATE KEY-----\n' +
binascii.b2a_base64(der_encode(
((_ES2, ((_ES2_PBKDF2, (None, None)),
(_ES2_AES128, None))), b''))) +
b'-----END ENCRYPTED PRIVATE KEY-----'),
('Invalid PEM PKCS#8 PBES2 PBKDF2 iteration count',
b'-----BEGIN ENCRYPTED PRIVATE KEY-----\n' +
binascii.b2a_base64(der_encode(
((_ES2, ((_ES2_PBKDF2, (b'', None)),
(_ES2_AES128, None))), b''))) +
b'-----END ENCRYPTED PRIVATE KEY-----'),
('Invalid PEM PKCS#8 PBES2 PBKDF2 PRF',
b'-----BEGIN ENCRYPTED PRIVATE KEY-----\n' +
binascii.b2a_base64(der_encode(
((_ES2, ((_ES2_PBKDF2, (b'', 0, None)),
(_ES2_AES128, None))), b''))) +
b'-----END ENCRYPTED PRIVATE KEY-----'),
('Unknown PEM PKCS#8 PBES2 PBKDF2 PRF',
b'-----BEGIN ENCRYPTED PRIVATE KEY-----\n' +
binascii.b2a_base64(der_encode(
((_ES2, ((_ES2_PBKDF2, (b'', 0,
(ObjectIdentifier('1.1'), None))),
(_ES2_AES128, None))), b''))) +
b'-----END ENCRYPTED PRIVATE KEY-----'),
('Invalid PEM PKCS#8 PBES2 encryption parameters',
b'-----BEGIN ENCRYPTED PRIVATE KEY-----\n' +
binascii.b2a_base64(der_encode(
((_ES2, ((_ES2_PBKDF2, (b'', 0)),
(_ES2_AES128, None))), b''))) +
b'-----END ENCRYPTED PRIVATE KEY-----'),
('Invalid length PEM PKCS#8 PBES2 IV',