Debian Codegraph @

lib/Crypto/Signature/DSS.py

raw symbols SCIP
1 #
2 # Signature/DSS.py : DSS.py
3 #
4 # ===================================================================
5 #
6 # Copyright (c) 2014, Legrandin <[email protected]>
7 # All rights reserved.
8 #
9 # Redistribution and use in source and binary forms, with or without
10 # modification, are permitted provided that the following conditions
11 # are met:
12 #
13 # 1. Redistributions of source code must retain the above copyright
14 # notice, this list of conditions and the following disclaimer.
15 # 2. Redistributions in binary form must reproduce the above copyright
16 # notice, this list of conditions and the following disclaimer in
17 # the documentation and/or other materials provided with the
18 # distribution.
19 #
20 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23 # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
24 # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26 # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
28 # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
30 # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31 # POSSIBILITY OF SUCH DAMAGE.
32 # ===================================================================
33
34 from Crypto.Util.asn1 import DerSequence
35 from Crypto.Util.number import long_to_bytes
36 from Crypto.Math.Numbers import Integer
37
38 from Crypto.Hash import HMAC
39 from Crypto.PublicKey.ECC import EccKey
40 from Crypto.PublicKey.DSA import DsaKey
41
42 __all__ = ['DssSigScheme', 'new']
43
44
45 class DssSigScheme(object):
46 """A (EC)DSA signature object.
47 Do not instantiate directly.
48 Use :func:`Crypto.Signature.DSS.new`.
49 """
50
51 def __init__(self, key, encoding, order):
52 """Create a new Digital Signature Standard (DSS) object.
53
54 Do not instantiate this object directly,
55 use `Crypto.Signature.DSS.new` instead.
56 """
57
58 self._key = key
59 self._encoding = encoding
60 self._order = order
61
62 self._order_bits = self._order.size_in_bits()
63 self._order_bytes = (self._order_bits - 1) // 8 + 1
64
65 def can_sign(self):
66 """Return ``True`` if this signature object can be used
67 for signing messages."""
68
69 return self._key.has_private()
70
71 def _compute_nonce(self, msg_hash):
72 raise NotImplementedError("To be provided by subclasses")
73
74 def _valid_hash(self, msg_hash):
75 raise NotImplementedError("To be provided by subclasses")
76
77 def sign(self, msg_hash):
78 """Compute the DSA/ECDSA signature of a message.
79
80 Args:
81 msg_hash (hash object):
82 The hash that was carried out over the message.
83 The object belongs to the :mod:`Crypto.Hash` package.
84 Under mode ``'fips-186-3'``, the hash must be a FIPS
85 approved secure hash (SHA-2 or SHA-3).
86
87 :return: The signature as ``bytes``
88 :raise ValueError: if the hash algorithm is incompatible to the (EC)DSA key
89 :raise TypeError: if the (EC)DSA key has no private half
90 """
91
92 if not self._key.has_private():
93 raise TypeError("Private key is needed to sign")
94
95 if not self._valid_hash(msg_hash):
96 raise ValueError("Hash is not sufficiently strong")
97
98 # Generate the nonce k (critical!)
99 nonce = self._compute_nonce(msg_hash)
100
101 # Perform signature using the raw API
102 z = Integer.from_bytes(msg_hash.digest()[:self._order_bytes])
103 sig_pair = self._key._sign(z, nonce)
104
105 # Encode the signature into a single byte string
106 if self._encoding == 'binary':
107 output = b"".join([long_to_bytes(x, self._order_bytes)
108 for x in sig_pair])
109 else:
110 # Dss-sig ::= SEQUENCE {
111 # r INTEGER,
112 # s INTEGER
113 # }
114 # Ecdsa-Sig-Value ::= SEQUENCE {
115 # r INTEGER,
116 # s INTEGER
117 # }
118 output = DerSequence(sig_pair).encode()
119
120 return output
121
122 def verify(self, msg_hash, signature):
123 """Check if a certain (EC)DSA signature is authentic.
124
125 Args:
126 msg_hash (hash object):
127 The hash that was carried out over the message.
128 This is an object belonging to the :mod:`Crypto.Hash` module.
129 Under mode ``'fips-186-3'``, the hash must be a FIPS
130 approved secure hash (SHA-2 or SHA-3).
131
132 signature (``bytes``):
133 The signature that needs to be validated.
134
135 :raise ValueError: if the signature is not authentic
136 """
137
138 if not self._valid_hash(msg_hash):
139 raise ValueError("Hash is not sufficiently strong")
140
141 if self._encoding == 'binary':
142 if len(signature) != (2 * self._order_bytes):
143 raise ValueError("The signature is not authentic (length)")
144 r_prime, s_prime = [Integer.from_bytes(x)
145 for x in (signature[:self._order_bytes],
146 signature[self._order_bytes:])]
147 else:
148 try:
149 der_seq = DerSequence().decode(signature, strict=True)
150 except (ValueError, IndexError):
151 raise ValueError("The signature is not authentic (DER)")
152 if len(der_seq) != 2 or not der_seq.hasOnlyInts():
153 raise ValueError("The signature is not authentic (DER content)")
154 r_prime, s_prime = Integer(der_seq[0]), Integer(der_seq[1])
155
156 if not (0 < r_prime < self._order) or not (0 < s_prime < self._order):
157 raise ValueError("The signature is not authentic (d)")
158
159 z = Integer.from_bytes(msg_hash.digest()[:self._order_bytes])
160 result = self._key._verify(z, (r_prime, s_prime))
161 if not result:
162 raise ValueError("The signature is not authentic")
163 # Make PyCrypto code to fail
164 return False
165
166
167 class DeterministicDsaSigScheme(DssSigScheme):
168 # Also applicable to ECDSA
169
170 def __init__(self, key, encoding, order, private_key):
171 super(DeterministicDsaSigScheme, self).__init__(key, encoding, order)
172 self._private_key = private_key
173
174 def _bits2int(self, bstr):
175 """See 2.3.2 in RFC6979"""
176
177 result = Integer.from_bytes(bstr)
178 q_len = self._order.size_in_bits()
179 b_len = len(bstr) * 8
180 if b_len > q_len:
181 # Only keep leftmost q_len bits
182 result >>= (b_len - q_len)
183 return result
184
185 def _int2octets(self, int_mod_q):
186 """See 2.3.3 in RFC6979"""
187
188 assert 0 < int_mod_q < self._order
189 return long_to_bytes(int_mod_q, self._order_bytes)
190
191 def _bits2octets(self, bstr):
192 """See 2.3.4 in RFC6979"""
193
194 z1 = self._bits2int(bstr)
195 if z1 < self._order:
196 z2 = z1
197 else:
198 z2 = z1 - self._order
199 return self._int2octets(z2)
200
201 def _compute_nonce(self, mhash):
202 """Generate k in a deterministic way"""
203
204 # See section 3.2 in RFC6979.txt
205 # Step a
206 h1 = mhash.digest()
207 # Step b
208 mask_v = b'\x01' * mhash.digest_size
209 # Step c
210 nonce_k = b'\x00' * mhash.digest_size
211
212 for int_oct in (b'\x00', b'\x01'):
213 # Step d/f
214 nonce_k = HMAC.new(nonce_k,
215 mask_v + int_oct +
216 self._int2octets(self._private_key) +
217 self._bits2octets(h1), mhash).digest()
218 # Step e/g
219 mask_v = HMAC.new(nonce_k, mask_v, mhash).digest()
220
221 nonce = -1
222 while not (0 < nonce < self._order):
223 # Step h.C (second part)
224 if nonce != -1:
225 nonce_k = HMAC.new(nonce_k, mask_v + b'\x00',
226 mhash).digest()
227 mask_v = HMAC.new(nonce_k, mask_v, mhash).digest()
228
229 # Step h.A
230 mask_t = b""
231
232 # Step h.B
233 while len(mask_t) < self._order_bytes:
234 mask_v = HMAC.new(nonce_k, mask_v, mhash).digest()
235 mask_t += mask_v
236
237 # Step h.C (first part)
238 nonce = self._bits2int(mask_t)
239 return nonce
240
241 def _valid_hash(self, msg_hash):
242 return True
243
244
245 class FipsDsaSigScheme(DssSigScheme):
246
247 #: List of L (bit length of p) and N (bit length of q) combinations
248 #: that are allowed by FIPS 186-3. The security level is provided in
249 #: Table 2 of FIPS 800-57 (rev3).
250 _fips_186_3_L_N = (
251 (1024, 160), # 80 bits (SHA-1 or stronger)
252 (2048, 224), # 112 bits (SHA-224 or stronger)
253 (2048, 256), # 128 bits (SHA-256 or stronger)
254 (3072, 256) # 256 bits (SHA-512)
255 )
256
257 def __init__(self, key, encoding, order, randfunc):
258 super(FipsDsaSigScheme, self).__init__(key, encoding, order)
259 self._randfunc = randfunc
260
261 L = Integer(key.p).size_in_bits()
262 if (L, self._order_bits) not in self._fips_186_3_L_N:
263 error = ("L/N (%d, %d) is not compliant to FIPS 186-3"
264 % (L, self._order_bits))
265 raise ValueError(error)
266
267 def _compute_nonce(self, msg_hash):
268 # hash is not used
269 return Integer.random_range(min_inclusive=1,
270 max_exclusive=self._order,
271 randfunc=self._randfunc)
272
273 def _valid_hash(self, msg_hash):
274 """Verify that SHA-1, SHA-2 or SHA-3 are used"""
275 return (msg_hash.oid == "1.3.14.3.2.26" or
276 msg_hash.oid.startswith("2.16.840.1.101.3.4.2."))
277
278
279 class FipsEcDsaSigScheme(DssSigScheme):
280
281 def __init__(self, key, encoding, order, randfunc):
282 super(FipsEcDsaSigScheme, self).__init__(key, encoding, order)
283 self._randfunc = randfunc
284
285 def _compute_nonce(self, msg_hash):
286 return Integer.random_range(min_inclusive=1,
287 max_exclusive=self._key._curve.order,
288 randfunc=self._randfunc)
289
290 def _valid_hash(self, msg_hash):
291 """Verify that the strength of the hash matches or exceeds
292 the strength of the EC. We fail if the hash is too weak."""
293
294 modulus_bits = self._key.pointQ.size_in_bits()
295
296 # SHS: SHA-2, SHA-3, truncated SHA-512
297 sha224 = ("2.16.840.1.101.3.4.2.4", "2.16.840.1.101.3.4.2.7", "2.16.840.1.101.3.4.2.5")
298 sha256 = ("2.16.840.1.101.3.4.2.1", "2.16.840.1.101.3.4.2.8", "2.16.840.1.101.3.4.2.6")
299 sha384 = ("2.16.840.1.101.3.4.2.2", "2.16.840.1.101.3.4.2.9")
300 sha512 = ("2.16.840.1.101.3.4.2.3", "2.16.840.1.101.3.4.2.10")
301 shs = sha224 + sha256 + sha384 + sha512
302
303 try:
304 result = msg_hash.oid in shs
305 except AttributeError:
306 result = False
307 return result
308
309
310 def new(key, mode, encoding='binary', randfunc=None):
311 """Create a signature object :class:`DssSigScheme` that
312 can perform (EC)DSA signature or verification.
313
314 .. note::
315 Refer to `NIST SP 800 Part 1 Rev 4`_ (or newer release) for an
316 overview of the recommended key lengths.
317
318 Args:
319 key (:class:`Crypto.PublicKey.DSA` or :class:`Crypto.PublicKey.ECC`):
320 The key to use for computing the signature (*private* keys only)
321 or for verifying one.
322 For DSA keys, let ``L`` and ``N`` be the bit lengths of the modulus ``p``
323 and of ``q``: the pair ``(L,N)`` must appear in the following list,
324 in compliance to section 4.2 of `FIPS 186-4`_:
325
326 - (1024, 160) *legacy only; do not create new signatures with this*
327 - (2048, 224) *deprecated; do not create new signatures with this*
328 - (2048, 256)
329 - (3072, 256)
330
331 For ECC, only keys over P-224, P-256, P-384, and P-521 are accepted.
332
333 mode (string):
334 The parameter can take these values:
335
336 - ``'fips-186-3'``. The signature generation is randomized and carried out
337 according to `FIPS 186-3`_: the nonce ``k`` is taken from the RNG.
338 - ``'deterministic-rfc6979'``. The signature generation is not
339 randomized. See RFC6979_.
340
341 encoding (string):
342 How the signature is encoded. This value determines the output of
343 :meth:`sign` and the input to :meth:`verify`.
344
345 The following values are accepted:
346
347 - ``'binary'`` (default), the signature is the raw concatenation
348 of ``r`` and ``s``. It is defined in the IEEE P.1363 standard.
349 For DSA, the size in bytes of the signature is ``N/4`` bytes
350 (e.g. 64 for ``N=256``).
351 For ECDSA, the signature is always twice the length of a point
352 coordinate (e.g. 64 bytes for P-256).
353
354 - ``'der'``, the signature is a ASN.1 DER SEQUENCE
355 with two INTEGERs (``r`` and ``s``). It is defined in RFC3279_.
356 The size of the signature is variable.
357
358 randfunc (callable):
359 A function that returns random ``bytes``, of a given length.
360 If omitted, the internal RNG is used.
361 Only applicable for the *'fips-186-3'* mode.
362
363 .. _FIPS 186-3: http://csrc.nist.gov/publications/fips/fips186-3/fips_186-3.pdf
364 .. _FIPS 186-4: http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
365 .. _NIST SP 800 Part 1 Rev 4: http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-57pt1r4.pdf
366 .. _RFC6979: http://tools.ietf.org/html/rfc6979
367 .. _RFC3279: https://tools.ietf.org/html/rfc3279#section-2.2.2
368 """
369
370 # The goal of the 'mode' parameter is to avoid to
371 # have the current version of the standard as default.
372 #
373 # Over time, such version will be superseded by (for instance)
374 # FIPS 186-4 and it will be odd to have -3 as default.
375
376 if encoding not in ('binary', 'der'):
377 raise ValueError("Unknown encoding '%s'" % encoding)
378
379 if isinstance(key, EccKey):
380 order = key._curve.order
381 private_key_attr = 'd'
382 if key._curve.name == "ed25519":
383 raise ValueError("ECC key is not on a NIST P curve")
384 elif isinstance(key, DsaKey):
385 order = Integer(key.q)
386 private_key_attr = 'x'
387 else:
388 raise ValueError("Unsupported key type " + str(type(key)))
389
390 if key.has_private():
391 private_key = getattr(key, private_key_attr)
392 else:
393 private_key = None
394
395 if mode == 'deterministic-rfc6979':
396 return DeterministicDsaSigScheme(key, encoding, order, private_key)
397 elif mode == 'fips-186-3':
398 if isinstance(key, EccKey):
399 return FipsEcDsaSigScheme(key, encoding, order, randfunc)
400 else:
401 return FipsDsaSigScheme(key, encoding, order, randfunc)
402 else:
403 raise ValueError("Unknown DSS mode '%s'" % mode)