Debian Codegraph @

lib/Crypto/Signature/pss.py

raw symbols SCIP
1 # ===================================================================
2 #
3 # Copyright (c) 2014, Legrandin <[email protected]>
4 # All rights reserved.
5 #
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions
8 # are met:
9 #
10 # 1. Redistributions of source code must retain the above copyright
11 # notice, this list of conditions and the following disclaimer.
12 # 2. Redistributions in binary form must reproduce the above copyright
13 # notice, this list of conditions and the following disclaimer in
14 # the documentation and/or other materials provided with the
15 # distribution.
16 #
17 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
20 # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
21 # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
22 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
23 # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25 # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
27 # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28 # POSSIBILITY OF SUCH DAMAGE.
29 # ===================================================================
30
31 from Crypto.Util.py3compat import bchr, bord, iter_range
32 import Crypto.Util.number
33 from Crypto.Util.number import (ceil_div,
34 long_to_bytes,
35 bytes_to_long
36 )
37 from Crypto.Util.strxor import strxor
38 from Crypto import Random
39
40
41 class PSS_SigScheme:
42 """A signature object for ``RSASSA-PSS``.
43 Do not instantiate directly.
44 Use :func:`Crypto.Signature.pss.new`.
45 """
46
47 def __init__(self, key, mgfunc, saltLen, randfunc):
48 """Initialize this PKCS#1 PSS signature scheme object.
49
50 :Parameters:
51 key : an RSA key object
52 If a private half is given, both signature and
53 verification are possible.
54 If a public half is given, only verification is possible.
55 mgfunc : callable
56 A mask generation function that accepts two parameters:
57 a string to use as seed, and the lenth of the mask to
58 generate, in bytes.
59 saltLen : integer
60 Length of the salt, in bytes.
61 randfunc : callable
62 A function that returns random bytes.
63 """
64
65 self._key = key
66 self._saltLen = saltLen
67 self._mgfunc = mgfunc
68 self._randfunc = randfunc
69
70 def can_sign(self):
71 """Return ``True`` if this object can be used to sign messages."""
72 return self._key.has_private()
73
74 def sign(self, msg_hash):
75 """Create the PKCS#1 PSS signature of a message.
76
77 This function is also called ``RSASSA-PSS-SIGN`` and
78 it is specified in
79 `section 8.1.1 of RFC8017 <https://tools.ietf.org/html/rfc8017#section-8.1.1>`_.
80
81 :parameter msg_hash:
82 This is an object from the :mod:`Crypto.Hash` package.
83 It has been used to digest the message to sign.
84 :type msg_hash: hash object
85
86 :return: the signature encoded as a *byte string*.
87 :raise ValueError: if the RSA key is not long enough for the given hash algorithm.
88 :raise TypeError: if the RSA key has no private half.
89 """
90
91 # Set defaults for salt length and mask generation function
92 if self._saltLen is None:
93 sLen = msg_hash.digest_size
94 else:
95 sLen = self._saltLen
96
97 if self._mgfunc is None:
98 mgf = lambda x, y: MGF1(x, y, msg_hash)
99 else:
100 mgf = self._mgfunc
101
102 modBits = Crypto.Util.number.size(self._key.n)
103
104 # See 8.1.1 in RFC3447
105 k = ceil_div(modBits, 8) # k is length in bytes of the modulus
106 # Step 1
107 em = _EMSA_PSS_ENCODE(msg_hash, modBits-1, self._randfunc, mgf, sLen)
108 # Step 2a (OS2IP)
109 em_int = bytes_to_long(em)
110 # Step 2b (RSASP1) and Step 2c (I2OSP)
111 signature = self._key._decrypt_to_bytes(em_int)
112 # Verify no faults occurred
113 if em_int != pow(bytes_to_long(signature), self._key.e, self._key.n):
114 raise ValueError("Fault detected in RSA private key operation")
115 return signature
116
117 def verify(self, msg_hash, signature):
118 """Check if the PKCS#1 PSS signature over a message is valid.
119
120 This function is also called ``RSASSA-PSS-VERIFY`` and
121 it is specified in
122 `section 8.1.2 of RFC8037 <https://tools.ietf.org/html/rfc8017#section-8.1.2>`_.
123
124 :parameter msg_hash:
125 The hash that was carried out over the message. This is an object
126 belonging to the :mod:`Crypto.Hash` module.
127 :type parameter: hash object
128
129 :parameter signature:
130 The signature that needs to be validated.
131 :type signature: bytes
132
133 :raise ValueError: if the signature is not valid.
134 """
135
136 # Set defaults for salt length and mask generation function
137 if self._saltLen is None:
138 sLen = msg_hash.digest_size
139 else:
140 sLen = self._saltLen
141 if self._mgfunc:
142 mgf = self._mgfunc
143 else:
144 mgf = lambda x, y: MGF1(x, y, msg_hash)
145
146 modBits = Crypto.Util.number.size(self._key.n)
147
148 # See 8.1.2 in RFC3447
149 k = ceil_div(modBits, 8) # Convert from bits to bytes
150 # Step 1
151 if len(signature) != k:
152 raise ValueError("Incorrect signature")
153 # Step 2a (O2SIP)
154 signature_int = bytes_to_long(signature)
155 # Step 2b (RSAVP1)
156 em_int = self._key._encrypt(signature_int)
157 # Step 2c (I2OSP)
158 emLen = ceil_div(modBits - 1, 8)
159 em = long_to_bytes(em_int, emLen)
160 # Step 3/4
161 _EMSA_PSS_VERIFY(msg_hash, em, modBits-1, mgf, sLen)
162
163
164 def MGF1(mgfSeed, maskLen, hash_gen):
165 """Mask Generation Function, described in `B.2.1 of RFC8017
166 <https://tools.ietf.org/html/rfc8017>`_.
167
168 :param mfgSeed:
169 seed from which the mask is generated
170 :type mfgSeed: byte string
171
172 :param maskLen:
173 intended length in bytes of the mask
174 :type maskLen: integer
175
176 :param hash_gen:
177 A module or a hash object from :mod:`Crypto.Hash`
178 :type hash_object:
179
180 :return: the mask, as a *byte string*
181 """
182
183 T = b""
184 for counter in iter_range(ceil_div(maskLen, hash_gen.digest_size)):
185 c = long_to_bytes(counter, 4)
186 hobj = hash_gen.new()
187 hobj.update(mgfSeed + c)
188 T = T + hobj.digest()
189 assert(len(T) >= maskLen)
190 return T[:maskLen]
191
192
193 def _EMSA_PSS_ENCODE(mhash, emBits, randFunc, mgf, sLen):
194 r"""
195 Implement the ``EMSA-PSS-ENCODE`` function, as defined
196 in PKCS#1 v2.1 (RFC3447, 9.1.1).
197
198 The original ``EMSA-PSS-ENCODE`` actually accepts the message ``M``
199 as input, and hash it internally. Here, we expect that the message
200 has already been hashed instead.
201
202 :Parameters:
203 mhash : hash object
204 The hash object that holds the digest of the message being signed.
205 emBits : int
206 Maximum length of the final encoding, in bits.
207 randFunc : callable
208 An RNG function that accepts as only parameter an int, and returns
209 a string of random bytes, to be used as salt.
210 mgf : callable
211 A mask generation function that accepts two parameters: a string to
212 use as seed, and the lenth of the mask to generate, in bytes.
213 sLen : int
214 Length of the salt, in bytes.
215
216 :Return: An ``emLen`` byte long string that encodes the hash
217 (with ``emLen = \ceil(emBits/8)``).
218
219 :Raise ValueError:
220 When digest or salt length are too big.
221 """
222
223 emLen = ceil_div(emBits, 8)
224
225 # Bitmask of digits that fill up
226 lmask = 0
227 for i in iter_range(8*emLen-emBits):
228 lmask = lmask >> 1 | 0x80
229
230 # Step 1 and 2 have been already done
231 # Step 3
232 if emLen < mhash.digest_size+sLen+2:
233 raise ValueError("Digest or salt length are too long"
234 " for given key size.")
235 # Step 4
236 salt = randFunc(sLen)
237 # Step 5
238 m_prime = bchr(0)*8 + mhash.digest() + salt
239 # Step 6
240 h = mhash.new()
241 h.update(m_prime)
242 # Step 7
243 ps = bchr(0)*(emLen-sLen-mhash.digest_size-2)
244 # Step 8
245 db = ps + bchr(1) + salt
246 # Step 9
247 dbMask = mgf(h.digest(), emLen-mhash.digest_size-1)
248 # Step 10
249 maskedDB = strxor(db, dbMask)
250 # Step 11
251 maskedDB = bchr(bord(maskedDB[0]) & ~lmask) + maskedDB[1:]
252 # Step 12
253 em = maskedDB + h.digest() + bchr(0xBC)
254 return em
255
256
257 def _EMSA_PSS_VERIFY(mhash, em, emBits, mgf, sLen):
258 """
259 Implement the ``EMSA-PSS-VERIFY`` function, as defined
260 in PKCS#1 v2.1 (RFC3447, 9.1.2).
261
262 ``EMSA-PSS-VERIFY`` actually accepts the message ``M`` as input,
263 and hash it internally. Here, we expect that the message has already
264 been hashed instead.
265
266 :Parameters:
267 mhash : hash object
268 The hash object that holds the digest of the message to be verified.
269 em : string
270 The signature to verify, therefore proving that the sender really
271 signed the message that was received.
272 emBits : int
273 Length of the final encoding (em), in bits.
274 mgf : callable
275 A mask generation function that accepts two parameters: a string to
276 use as seed, and the lenth of the mask to generate, in bytes.
277 sLen : int
278 Length of the salt, in bytes.
279
280 :Raise ValueError:
281 When the encoding is inconsistent, or the digest or salt lengths
282 are too big.
283 """
284
285 emLen = ceil_div(emBits, 8)
286
287 # Bitmask of digits that fill up
288 lmask = 0
289 for i in iter_range(8*emLen-emBits):
290 lmask = lmask >> 1 | 0x80
291
292 # Step 1 and 2 have been already done
293 # Step 3
294 if emLen < mhash.digest_size+sLen+2:
295 raise ValueError("Incorrect signature")
296 # Step 4
297 if ord(em[-1:]) != 0xBC:
298 raise ValueError("Incorrect signature")
299 # Step 5
300 maskedDB = em[:emLen-mhash.digest_size-1]
301 h = em[emLen-mhash.digest_size-1:-1]
302 # Step 6
303 if lmask & bord(em[0]):
304 raise ValueError("Incorrect signature")
305 # Step 7
306 dbMask = mgf(h, emLen-mhash.digest_size-1)
307 # Step 8
308 db = strxor(maskedDB, dbMask)
309 # Step 9
310 db = bchr(bord(db[0]) & ~lmask) + db[1:]
311 # Step 10
312 if not db.startswith(bchr(0)*(emLen-mhash.digest_size-sLen-2) + bchr(1)):
313 raise ValueError("Incorrect signature")
314 # Step 11
315 if sLen > 0:
316 salt = db[-sLen:]
317 else:
318 salt = b""
319 # Step 12
320 m_prime = bchr(0)*8 + mhash.digest() + salt
321 # Step 13
322 hobj = mhash.new()
323 hobj.update(m_prime)
324 hp = hobj.digest()
325 # Step 14
326 if h != hp:
327 raise ValueError("Incorrect signature")
328
329
330 def new(rsa_key, **kwargs):
331 """Create an object for making or verifying PKCS#1 PSS signatures.
332
333 :parameter rsa_key:
334 The RSA key to use for signing or verifying the message.
335 This is a :class:`Crypto.PublicKey.RSA` object.
336 Signing is only possible when ``rsa_key`` is a **private** RSA key.
337 :type rsa_key: RSA object
338
339 :Keyword Arguments:
340
341 * *mask_func* (``callable``) --
342 A function that returns the mask (as `bytes`).
343 It must accept two parameters: a seed (as `bytes`)
344 and the length of the data to return.
345
346 If not specified, it will be the function :func:`MGF1` defined in
347 `RFC8017 <https://tools.ietf.org/html/rfc8017#page-67>`_ and
348 combined with the same hash algorithm applied to the
349 message to sign or verify.
350
351 If you want to use a different function, for instance still :func:`MGF1`
352 but together with another hash, you can do::
353
354 from Crypto.Hash import SHA256
355 from Crypto.Signature.pss import MGF1
356 mgf = lambda x, y: MGF1(x, y, SHA256)
357
358 * *salt_bytes* (``integer``) --
359 Length of the salt, in bytes.
360 It is a value between 0 and ``emLen - hLen - 2``, where ``emLen``
361 is the size of the RSA modulus and ``hLen`` is the size of the digest
362 applied to the message to sign or verify.
363
364 The salt is generated internally, you don't need to provide it.
365
366 If not specified, the salt length will be ``hLen``.
367 If it is zero, the signature scheme becomes deterministic.
368
369 Note that in some implementations such as OpenSSL the default
370 salt length is ``emLen - hLen - 2`` (even though it is not more
371 secure than ``hLen``).
372
373 * *rand_func* (``callable``) --
374 A function that returns random ``bytes``, of the desired length.
375 The default is :func:`Crypto.Random.get_random_bytes`.
376
377 :return: a :class:`PSS_SigScheme` signature object
378 """
379
380 mask_func = kwargs.pop("mask_func", None)
381 salt_len = kwargs.pop("salt_bytes", None)
382 rand_func = kwargs.pop("rand_func", None)
383 if rand_func is None:
384 rand_func = Random.get_random_bytes
385 if kwargs:
386 raise ValueError("Unknown keywords: " + str(kwargs.keys()))
387 return PSS_SigScheme(rsa_key, mask_func, salt_len, rand_func)