-
Notifications
You must be signed in to change notification settings - Fork 0
/
ssh.py
1626 lines (1412 loc) · 55.8 KB
/
ssh.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 Adi Roiban.
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
SSH keys management.
"""
import base64
import binascii
import hmac
import itertools
import struct
import textwrap
from hashlib import md5, sha1
from Crypto import Util
from Crypto.Cipher import AES, DES3
from Crypto.PublicKey import DSA, RSA
from OpenSSL import rand
from pyasn1.codec.ber import decoder as berDecoder
from pyasn1.codec.ber import encoder as berEncoder
from pyasn1.error import PyAsn1Error
from pyasn1.type import univ
from chevah.compat import local_filesystem
from chevah.keycert import common, sexpy, _path
from chevah.keycert.exceptions import (
BadKeyError,
EncryptedKeyError,
KeyCertException,
)
DEFAULT_PUBLIC_KEY_EXTENSION = u'.pub'
DEFAULT_KEY_SIZE = 1024
DEFAULT_KEY_TYPE = 'rsa'
SSHCOM_MAGIC_NUMBER = int('3f6ff9eb', base=16)
PUTTY_HMAC_KEY = 'putty-private-key-file-mac-key'
ID_SHA1 = '\x30\x21\x30\x09\x06\x05\x2b\x0e\x03\x02\x1a\x05\x00\x04\x14'
def generate_ssh_key_parser(
subparsers, name, default_key_size=2048, default_key_type='rsa'):
"""
Create an argparse sub-command with `name` attached to `subparsers`.
"""
generate_ssh_key = subparsers.add_parser(
name,
help='Create a SSH public and private key pair.',
)
generate_ssh_key.add_argument(
'--key-file',
metavar='FILE',
help=(
'Store the keys pair in FILE and FILE.pub. Default id_TYPE.'),
)
generate_ssh_key.add_argument(
'--key-size',
type=int, metavar="SIZE", default=default_key_size,
help='Generate a RSA or DSA key of size SIZE. Default %(default)s',
)
generate_ssh_key.add_argument(
'--key-type',
metavar="[rsa|dsa]", default=default_key_type,
help='Generate a DSA or RSA key. Default %(default)s.',
)
generate_ssh_key.add_argument(
'--key-comment',
metavar="COMMENT_TEXT",
help=(
'Generate the public key using this comment. Default no comment.'),
)
generate_ssh_key.add_argument(
'--key-skip',
action='store_true', default=False,
help='Do not create a new key if a key file already exists.',
)
return generate_ssh_key
def generate_ssh_key(options, open_method=None):
"""
Generate a SSH RSA or DSA key and store it on disk.
`options` is an argparse namespace. See `generate_ssh_key_subparser`.
Return a tuple of (exit_code, operation_message, key).
For success, exit_code is 0.
`open_method` is a helper for dependency injection during tests.
"""
key = None
if open_method is None: # pragma: no cover
open_method = open
exit_code = 0
message = ''
try:
key_size = options.key_size
key_type = options.key_type.lower()
if not hasattr(options, 'key_file') or options.key_file is None:
options.key_file = u'id_%s' % (key_type)
private_file = options.key_file
public_file = u'%s%s' % (
options.key_file, DEFAULT_PUBLIC_KEY_EXTENSION)
skip = _skip_key_generation(options, private_file, public_file)
if skip:
return (0, u'Key already exists.', key)
key = Key.generate(key_type=key_type, key_size=key_size)
with open_method(_path(private_file), 'wb') as file_handler:
_store_OpenSSH(key, private_file=file_handler)
key_comment = None
if hasattr(options, 'key_comment') and options.key_comment:
key_comment = options.key_comment
message_comment = u'having comment "%s"' % key_comment
else:
message_comment = u'without a comment'
with open_method(_path(public_file), 'wb') as file_handler:
_store_OpenSSH(key, public_file=file_handler, comment=key_comment)
message = (
u'SSH key of type "%s" and length "%d" generated as '
u'public key file "%s" and private key file "%s" %s.') % (
key_type,
key_size,
public_file,
private_file,
message_comment,
)
exit_code = 0
except KeyCertException as error:
exit_code = 1
message = error.message
except Exception as error:
exit_code = 1
message = str(error)
return (exit_code, message, key)
def _store_OpenSSH(key, public_file=None, private_file=None, comment=None):
"""
Store the public and private key into a file like object using
OpenSSH format.
"""
if public_file:
public_openssh = key.public().toString(type='openssh')
if comment:
public_content = '%s %s' % (
public_openssh, comment.encode('utf-8'))
else:
public_content = public_openssh
public_file.write(public_content)
if private_file:
private_file.write(key.toString(type='openssh'))
def _skip_key_generation(options, private_file, public_file):
"""
Return True when key generation can be skipped.
Key generation can be skipped when private key already exists. Public
key is ignored.
Raise KeyCertException if file exists.
"""
private_segments = local_filesystem.getSegmentsFromRealPath(private_file)
if local_filesystem.exists(private_segments):
if options.key_skip:
return True
else:
raise KeyCertException(
u'Private key already exists. %s' % private_file)
public_segments = local_filesystem.getSegmentsFromRealPath(public_file)
if local_filesystem.exists(public_segments):
raise KeyCertException(u'Public key already exists. %s' % public_file)
return False
class Key(object):
"""
An object representing a key. A key can be either a public or
private key. A public key can verify a signature; a private key can
create or verify a signature. To generate a string that can be stored
on disk, use the toString method. If you have a private key, but want
the string representation of the public key, use Key.public().toString().
@ivar keyObject: The C{Crypto.PublicKey.pubkey.pubkey} object that
operations are performed with.
"""
@staticmethod
def secureRandom(n): # pragma: no cover
return rand.bytes(n)
def __init__(self, keyObject):
"""
Initialize a PublicKey with a C{Crypto.PublicKey.pubkey.pubkey}
object.
@type keyObject: C{Crypto.PublicKey.pubkey.pubkey}
"""
self.keyObject = keyObject
def __eq__(self, other):
"""
Return True if other represents an object with the same key.
"""
if type(self) == type(other):
return self.type() == other.type() and self.data() == other.data()
else:
return NotImplemented
def __ne__(self, other):
"""
Return True if other represents anything other than this key.
"""
result = self.__eq__(other)
if result == NotImplemented:
return result
return not result
def __repr__(self):
"""
Return a pretty representation of this object.
"""
lines = [
'<%s %s (%s bits)' % (
self.type(),
self.isPublic() and 'Public Key' or 'Private Key',
self.keyObject.size())]
for k, v in sorted(self.data().items()):
lines.append('attr %s:' % k)
by = common.MP(v)[4:]
while by:
m = by[:15]
by = by[15:]
o = ''
for c in m:
o = o + '%02x:' % ord(c)
if len(m) < 15:
o = o[:-1]
lines.append('\t' + o)
lines[-1] = lines[-1] + '>'
return '\n'.join(lines)
@classmethod
def fromFile(cls, filename, type=None, passphrase=None, encoding='utf-8'):
"""
Return a Key object corresponding to the data in filename. type
and passphrase function as they do in fromString.
"""
with open(_path(filename, encoding), 'rb') as file:
return cls.fromString(file.read(), type, passphrase)
@classmethod
def fromString(cls, data, type=None, passphrase=None):
"""
Return a Key object corresponding to the string data.
type is optionally the type of string, matching a _fromString_*
method. Otherwise, the _guessStringType() classmethod will be used
to guess a type. If the key is encrypted, passphrase is used as
the decryption key.
@type data: C{str}
@type type: C{None}/C{str}
@type passphrase: C{None}/C{str}
@rtype: C{Key}
"""
if type is None:
type = cls._guessStringType(data)
if type is None:
raise BadKeyError('Cannot guess the type for %r' % data[:80])
try:
method = getattr(cls, '_fromString_%s' % type.upper(), None)
if method is None:
raise BadKeyError('no _fromString method for %s' % type)
if method.func_code.co_argcount == 2: # no passphrase
if passphrase:
raise BadKeyError('key not encrypted')
return method(data)
else:
return method(data, passphrase)
except (IndexError):
# Most probably some parts are missing from the key, so
# we consider it too short.
raise BadKeyError('Key is too short.')
except (struct.error, binascii.Error, TypeError):
raise BadKeyError('Fail to parse key content.')
def toString(self, type, extra=None):
"""
Create a string representation of this key. If the key is a private
key and you want the represenation of its public key, use
C{key.public().toString()}. type maps to a _toString_* method.
@param type: The type of string to emit. Currently supported values
are C{'OPENSSH'}, C{'LSH'}, and C{'AGENTV3'}.
@type type: L{str}
@param extra: Any extra data supported by the selected format which
is not part of the key itself. For public OpenSSH keys, this is
a comment. For private OpenSSH keys, this is a passphrase to
encrypt with.
@type extra: L{str} or L{NoneType}
@rtype: L{str}
"""
method = getattr(self, '_toString_%s' % type.upper(), None)
if method is None:
raise BadKeyError('unknown type: %s' % type)
if method.func_code.co_argcount == 2:
return method(extra)
else:
return method()
@classmethod
def generate(cls, key_type=DEFAULT_KEY_TYPE, key_size=DEFAULT_KEY_SIZE):
"""
Return a new key.
"""
if not key_type:
key_type = 'not-specified'
key_type = key_type.lower()
if key_type == u'rsa':
key_class = RSA
elif key_type == u'dsa':
key_class = DSA
else:
raise KeyCertException('Unknown key type "%s".' % (key_type))
key = None
try:
key = key_class.generate(bits=key_size)
except ValueError, error:
raise KeyCertException(
u'Wrong key size "%d". %s.' % (key_size, error))
return cls(key)
@classmethod
def _guessStringType(cls, data):
"""
Guess the type of key in data.
The types map to _fromString_* methods.
"""
if data.startswith('ssh-') or data.startswith('ecdsa-sha2-nistp'):
return 'public_openssh'
elif data.startswith('---- BEGIN SSH2 PUBLIC KEY ----'):
return 'public_sshcom'
elif data.startswith('---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----'):
return 'private_sshcom'
elif (
data.startswith('-----BEGIN RSA') or
data.startswith('-----BEGIN DSA') or
data.startswith('-----BEGIN EC')
):
return 'private_openssh'
elif data.startswith('PuTTY-User-Key-File-2'):
return 'private_putty'
elif data.startswith('{'):
return 'public_lsh'
elif data.startswith('('):
return 'private_lsh'
elif data.startswith('\x00\x00\x00\x07ssh-'):
ignored, rest = common.getNS(data)
count = 0
while rest:
count += 1
ignored, rest = common.getMP(rest)
if count > 4:
return 'agentv3'
else:
return 'blob'
@classmethod
def getKeyFormat(cls, data):
"""
Return a type of key.
"""
key_type = cls._guessStringType(data)
human_readable = {
'public_openssh': 'OpenSSH Public',
'private_openssh': 'OpenSSH Private',
'public_sshcom': 'SSH.com Public',
'private_sshcom': 'SSH.com Private',
'private_putty': 'PuTTY Private',
'public_lsh': 'LSH Public',
'private_lsh': 'LSH Private',
}
return human_readable.get(key_type, 'Unknown format')
@property
def size(self):
"""
Return the key size.
"""
return self.keyObject.size() + 1
@property
def private_openssh(self):
"""
Return the OpenSSH representation for the public key part.
"""
return self.toString(type='openssh')
@property
def public_openssh(self):
"""
Return the OpenSSH representation for private key part.
"""
return self.public().toString(type='openssh')
def type(self):
"""
Return the type of the object we wrap. Currently this can only be
'RSA' or 'DSA'.
"""
# the class is Crypto.PublicKey.<type>.<stuff we don't care about>
mod = self.keyObject.__class__.__module__
if mod.startswith('Crypto.PublicKey'):
type = mod.split('.')[2]
else:
raise RuntimeError('unknown type of object: %r' % self.keyObject)
if type in ('RSA', 'DSA'):
return type
else:
raise RuntimeError('unknown type of key: %s' % type)
def sshType(self):
"""
Return the type of the object we wrap as defined in the ssh protocol.
Currently this can only be 'ssh-rsa' or 'ssh-dss'.
"""
return {'RSA': 'ssh-rsa', 'DSA': 'ssh-dss'}[self.type()]
def data(self):
"""
Return the values of the public key as a dictionary.
@rtype: C{dict}
"""
keyData = {}
for name in self.keyObject.keydata:
value = getattr(self.keyObject, name, None)
if value is not None:
keyData[name] = value
return keyData
def blob(self):
"""
Return the public key blob for this key. The blob is the
over-the-wire format for public keys:
RSA keys::
string 'ssh-rsa'
integer e
integer n
DSA keys::
string 'ssh-dss'
integer p
integer q
integer g
integer y
@rtype: C{str}
"""
type = self.type()
data = self.data()
if type == 'RSA':
return (common.NS('ssh-rsa') + common.MP(data['e']) +
common.MP(data['n']))
elif type == 'DSA':
return (common.NS('ssh-dss') + common.MP(data['p']) +
common.MP(data['q']) + common.MP(data['g']) +
common.MP(data['y']))
def privateBlob(self):
"""
Return the private key blob for this key. The blob is the
over-the-wire format for private keys:
RSA keys::
string 'ssh-rsa'
integer n
integer e
integer d
integer u
integer p
integer q
DSA keys::
string 'ssh-dss'
integer p
integer q
integer g
integer y
integer x
"""
type = self.type()
data = self.data()
if type == 'RSA':
return (common.NS('ssh-rsa') + common.MP(data['n']) +
common.MP(data['e']) + common.MP(data['d']) +
common.MP(data['u']) + common.MP(data['p']) +
common.MP(data['q']))
elif type == 'DSA':
return (common.NS('ssh-dss') + common.MP(data['p']) +
common.MP(data['q']) + common.MP(data['g']) +
common.MP(data['y']) + common.MP(data['x']))
def public(self):
"""
Returns a version of this key containing only the public key data.
If this is a public key, this may or may not be the same object
as self.
"""
return Key(self.keyObject.publickey())
def isPublic(self):
"""
Returns True if this Key is a public key.
"""
return not self.keyObject.has_private()
def fingerprint(self):
"""
Get the user presentation of the fingerprint of this L{Key}. As
described by U{RFC 4716 section
4<http://tools.ietf.org/html/rfc4716#section-4>}::
The fingerprint of a public key consists of the output of the MD5
message-digest algorithm [RFC1321]. The input to the algorithm is
the public key data as specified by [RFC4253]. (...) The output
of the (MD5) algorithm is presented to the user as a sequence of 16
octets printed as hexadecimal with lowercase letters and separated
by colons.
@return: the user presentation of this L{Key}'s fingerprint, as a
string.
@rtype: L{str}
"""
return ':'.join([x.encode('hex') for x in md5(self.blob()).digest()])
def sign(self, data):
"""
Returns a signature with this Key.
@type data: C{str}
@rtype: C{str}
"""
if self.type() == 'RSA':
digest = pkcs1Digest(data, self.keyObject.size() / 8)
signature = self.keyObject.sign(digest, '')[0]
ret = common.NS(Util.number.long_to_bytes(signature))
elif self.type() == 'DSA':
digest = sha1(data).digest()
randomBytes = self.secureRandom(19)
sig = self.keyObject.sign(digest, randomBytes)
# SSH insists that the DSS signature blob be two 160-bit integers
# concatenated together. The sig[0], [1] numbers from obj.sign
# are just numbers, and could be any length from 0 to 160 bits.
# Make sure they are padded out to 160 bits (20 bytes each)
ret = common.NS(Util.number.long_to_bytes(sig[0], 20) +
Util.number.long_to_bytes(sig[1], 20))
return common.NS(self.sshType()) + ret
def verify(self, signature, data):
"""
Returns true if the signature for data is valid for this Key.
@type signature: C{str}
@type data: C{str}
@rtype: C{bool}
"""
if len(signature) == 40:
# DSA key with no padding
signatureType, signature = 'ssh-dss', common.NS(signature)
else:
signatureType, signature = common.getNS(signature)
if signatureType != self.sshType():
return False
if self.type() == 'RSA':
numbers = common.getMP(signature)
digest = pkcs1Digest(data, self.keyObject.size() / 8)
elif self.type() == 'DSA':
signature = common.getNS(signature)[0]
numbers = [Util.number.bytes_to_long(n) for n in signature[:20],
signature[20:]]
digest = sha1(data).digest()
return self.keyObject.verify(digest, numbers)
@classmethod
def _fromString_BLOB(cls, blob):
"""
Return a public key object corresponding to this public key blob.
The format of a RSA public key blob is::
string 'ssh-rsa'
integer e
integer n
The format of a DSA public key blob is::
string 'ssh-dss'
integer p
integer q
integer g
integer y
@type blob: C{str}
@return: a C{Crypto.PublicKey.pubkey.pubkey} object
@raises BadKeyError: if the key type (the first string) is unknown.
"""
keyType, rest = common.getNS(blob)
if keyType == 'ssh-rsa':
e, n, rest = common.getMP(rest, 2)
return cls(RSA.construct((n, e)))
elif keyType == 'ssh-dss':
p, q, g, y, rest = common.getMP(rest, 4)
return cls(DSA.construct((y, g, p, q)))
else:
raise BadKeyError('unknown blob type: %s' % keyType)
@classmethod
def _fromString_PRIVATE_BLOB(cls, blob):
"""
Return a private key object corresponding to this private key blob.
The blob formats are as follows:
RSA keys::
string 'ssh-rsa'
integer n
integer e
integer d
integer u
integer p
integer q
DSA keys::
string 'ssh-dss'
integer p
integer q
integer g
integer y
integer x
@type blob: C{str}
@return: a C{Crypto.PublicKey.pubkey.pubkey} object
@raises BadKeyError: if the key type (the first string) is unknown.
"""
keyType, rest = common.getNS(blob)
if keyType == 'ssh-rsa':
n, e, d, u, p, q, rest = common.getMP(rest, 6)
rsakey = cls(RSA.construct((n, e, d, p, q, u)))
return rsakey
elif keyType == 'ssh-dss':
p, q, g, y, x, rest = common.getMP(rest, 5)
dsakey = cls(DSA.construct((y, g, p, q, x)))
return dsakey
else:
raise BadKeyError('unknown blob type: %s' % keyType)
@classmethod
def _fromString_PUBLIC_OPENSSH(cls, data):
"""
Return a public key object corresponding to this OpenSSH public key
string. The format of an OpenSSH public key string is::
<key type> <base64-encoded public key blob>
@type data: C{str}
@return: A {Crypto.PublicKey.pubkey.pubkey} object
@raises BadKeyError: if the blob type is unknown.
"""
blob = base64.decodestring(data.split()[1])
return cls._fromString_BLOB(blob)
@classmethod
def _fromString_PRIVATE_OPENSSH(cls, data, passphrase):
"""
Return a private key object corresponding to this OpenSSH private key
string. If the key is encrypted, passphrase MUST be provided.
Providing a passphrase for an unencrypted key is an error.
The format of an OpenSSH private key string is::
-----BEGIN <key type> PRIVATE KEY-----
[Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,<initialization value>]
<base64-encoded ASN.1 structure>
------END <key type> PRIVATE KEY------
The ASN.1 structure of a RSA key is::
(0, n, e, d, p, q)
The ASN.1 structure of a DSA key is::
(0, p, q, g, y, x)
@type data: C{str}
@type passphrase: C{str}
@return: a C{Crypto.PublicKey.pubkey.pubkey} object
@raises BadKeyError: if
* a passphrase is provided for an unencrypted key
* the ASN.1 encoding is incorrect
@raises EncryptedKeyError: if
* a passphrase is not provided for an encrypted key
"""
lines = data.strip().split('\n')
kind = lines[0].split(' ')[1]
if lines[1].startswith('Proc-Type: 4,ENCRYPTED'): # encrypted key
if not passphrase:
raise EncryptedKeyError('Passphrase must be provided '
'for an encrypted key')
# Determine cipher and initialization vector
try:
_, cipher_iv_info = lines[2].split(' ', 1)
cipher, ivdata = cipher_iv_info.rstrip().split(',', 1)
except ValueError:
raise BadKeyError('invalid DEK-info %r' % lines[2])
if cipher == 'AES-128-CBC':
CipherClass = AES
keySize = 16
if len(ivdata) != 32:
raise BadKeyError('AES encrypted key with a bad IV')
elif cipher == 'DES-EDE3-CBC':
CipherClass = DES3
keySize = 24
if len(ivdata) != 16:
raise BadKeyError('DES encrypted key with a bad IV')
else:
raise BadKeyError('unknown encryption type %r' % cipher)
# extract keyData for decoding
iv = ''.join([chr(int(ivdata[i:i + 2], 16))
for i in range(0, len(ivdata), 2)])
ba = md5(passphrase + iv[:8]).digest()
bb = md5(ba + passphrase + iv[:8]).digest()
decKey = (ba + bb)[:keySize]
b64Data = base64.decodestring(''.join(lines[3:-1]))
keyData = CipherClass.new(decKey,
CipherClass.MODE_CBC,
iv).decrypt(b64Data)
removeLen = ord(keyData[-1])
keyData = keyData[:-removeLen]
else:
b64Data = ''.join(lines[1:-1])
keyData = base64.decodestring(b64Data)
try:
decodedKey = berDecoder.decode(keyData)[0]
except PyAsn1Error, e:
raise BadKeyError('Failed to decode key (Bad Passphrase?): %s' % e)
if kind == 'RSA':
if len(decodedKey) == 2: # alternate RSA key
decodedKey = decodedKey[0]
if len(decodedKey) < 6:
raise BadKeyError('RSA key failed to decode properly')
n, e, d, p, q = [long(value) for value in decodedKey[1:6]]
if p > q: # make p smaller than q
p, q = q, p
return cls(RSA.construct((n, e, d, p, q)))
elif kind == 'DSA':
p, q, g, y, x = [long(value) for value in decodedKey[1: 6]]
if len(decodedKey) < 6:
raise BadKeyError('DSA key failed to decode properly')
return cls(DSA.construct((y, g, p, q, x)))
else:
raise BadKeyError('Key type %s not supported.' % (kind))
def _toString_OPENSSH(self, extra):
"""
Return a public or private OpenSSH string. See
_fromString_PUBLIC_OPENSSH and _fromString_PRIVATE_OPENSSH for the
string formats. If extra is present, it represents a comment for a
public key, or a passphrase for a private key.
@param extra: Comment for a public key or passphrase for a
private key
@type extra: C{str}
@rtype: C{str}
"""
data = self.data()
if self.isPublic():
b64Data = base64.encodestring(self.blob()).replace('\n', '')
if not extra:
extra = ''
return ('%s %s %s' % (self.sshType(), b64Data, extra)).strip()
else:
lines = ['-----BEGIN %s PRIVATE KEY-----' % self.type()]
if self.type() == 'RSA':
p, q = data['p'], data['q']
objData = (0, data['n'], data['e'], data['d'], q, p,
data['d'] % (q - 1), data['d'] % (p - 1),
data['u'])
else:
objData = (0, data['p'], data['q'], data['g'], data['y'],
data['x'])
asn1Sequence = univ.Sequence()
for index, value in itertools.izip(itertools.count(), objData):
asn1Sequence.setComponentByPosition(index, univ.Integer(value))
asn1Data = berEncoder.encode(asn1Sequence)
if extra:
iv = self.secureRandom(8)
hexiv = ''.join(['%02X' % ord(x) for x in iv])
lines.append('Proc-Type: 4,ENCRYPTED')
lines.append('DEK-Info: DES-EDE3-CBC,%s\n' % hexiv)
ba = md5(extra + iv).digest()
bb = md5(ba + extra + iv).digest()
encKey = (ba + bb)[:24]
padLen = 8 - (len(asn1Data) % 8)
asn1Data += (chr(padLen) * padLen)
asn1Data = DES3.new(encKey, DES3.MODE_CBC,
iv).encrypt(asn1Data)
b64Data = base64.encodestring(asn1Data).replace('\n', '')
lines += [b64Data[i:i + 64] for i in range(0, len(b64Data), 64)]
lines.append('-----END %s PRIVATE KEY-----' % self.type())
return '\n'.join(lines)
@classmethod
def _fromString_PUBLIC_LSH(cls, data):
"""
Return a public key corresponding to this LSH public key string.
The LSH public key string format is::
<s-expression: ('public-key', (<key type>, (<name, <value>)+))>
The names for a RSA (key type 'rsa-pkcs1-sha1') key are: n, e.
The names for a DSA (key type 'dsa') key are: y, g, p, q.
@type data: C{str}
@return: a C{Crypto.PublicKey.pubkey.pubkey} object
@raises BadKeyError: if the key type is unknown
"""
sexp = sexpy.parse(base64.decodestring(data[1:-1]))
assert sexp[0] == 'public-key'
kd = {}
for name, data in sexp[1][1:]:
kd[name] = common.getMP(common.NS(data))[0]
if sexp[1][0] == 'dsa':
return cls(DSA.construct((kd['y'], kd['g'], kd['p'], kd['q'])))
elif sexp[1][0] == 'rsa-pkcs1-sha1':
return cls(RSA.construct((kd['n'], kd['e'])))
else:
raise BadKeyError('unknown lsh key type %s' % sexp[1][0])
@classmethod
def _fromString_PRIVATE_LSH(cls, data):
"""
Return a private key corresponding to this LSH private key string.
The LSH private key string format is::
<s-expression: ('private-key', (<key type>, (<name>, <value>)+))>
The names for a RSA (key type 'rsa-pkcs1-sha1') key are: n, e, d, p, q.
The names for a DSA (key type 'dsa') key are: y, g, p, q, x.
@type data: C{str}
@return: a {Crypto.PublicKey.pubkey.pubkey} object
@raises BadKeyError: if the key type is unknown
"""
sexp = sexpy.parse(data)
assert sexp[0] == 'private-key'
kd = {}
for name, data in sexp[1][1:]:
kd[name] = common.getMP(common.NS(data))[0]
if sexp[1][0] == 'dsa':
assert len(kd) == 5, len(kd)
return cls(DSA.construct((
kd['y'], kd['g'], kd['p'], kd['q'], kd['x'])))
elif sexp[1][0] == 'rsa-pkcs1':
assert len(kd) == 8, len(kd)
if kd['p'] > kd['q']: # make p smaller than q
kd['p'], kd['q'] = kd['q'], kd['p']
return cls(RSA.construct((
kd['n'], kd['e'], kd['d'], kd['p'], kd['q'])))
else:
raise BadKeyError('unknown lsh key type %s' % sexp[1][0])
def _toString_LSH(self):
"""
Return a public or private LSH key. See _fromString_PUBLIC_LSH and
_fromString_PRIVATE_LSH for the key formats.
@rtype: C{str}
"""
data = self.data()
if self.isPublic():
if self.type() == 'RSA':
keyData = sexpy.pack([['public-key',
['rsa-pkcs1-sha1',
['n', common.MP(data['n'])[4:]],
['e', common.MP(data['e'])[4:]]]]])
elif self.type() == 'DSA':
keyData = sexpy.pack([['public-key',
['dsa',
['p', common.MP(data['p'])[4:]],
['q', common.MP(data['q'])[4:]],
['g', common.MP(data['g'])[4:]],
['y', common.MP(data['y'])[4:]]]]])
return '{' + base64.encodestring(keyData).replace('\n', '') + '}'
else:
if self.type() == 'RSA':
p, q = data['p'], data['q']
return sexpy.pack([['private-key',
['rsa-pkcs1',
['n', common.MP(data['n'])[4:]],
['e', common.MP(data['e'])[4:]],
['d', common.MP(data['d'])[4:]],
['p', common.MP(q)[4:]],
['q', common.MP(p)[4:]],
['a', common.MP(data['d'] % (q - 1))[4:]],
['b', common.MP(data['d'] % (p - 1))[4:]],
['c', common.MP(data['u'])[4:]]]]])
elif self.type() == 'DSA':
return sexpy.pack([['private-key',
['dsa',
['p', common.MP(data['p'])[4:]],
['q', common.MP(data['q'])[4:]],
['g', common.MP(data['g'])[4:]],
['y', common.MP(data['y'])[4:]],
['x', common.MP(data['x'])[4:]]]]])
@classmethod
def _fromString_AGENTV3(cls, data):
"""
Return a private key object corresponding to the Secure Shell Key
Agent v3 format.
The SSH Key Agent v3 format for a RSA key is::
string 'ssh-rsa'
integer e
integer d
integer n
integer u
integer p
integer q
The SSH Key Agent v3 format for a DSA key is::
string 'ssh-dss'
integer p
integer q
integer g
integer y
integer x
@type data: C{str}
@return: a C{Crypto.PublicKey.pubkey.pubkey} object
@raises BadKeyError: if the key type (the first string) is unknown
"""
keyType, data = common.getNS(data)
if keyType == 'ssh-dss':
p, data = common.getMP(data)
q, data = common.getMP(data)
g, data = common.getMP(data)
y, data = common.getMP(data)
x, data = common.getMP(data)
return cls(DSA.construct((y, g, p, q, x)))
elif keyType == 'ssh-rsa':
e, data = common.getMP(data)
d, data = common.getMP(data)
n, data = common.getMP(data)
u, data = common.getMP(data)
p, data = common.getMP(data)
q, data = common.getMP(data)
return cls(RSA.construct((n, e, d, p, q, u)))
else:
raise BadKeyError("unknown key type %s" % keyType)
def _toString_AGENTV3(self):
"""
Return a private Secure Shell Agent v3 key. See
_fromString_AGENTV3 for the key format.
@rtype: C{str}
"""
data = self.data()
if not self.isPublic():
if self.type() == 'RSA':
values = (data['e'], data['d'], data['n'], data['u'],
data['p'], data['q'])
elif self.type() == 'DSA':