Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/scapy/layers/tls/crypto/pkcs1.py: 20%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

123 statements  

1# SPDX-License-Identifier: GPL-2.0-only 

2# This file is part of Scapy 

3# See https://scapy.net/ for more information 

4# Copyright (C) 2008 Arnaud Ebalard <arno@natisbad.org> 

5# 2015, 2016, 2017 Maxence Tury <maxence.tury@ssi.gouv.fr> 

6 

7""" 

8PKCS #1 methods as defined in RFC 3447. 

9 

10We cannot rely solely on the cryptography library, because the openssl package 

11used by the cryptography library may not implement the md5-sha1 hash, as with 

12Ubuntu or OSX. This is why we reluctantly keep some legacy crypto here. 

13""" 

14 

15from scapy.compat import bytes_encode, hex_bytes, bytes_hex 

16 

17from scapy.config import conf, crypto_validator 

18from scapy.error import warning 

19from scapy.layers.tls.crypto.hash import _get_hash 

20if conf.crypto_valid: 

21 from cryptography.exceptions import InvalidSignature, UnsupportedAlgorithm 

22 from cryptography.hazmat.backends import default_backend 

23 from cryptography.hazmat.primitives import hashes 

24 from cryptography.hazmat.primitives.asymmetric import padding 

25 

26 

27##################################################################### 

28# Some helpers 

29##################################################################### 

30 

31def pkcs_os2ip(s): 

32 """ 

33 OS2IP conversion function from RFC 3447. 

34 

35 :param s: octet string to be converted 

36 :return: n, the corresponding nonnegative integer 

37 """ 

38 return int(bytes_hex(s), 16) 

39 

40 

41def pkcs_i2osp(n, sLen): 

42 """ 

43 I2OSP conversion function from RFC 3447. 

44 The length parameter allows the function to perform the padding needed. 

45 Note that the user is responsible for providing a sufficient xLen. 

46 

47 :param n: nonnegative integer to be converted 

48 :param sLen: intended length of the resulting octet string 

49 :return: corresponding octet string 

50 """ 

51 # if n >= 256**sLen: 

52 # raise Exception("Integer too large for provided sLen %d" % sLen) 

53 fmt = "%%0%dx" % (2 * sLen) 

54 return hex_bytes(fmt % n) 

55 

56 

57def pkcs_ilen(n): 

58 """ 

59 This is a log base 256 which determines the minimum octet string 

60 length for unequivocal representation of integer n by pkcs_i2osp. 

61 """ 

62 i = 0 

63 while n > 0: 

64 n >>= 8 

65 i += 1 

66 return i 

67 

68 

69@crypto_validator 

70def _legacy_pkcs1_v1_5_encode_md5_sha1(M, emLen): 

71 """ 

72 Legacy method for PKCS1 v1.5 encoding with MD5-SHA1 hash. 

73 """ 

74 M = bytes_encode(M) 

75 md5_hash = hashes.Hash(_get_hash("md5"), backend=default_backend()) 

76 md5_hash.update(M) 

77 sha1_hash = hashes.Hash(_get_hash("sha1"), backend=default_backend()) 

78 sha1_hash.update(M) 

79 H = md5_hash.finalize() + sha1_hash.finalize() 

80 if emLen < 36 + 11: 

81 warning("pkcs_emsa_pkcs1_v1_5_encode: " 

82 "intended encoded message length too short") 

83 return None 

84 PS = b'\xff' * (emLen - 36 - 3) 

85 return b'\x00' + b'\x01' + PS + b'\x00' + H 

86 

87 

88##################################################################### 

89# Hash and padding helpers 

90##################################################################### 

91 

92if conf.crypto_valid: 

93 def _get_padding(padStr, mgf=padding.MGF1, h=hashes.SHA256, label=None): 

94 if padStr == "pkcs": 

95 return padding.PKCS1v15() 

96 elif padStr == "pss": 

97 # Can't find where this is written, but we have to use the digest 

98 # size instead of the automatic padding.PSS.MAX_LENGTH. 

99 return padding.PSS(mgf=mgf(h), salt_length=h.digest_size) 

100 elif padStr == "oaep": 

101 return padding.OAEP(mgf=mgf(h), algorithm=h, label=label) 

102 else: 

103 warning("Key.encrypt(): Unknown padding type (%s)", padStr) 

104 return None 

105 

106 

107##################################################################### 

108# Asymmetric Cryptography wrappers 

109##################################################################### 

110 

111# Make sure that default values are consistent across the whole TLS module, 

112# lest they be explicitly set to None between cert.py and pkcs1.py. 

113 

114class _EncryptAndVerifyRSA(object): 

115 

116 @crypto_validator 

117 def encrypt(self, m, t="pkcs", h="sha256", mgf=None, L=None): 

118 mgf = mgf or padding.MGF1 

119 h = _get_hash(h) 

120 pad = _get_padding(t, mgf, h, L) 

121 return self.pubkey.encrypt(m, pad) 

122 

123 @crypto_validator 

124 def verify(self, M, S, t="pkcs", h="sha256", mgf=None, L=None): 

125 M = bytes_encode(M) 

126 mgf = mgf or padding.MGF1 

127 try: 

128 h = _get_hash(h) 

129 except KeyError: 

130 warning("Cannot verify unknown hash format: %s" % h) 

131 return False 

132 pad = _get_padding(t, mgf, h, L) 

133 try: 

134 try: 

135 self.pubkey.verify(S, M, pad, h) 

136 except UnsupportedAlgorithm: 

137 if t != "pkcs" and h != "md5-sha1": 

138 raise UnsupportedAlgorithm("RSA verification with %s" % h) 

139 self._legacy_verify_md5_sha1(M, S) 

140 return True 

141 except InvalidSignature: 

142 return False 

143 

144 def _legacy_verify_md5_sha1(self, M, S): 

145 k = self._modulusLen // 8 

146 if len(S) != k: 

147 warning("invalid signature (len(S) != k)") 

148 return False 

149 s = pkcs_os2ip(S) 

150 n = self._modulus 

151 if s > n - 1: 

152 warning("Key._rsaep() expects a long between 0 and n-1") 

153 return None 

154 m = pow(s, self._pubExp, n) 

155 EM = pkcs_i2osp(m, k) 

156 EMPrime = _legacy_pkcs1_v1_5_encode_md5_sha1(M, k) 

157 if EMPrime is None: 

158 warning("Key._rsassa_pkcs1_v1_5_verify(): unable to encode.") 

159 return False 

160 return EM == EMPrime 

161 

162 

163class _DecryptAndSignRSA(object): 

164 

165 @crypto_validator 

166 def decrypt(self, C, t="pkcs", h="sha256", mgf=None, L=None): 

167 mgf = mgf or padding.MGF1 

168 h = _get_hash(h) 

169 pad = _get_padding(t, mgf, h, L) 

170 return self.key.decrypt(C, pad) 

171 

172 @crypto_validator 

173 def sign(self, M, t="pkcs", h="sha256", mgf=None, L=None): 

174 M = bytes_encode(M) 

175 mgf = mgf or padding.MGF1 

176 h = _get_hash(h) 

177 pad = _get_padding(t, mgf, h, L) 

178 try: 

179 return self.key.sign(M, pad, h) 

180 except UnsupportedAlgorithm: 

181 if t != "pkcs" and h != "md5-sha1": 

182 raise UnsupportedAlgorithm("RSA signature with %s" % h) 

183 return self._legacy_sign_md5_sha1(M) 

184 

185 def _legacy_sign_md5_sha1(self, M): 

186 M = bytes_encode(M) 

187 k = self._modulusLen // 8 

188 EM = _legacy_pkcs1_v1_5_encode_md5_sha1(M, k) 

189 if EM is None: 

190 warning("Key._rsassa_pkcs1_v1_5_sign(): unable to encode") 

191 return None 

192 m = pkcs_os2ip(EM) 

193 n = self._modulus 

194 if m > n - 1: 

195 warning("Key._rsaep() expects a long between 0 and n-1") 

196 return None 

197 privExp = self.key.private_numbers().d 

198 s = pow(m, privExp, n) 

199 return pkcs_i2osp(s, k)