Debian Codegraph @

lib/Crypto/PublicKey/DSA.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 #
3 # PublicKey/DSA.py : DSA signature primitive
4 #
5 # Written in 2008 by Dwayne C. Litzenberger <[email protected]>
6 #
7 # ===================================================================
8 # The contents of this file are dedicated to the public domain. To
9 # the extent that dedication to the public domain is not available,
10 # everyone is granted a worldwide, perpetual, royalty-free,
11 # non-exclusive license to exercise all rights associated with the
12 # contents of this file for any purpose whatsoever.
13 # No rights are reserved.
14 #
15 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
19 # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
20 # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
21 # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 # SOFTWARE.
23 # ===================================================================
24
25 __all__ = ['generate', 'construct', 'DsaKey', 'import_key' ]
26
27 import binascii
28 import struct
29 import itertools
30
31 from Crypto.Util.py3compat import bchr, bord, tobytes, tostr, iter_range
32
33 from Crypto import Random
34 from Crypto.IO import PKCS8, PEM
35 from Crypto.Hash import SHA256
36 from Crypto.Util.asn1 import (
37 DerObject, DerSequence,
38 DerInteger, DerObjectId,
39 DerBitString,
40 )
41
42 from Crypto.Math.Numbers import Integer
43 from Crypto.Math.Primality import (test_probable_prime, COMPOSITE,
44 PROBABLY_PRIME)
45
46 from Crypto.PublicKey import (_expand_subject_public_key_info,
47 _create_subject_public_key_info,
48 _extract_subject_public_key_info)
49
50 # ; The following ASN.1 types are relevant for DSA
51 #
52 # SubjectPublicKeyInfo ::= SEQUENCE {
53 # algorithm AlgorithmIdentifier,
54 # subjectPublicKey BIT STRING
55 # }
56 #
57 # id-dsa ID ::= { iso(1) member-body(2) us(840) x9-57(10040) x9cm(4) 1 }
58 #
59 # ; See RFC3279
60 # Dss-Parms ::= SEQUENCE {
61 # p INTEGER,
62 # q INTEGER,
63 # g INTEGER
64 # }
65 #
66 # DSAPublicKey ::= INTEGER
67 #
68 # DSSPrivatKey_OpenSSL ::= SEQUENCE
69 # version INTEGER,
70 # p INTEGER,
71 # q INTEGER,
72 # g INTEGER,
73 # y INTEGER,
74 # x INTEGER
75 # }
76 #
77
78 class DsaKey(object):
79 r"""Class defining an actual DSA key.
80 Do not instantiate directly.
81 Use :func:`generate`, :func:`construct` or :func:`import_key` instead.
82
83 :ivar p: DSA modulus
84 :vartype p: integer
85
86 :ivar q: Order of the subgroup
87 :vartype q: integer
88
89 :ivar g: Generator
90 :vartype g: integer
91
92 :ivar y: Public key
93 :vartype y: integer
94
95 :ivar x: Private key
96 :vartype x: integer
97
98 :undocumented: exportKey, publickey
99 """
100
101 _keydata = ['y', 'g', 'p', 'q', 'x']
102
103 def __init__(self, key_dict):
104 input_set = set(key_dict.keys())
105 public_set = set(('y' , 'g', 'p', 'q'))
106 if not public_set.issubset(input_set):
107 raise ValueError("Some DSA components are missing = %s" %
108 str(public_set - input_set))
109 extra_set = input_set - public_set
110 if extra_set and extra_set != set(('x',)):
111 raise ValueError("Unknown DSA components = %s" %
112 str(extra_set - set(('x',))))
113 self._key = dict(key_dict)
114
115 def _sign(self, m, k):
116 if not self.has_private():
117 raise TypeError("DSA public key cannot be used for signing")
118 if not (1 < k < self.q):
119 raise ValueError("k is not between 2 and q-1")
120
121 x, q, p, g = [self._key[comp] for comp in ['x', 'q', 'p', 'g']]
122
123 blind_factor = Integer.random_range(min_inclusive=1,
124 max_exclusive=q)
125 inv_blind_k = (blind_factor * k).inverse(q)
126 blind_x = x * blind_factor
127
128 r = pow(g, k, p) % q # r = (g**k mod p) mod q
129 s = (inv_blind_k * (blind_factor * m + blind_x * r)) % q
130 return map(int, (r, s))
131
132 def _verify(self, m, sig):
133 r, s = sig
134 y, q, p, g = [self._key[comp] for comp in ['y', 'q', 'p', 'g']]
135 if not (0 < r < q) or not (0 < s < q):
136 return False
137 w = Integer(s).inverse(q)
138 u1 = (w * m) % q
139 u2 = (w * r) % q
140 v = (pow(g, u1, p) * pow(y, u2, p) % p) % q
141 return v == r
142
143 def has_private(self):
144 """Whether this is a DSA private key"""
145
146 return 'x' in self._key
147
148 def can_encrypt(self): # legacy
149 return False
150
151 def can_sign(self): # legacy
152 return True
153
154 def public_key(self):
155 """A matching DSA public key.
156
157 Returns:
158 a new :class:`DsaKey` object
159 """
160
161 public_components = dict((k, self._key[k]) for k in ('y', 'g', 'p', 'q'))
162 return DsaKey(public_components)
163
164 def __eq__(self, other):
165 if bool(self.has_private()) != bool(other.has_private()):
166 return False
167
168 result = True
169 for comp in self._keydata:
170 result = result and (getattr(self._key, comp, None) ==
171 getattr(other._key, comp, None))
172 return result
173
174 def __ne__(self, other):
175 return not self.__eq__(other)
176
177 def __getstate__(self):
178 # DSA key is not pickable
179 from pickle import PicklingError
180 raise PicklingError
181
182 def domain(self):
183 """The DSA domain parameters.
184
185 Returns
186 tuple : (p,q,g)
187 """
188
189 return [int(self._key[comp]) for comp in ('p', 'q', 'g')]
190
191 def __repr__(self):
192 attrs = []
193 for k in self._keydata:
194 if k == 'p':
195 bits = Integer(self.p).size_in_bits()
196 attrs.append("p(%d)" % (bits,))
197 elif hasattr(self, k):
198 attrs.append(k)
199 if self.has_private():
200 attrs.append("private")
201 # PY3K: This is meant to be text, do not change to bytes (data)
202 return "<%s @0x%x %s>" % (self.__class__.__name__, id(self), ",".join(attrs))
203
204 def __getattr__(self, item):
205 try:
206 return int(self._key[item])
207 except KeyError:
208 raise AttributeError(item)
209
210 def export_key(self, format='PEM', pkcs8=None, passphrase=None,
211 protection=None, randfunc=None):
212 """Export this DSA key.
213
214 Args:
215 format (string):
216 The encoding for the output:
217
218 - *'PEM'* (default). ASCII as per `RFC1421`_/ `RFC1423`_.
219 - *'DER'*. Binary ASN.1 encoding.
220 - *'OpenSSH'*. ASCII one-liner as per `RFC4253`_.
221 Only suitable for public keys, not for private keys.
222
223 passphrase (string):
224 *Private keys only*. The pass phrase to protect the output.
225
226 pkcs8 (boolean):
227 *Private keys only*. If ``True`` (default), the key is encoded
228 with `PKCS#8`_. If ``False``, it is encoded in the custom
229 OpenSSL/OpenSSH container.
230
231 protection (string):
232 *Only in combination with a pass phrase*.
233 The encryption scheme to use to protect the output.
234
235 If :data:`pkcs8` takes value ``True``, this is the PKCS#8
236 algorithm to use for deriving the secret and encrypting
237 the private DSA key.
238 For a complete list of algorithms, see :mod:`Crypto.IO.PKCS8`.
239 The default is *PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC*.
240
241 If :data:`pkcs8` is ``False``, the obsolete PEM encryption scheme is
242 used. It is based on MD5 for key derivation, and Triple DES for
243 encryption. Parameter :data:`protection` is then ignored.
244
245 The combination ``format='DER'`` and ``pkcs8=False`` is not allowed
246 if a passphrase is present.
247
248 randfunc (callable):
249 A function that returns random bytes.
250 By default it is :func:`Crypto.Random.get_random_bytes`.
251
252 Returns:
253 byte string : the encoded key
254
255 Raises:
256 ValueError : when the format is unknown or when you try to encrypt a private
257 key with *DER* format and OpenSSL/OpenSSH.
258
259 .. warning::
260 If you don't provide a pass phrase, the private key will be
261 exported in the clear!
262
263 .. _RFC1421: http://www.ietf.org/rfc/rfc1421.txt
264 .. _RFC1423: http://www.ietf.org/rfc/rfc1423.txt
265 .. _RFC4253: http://www.ietf.org/rfc/rfc4253.txt
266 .. _`PKCS#8`: http://www.ietf.org/rfc/rfc5208.txt
267 """
268
269 if passphrase is not None:
270 passphrase = tobytes(passphrase)
271
272 if randfunc is None:
273 randfunc = Random.get_random_bytes
274
275 if format == 'OpenSSH':
276 tup1 = [self._key[x].to_bytes() for x in ('p', 'q', 'g', 'y')]
277
278 def func(x):
279 if (bord(x[0]) & 0x80):
280 return bchr(0) + x
281 else:
282 return x
283
284 tup2 = [func(x) for x in tup1]
285 keyparts = [b'ssh-dss'] + tup2
286 keystring = b''.join(
287 [struct.pack(">I", len(kp)) + kp for kp in keyparts]
288 )
289 return b'ssh-dss ' + binascii.b2a_base64(keystring)[:-1]
290
291 # DER format is always used, even in case of PEM, which simply
292 # encodes it into BASE64.
293 params = DerSequence([self.p, self.q, self.g])
294 if self.has_private():
295 if pkcs8 is None:
296 pkcs8 = True
297 if pkcs8:
298 if not protection:
299 protection = 'PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC'
300 private_key = DerInteger(self.x).encode()
301 binary_key = PKCS8.wrap(
302 private_key, oid, passphrase,
303 protection, key_params=params,
304 randfunc=randfunc
305 )
306 if passphrase:
307 key_type = 'ENCRYPTED PRIVATE'
308 else:
309 key_type = 'PRIVATE'
310 passphrase = None
311 else:
312 if format != 'PEM' and passphrase:
313 raise ValueError("DSA private key cannot be encrypted")
314 ints = [0, self.p, self.q, self.g, self.y, self.x]
315 binary_key = DerSequence(ints).encode()
316 key_type = "DSA PRIVATE"
317 else:
318 if pkcs8:
319 raise ValueError("PKCS#8 is only meaningful for private keys")
320
321 binary_key = _create_subject_public_key_info(oid,
322 DerInteger(self.y), params)
323 key_type = "PUBLIC"
324
325 if format == 'DER':
326 return binary_key
327 if format == 'PEM':
328 pem_str = PEM.encode(
329 binary_key, key_type + " KEY",
330 passphrase, randfunc
331 )
332 return tobytes(pem_str)
333 raise ValueError("Unknown key format '%s'. Cannot export the DSA key." % format)
334
335 # Backward-compatibility
336 exportKey = export_key
337 publickey = public_key
338
339 # Methods defined in PyCrypto that we don't support anymore
340
341 def sign(self, M, K):
342 raise NotImplementedError("Use module Crypto.Signature.DSS instead")
343
344 def verify(self, M, signature):
345 raise NotImplementedError("Use module Crypto.Signature.DSS instead")
346
347 def encrypt(self, plaintext, K):
348 raise NotImplementedError
349
350 def decrypt(self, ciphertext):
351 raise NotImplementedError
352
353 def blind(self, M, B):
354 raise NotImplementedError
355
356 def unblind(self, M, B):
357 raise NotImplementedError
358
359 def size(self):
360 raise NotImplementedError
361
362
363 def _generate_domain(L, randfunc):
364 """Generate a new set of DSA domain parameters"""
365
366 N = { 1024:160, 2048:224, 3072:256 }.get(L)
367 if N is None:
368 raise ValueError("Invalid modulus length (%d)" % L)
369
370 outlen = SHA256.digest_size * 8
371 n = (L + outlen - 1) // outlen - 1 # ceil(L/outlen) -1
372 b_ = L - 1 - (n * outlen)
373
374 # Generate q (A.1.1.2)
375 q = Integer(4)
376 upper_bit = 1 << (N - 1)
377 while test_probable_prime(q, randfunc) != PROBABLY_PRIME:
378 seed = randfunc(64)
379 U = Integer.from_bytes(SHA256.new(seed).digest()) & (upper_bit - 1)
380 q = U | upper_bit | 1
381
382 assert(q.size_in_bits() == N)
383
384 # Generate p (A.1.1.2)
385 offset = 1
386 upper_bit = 1 << (L - 1)
387 while True:
388 V = [ SHA256.new(seed + Integer(offset + j).to_bytes()).digest()
389 for j in iter_range(n + 1) ]
390 V = [ Integer.from_bytes(v) for v in V ]
391 W = sum([V[i] * (1 << (i * outlen)) for i in iter_range(n)],
392 (V[n] & ((1 << b_) - 1)) * (1 << (n * outlen)))
393
394 X = Integer(W + upper_bit) # 2^{L-1} < X < 2^{L}
395 assert(X.size_in_bits() == L)
396
397 c = X % (q * 2)
398 p = X - (c - 1) # 2q divides (p-1)
399 if p.size_in_bits() == L and \
400 test_probable_prime(p, randfunc) == PROBABLY_PRIME:
401 break
402 offset += n + 1
403
404 # Generate g (A.2.3, index=1)
405 e = (p - 1) // q
406 for count in itertools.count(1):
407 U = seed + b"ggen" + bchr(1) + Integer(count).to_bytes()
408 W = Integer.from_bytes(SHA256.new(U).digest())
409 g = pow(W, e, p)
410 if g != 1:
411 break
412
413 return (p, q, g, seed)
414
415
416 def generate(bits, randfunc=None, domain=None):
417 """Generate a new DSA key pair.
418
419 The algorithm follows Appendix A.1/A.2 and B.1 of `FIPS 186-4`_,
420 respectively for domain generation and key pair generation.
421
422 Args:
423 bits (integer):
424 Key length, or size (in bits) of the DSA modulus *p*.
425 It must be 1024, 2048 or 3072.
426
427 randfunc (callable):
428 Random number generation function; it accepts a single integer N
429 and return a string of random data N bytes long.
430 If not specified, :func:`Crypto.Random.get_random_bytes` is used.
431
432 domain (tuple):
433 The DSA domain parameters *p*, *q* and *g* as a list of 3
434 integers. Size of *p* and *q* must comply to `FIPS 186-4`_.
435 If not specified, the parameters are created anew.
436
437 Returns:
438 :class:`DsaKey` : a new DSA key object
439
440 Raises:
441 ValueError : when **bits** is too little, too big, or not a multiple of 64.
442
443 .. _FIPS 186-4: http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
444 """
445
446 if randfunc is None:
447 randfunc = Random.get_random_bytes
448
449 if domain:
450 p, q, g = map(Integer, domain)
451
452 ## Perform consistency check on domain parameters
453 # P and Q must be prime
454 fmt_error = test_probable_prime(p) == COMPOSITE
455 fmt_error |= test_probable_prime(q) == COMPOSITE
456 # Verify Lagrange's theorem for sub-group
457 fmt_error |= ((p - 1) % q) != 0
458 fmt_error |= g <= 1 or g >= p
459 fmt_error |= pow(g, q, p) != 1
460 if fmt_error:
461 raise ValueError("Invalid DSA domain parameters")
462 else:
463 p, q, g, _ = _generate_domain(bits, randfunc)
464
465 L = p.size_in_bits()
466 N = q.size_in_bits()
467
468 if L != bits:
469 raise ValueError("Mismatch between size of modulus (%d)"
470 " and 'bits' parameter (%d)" % (L, bits))
471
472 if (L, N) not in [(1024, 160), (2048, 224),
473 (2048, 256), (3072, 256)]:
474 raise ValueError("Lengths of p and q (%d, %d) are not compatible"
475 "to FIPS 186-3" % (L, N))
476
477 if not 1 < g < p:
478 raise ValueError("Incorrent DSA generator")
479
480 # B.1.1
481 c = Integer.random(exact_bits=N + 64, randfunc=randfunc)
482 x = c % (q - 1) + 1 # 1 <= x <= q-1
483 y = pow(g, x, p)
484
485 key_dict = { 'y':y, 'g':g, 'p':p, 'q':q, 'x':x }
486 return DsaKey(key_dict)
487
488
489 def construct(tup, consistency_check=True):
490 """Construct a DSA key from a tuple of valid DSA components.
491
492 Args:
493 tup (tuple):
494 A tuple of long integers, with 4 or 5 items
495 in the following order:
496
497 1. Public key (*y*).
498 2. Sub-group generator (*g*).
499 3. Modulus, finite field order (*p*).
500 4. Sub-group order (*q*).
501 5. Private key (*x*). Optional.
502
503 consistency_check (boolean):
504 If ``True``, the library will verify that the provided components
505 fulfil the main DSA properties.
506
507 Raises:
508 ValueError: when the key being imported fails the most basic DSA validity checks.
509
510 Returns:
511 :class:`DsaKey` : a DSA key object
512 """
513
514 key_dict = dict(zip(('y', 'g', 'p', 'q', 'x'), map(Integer, tup)))
515 key = DsaKey(key_dict)
516
517 fmt_error = False
518 if consistency_check:
519 # P and Q must be prime
520 fmt_error = test_probable_prime(key.p) == COMPOSITE
521 fmt_error |= test_probable_prime(key.q) == COMPOSITE
522 # Verify Lagrange's theorem for sub-group
523 fmt_error |= ((key.p - 1) % key.q) != 0
524 fmt_error |= key.g <= 1 or key.g >= key.p
525 fmt_error |= pow(key.g, key.q, key.p) != 1
526 # Public key
527 fmt_error |= key.y <= 0 or key.y >= key.p
528 if hasattr(key, 'x'):
529 fmt_error |= key.x <= 0 or key.x >= key.q
530 fmt_error |= pow(key.g, key.x, key.p) != key.y
531
532 if fmt_error:
533 raise ValueError("Invalid DSA key components")
534
535 return key
536
537
538 # Dss-Parms ::= SEQUENCE {
539 # p OCTET STRING,
540 # q OCTET STRING,
541 # g OCTET STRING
542 # }
543 # DSAPublicKey ::= INTEGER -- public key, y
544
545 def _import_openssl_private(encoded, passphrase, params):
546 if params:
547 raise ValueError("DSA private key already comes with parameters")
548 der = DerSequence().decode(encoded, nr_elements=6, only_ints_expected=True)
549 if der[0] != 0:
550 raise ValueError("No version found")
551 tup = [der[comp] for comp in (4, 3, 1, 2, 5)]
552 return construct(tup)
553
554
555 def _import_subjectPublicKeyInfo(encoded, passphrase, params):
556
557 algoid, encoded_key, emb_params = _expand_subject_public_key_info(encoded)
558 if algoid != oid:
559 raise ValueError("No DSA subjectPublicKeyInfo")
560 if params and emb_params:
561 raise ValueError("Too many DSA parameters")
562
563 y = DerInteger().decode(encoded_key).value
564 p, q, g = list(DerSequence().decode(params or emb_params))
565 tup = (y, g, p, q)
566 return construct(tup)
567
568
569 def _import_x509_cert(encoded, passphrase, params):
570
571 sp_info = _extract_subject_public_key_info(encoded)
572 return _import_subjectPublicKeyInfo(sp_info, None, params)
573
574
575 def _import_pkcs8(encoded, passphrase, params):
576 if params:
577 raise ValueError("PKCS#8 already includes parameters")
578 k = PKCS8.unwrap(encoded, passphrase)
579 if k[0] != oid:
580 raise ValueError("No PKCS#8 encoded DSA key")
581 x = DerInteger().decode(k[1]).value
582 p, q, g = list(DerSequence().decode(k[2]))
583 tup = (pow(g, x, p), g, p, q, x)
584 return construct(tup)
585
586
587 def _import_key_der(key_data, passphrase, params):
588 """Import a DSA key (public or private half), encoded in DER form."""
589
590 decodings = (_import_openssl_private,
591 _import_subjectPublicKeyInfo,
592 _import_x509_cert,
593 _import_pkcs8)
594
595 for decoding in decodings:
596 try:
597 return decoding(key_data, passphrase, params)
598 except ValueError:
599 pass
600
601 raise ValueError("DSA key format is not supported")
602
603
604 def import_key(extern_key, passphrase=None):
605 """Import a DSA key.
606
607 Args:
608 extern_key (string or byte string):
609 The DSA key to import.
610
611 The following formats are supported for a DSA **public** key:
612
613 - X.509 certificate (binary DER or PEM)
614 - X.509 ``subjectPublicKeyInfo`` (binary DER or PEM)
615 - OpenSSH (ASCII one-liner, see `RFC4253`_)
616
617 The following formats are supported for a DSA **private** key:
618
619 - `PKCS#8`_ ``PrivateKeyInfo`` or ``EncryptedPrivateKeyInfo``
620 DER SEQUENCE (binary or PEM)
621 - OpenSSL/OpenSSH custom format (binary or PEM)
622
623 For details about the PEM encoding, see `RFC1421`_/`RFC1423`_.
624
625 passphrase (string):
626 In case of an encrypted private key, this is the pass phrase
627 from which the decryption key is derived.
628
629 Encryption may be applied either at the `PKCS#8`_ or at the PEM level.
630
631 Returns:
632 :class:`DsaKey` : a DSA key object
633
634 Raises:
635 ValueError : when the given key cannot be parsed (possibly because
636 the pass phrase is wrong).
637
638 .. _RFC1421: http://www.ietf.org/rfc/rfc1421.txt
639 .. _RFC1423: http://www.ietf.org/rfc/rfc1423.txt
640 .. _RFC4253: http://www.ietf.org/rfc/rfc4253.txt
641 .. _PKCS#8: http://www.ietf.org/rfc/rfc5208.txt
642 """
643
644 extern_key = tobytes(extern_key)
645 if passphrase is not None:
646 passphrase = tobytes(passphrase)
647
648 if extern_key.startswith(b'-----'):
649 # This is probably a PEM encoded key
650 (der, marker, enc_flag) = PEM.decode(tostr(extern_key), passphrase)
651 if enc_flag:
652 passphrase = None
653 return _import_key_der(der, passphrase, None)
654
655 if extern_key.startswith(b'ssh-dss '):
656 # This is probably a public OpenSSH key
657 keystring = binascii.a2b_base64(extern_key.split(b' ')[1])
658 keyparts = []
659 while len(keystring) > 4:
660 length = struct.unpack(">I", keystring[:4])[0]
661 keyparts.append(keystring[4:4 + length])
662 keystring = keystring[4 + length:]
663 if keyparts[0] == b"ssh-dss":
664 tup = [Integer.from_bytes(keyparts[x]) for x in (4, 3, 1, 2)]
665 return construct(tup)
666
667 if len(extern_key) > 0 and bord(extern_key[0]) == 0x30:
668 # This is probably a DER encoded key
669 return _import_key_der(extern_key, passphrase, None)
670
671 raise ValueError("DSA key format is not supported")
672
673
674 # Backward compatibility
675 importKey = import_key
676
677 #: `Object ID`_ for a DSA key.
678 #:
679 #: id-dsa ID ::= { iso(1) member-body(2) us(840) x9-57(10040) x9cm(4) 1 }
680 #:
681 #: .. _`Object ID`: http://www.alvestrand.no/objectid/1.2.840.10040.4.1.html
682 oid = "1.2.840.10040.4.1"